/*
 * MIT License
 *
 * Copyright (c) 2018 Billy Yuan
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.billyyccc.database;

/**
 * @author Billy Yuan
 */
public class DatabaseServiceTestBase {
  //TODO Add an embedded postgres server for data-service layer unit tests.
}

Add a db service layer test stub


package checksum;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class ChecksumGenerator
{
  private MessageDigest digester;

  /**
   *  Creates a new ChecksumGenerator-object which uses the given algorithm.
   *
   *  @param algorithm algorithm to use
   */
  public ChecksumGenerator(String algorithm) throws NoSuchAlgorithmException
  {
    digester = MessageDigest.getInstance(algorithm.toUpperCase());
  }

  /**
   *  Returns the checksum for data in given input stream.
   *
   *  @param input  input stream
   *  @param length length of data
   *  @return       checksum for data in given input stream
   */
  public byte[] getChecksum(InputStream in, long length) throws IOException
  {
    DigestInputStream input = new DigestInputStream(in, digester);

    byte[] buffer = new byte[262144];
    long bytesRead = 0;

    while (bytesRead < length)
      bytesRead += input.read(buffer);

    return digester.digest();
  }

  /**
   *  Prints help text.
   */
  private static void printHelpText()
  {
    System.out.println("Usage:\n" +
                       "java checksum.ChecksumGenerator ALGORITHM FILE\n" +
                       "\tALGORITHM - The Hash-algorithm to use (\"SHA-1\", \"SHA-256\", \"MD5\")\n" +
                       "\tFILE - The file to hash");
  }

  /**
   *  Returns a String-representation of given checksum.
   *
   *  @param checksum checksum byte-array
   *  @return         String-representation of given checksum
   */
  public static String getChecksumString(byte[] checksum)
  {
    String checksumString = "";
    for (byte b : checksum)
      checksumString += String.format("%x", b);

    return checksumString;
  }

  public static void main(String[] args)
  {
    if (args.length > 1)
    {
      String algorithm = args[0],
             fileName  = args[1];

      File file = new File(fileName);

      if (file.exists())
      {
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(file)))
        {
          ChecksumGenerator generator = new ChecksumGenerator(algorithm);
          String checksum = getChecksumString(generator.getChecksum(in, file.length()));

          System.out.println(checksum);
        }
        catch (Exception e)
        {
          System.err.println(e.getMessage());
          e.printStackTrace();
        }
      }
      else
      {
        System.err.printf("The file \"%s\" does not exist!\n", fileName);
      }
    }
    else
      printHelpText();
  }
}

Implement a simple checksum generator


import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

public class RegExConverter {

	/** Operators precedence map. */
	private static final Map<Character, Integer> precedenceMap;
	static {
		Map<Character, Integer> map = new HashMap<Character, Integer>();
		map.put('(', 1);
		map.put('|', 2);
		map.put('&', 3); // explicit concatenation operator
		map.put('?', 4);
		map.put('*', 4);
		map.put('+', 4);
		map.put('^', 5);
		precedenceMap = Collections.unmodifiableMap(map);
	};

	/**
	 * Get character precedence.
	 *
	 * @param c character
	 * @return corresponding precedence
	 */
	private static Integer getPrecedence(Character c) {
		Integer precedence = precedenceMap.get(c);
		return precedence == null ? 6 : precedence;
	}

	/**
	 * Transform regular expression by inserting a '&' as explicit concatenation
	 * operator.
	 */
	public static String formatRegEx(String regex) {
		// TODO
		return null;
	}

	/**
	 * Convert regular expression from infix to postfix notation using
	 * Shunting-yard algorithm.
	 *
	 * @param regex infix notation
	 * @return postfix notation
	 */
	public static String infixToPostfix(String regex) {
		String postfix = new String();

		Stack<Character> stack = new Stack<Character>();

		String formattedRegEx = formatRegEx(regex);

		for (Character c : formattedRegEx.toCharArray()) {
			switch (c) {
				case '(':
					stack.push(c);
					break;

				case ')':
					while (!stack.peek().equals('(')) {
						postfix += stack.pop();
					}
					stack.pop(); // pop '('
					break;

				default:
					while (stack.size() > 0) {
						Character peekedChar = stack.peek();

						Integer peekedCharPrecedence = getPrecedence(peekedChar);
						Integer currentCharPrecedence = getPrecedence(c);

						if (peekedCharPrecedence >= currentCharPrecedence) {
							postfix += stack.pop();
						} else {
							break;
						}
					}
					stack.push(c);
					break;
			}

		}

		while (stack.size() > 0)
			postfix += stack.pop();

		return postfix;
	}
}

Add converter from infix to postfix notation.


/**
 * The {@code distancemetrics} package contains strategy classes to parametrize
 * the way self-organizing maps measure the distance from a neuron to an input
 * vector.  The classes are intended to be created by the user and given to a
 * self-organizing map, which will assume control.  These classes all derive
 * from {@link cs437.som.DistanceMetric} in {@link cs437.som}.
 */
package cs437.som.distancemetrics;

Add a package annotation to distancemetrics.


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2013 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * 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.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.text.io;

import imagej.io.AbstractIOPlugin;
import imagej.io.IOPlugin;
import imagej.text.TextService;

import java.io.File;
import java.io.IOException;

import org.scijava.plugin.Plugin;

/**
 * {@link IOPlugin} for text conversion to HTML.
 *
 * @author Curtis Rueden
 * @see TextService
 */
@Plugin(type = IOPlugin.class)
public class TextIOPlugin extends AbstractIOPlugin<String> {

	// -- IOPlugin methods --

	@Override
	public Class<String> getDataType() {
		return String.class;
	}

	@Override
	public boolean supportsOpen(final String source) {
		final TextService textService = getContext().getService(TextService.class);
		return textService.supports(new File(source));
	}

	@Override
	public String open(final String source) throws IOException {
		if (source == null) return null;
		final TextService textService = getContext().getService(TextService.class);
		return textService.asHTML(new File(source));
	}

}

Add an I/O plugin for text formats


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * 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.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 */
package org.jenetics.internal.util;

import java.util.Optional;
import java.util.function.Predicate;

/**
 * @author Franz Wilhelmstötter
 * @since 3.0
 * @version 3.0 — $Date: 2014-06-28 $
 */
public final class Equality<T> {
	private final T _self;
	private final Optional<T> _other;

	private Equality(final T self, final Optional<T> other) {
		_self = self;
		_other = other;
	}

	public boolean test(final Predicate<T> equality) {
		return _other.filter(o -> o == _self).isPresent() ||
			_other.filter(equality).isPresent();
	}

	public static <T> Equality<T> of(final T self, final Object other) {
		@SuppressWarnings("unchecked")
		final Class<T> type = (Class<T>)self.getClass();
		return new Equality<>(self, cast(type, other));
	}

	private static  Optional cast(final Class type, final Object object) {
		return Optional.ofNullable(object)
			.filter(o -> o.getClass() == type)
			.map(type::cast);
	}
}

Add helper class for implementing 'equals' method.


package aeronicamc.mods.mxtune.gui.widget;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.widget.TextFieldWidget;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.StringTextComponent;

import javax.annotation.Nullable;

public class MXTextFieldWidget extends TextFieldWidget
{
    protected int padding = 0;
    public MXTextFieldWidget(int pMaxLength)
    {
        super(Minecraft.getInstance().font, 0, 0, 0, 0, new StringTextComponent(""));
        this.setMaxLength(pMaxLength);
    }

    public MXTextFieldWidget(FontRenderer pFont, int pX, int pY, int pWidth, int pHeight, ITextComponent pMessage)
    {
        super(pFont, pX, pY, pWidth, pHeight, pMessage);
    }

    public MXTextFieldWidget(FontRenderer pFont, int pX, int pY, int pWidth, int pHeight, @Nullable TextFieldWidget p_i232259_6_, ITextComponent pMessage)
    {
        super(pFont, pX, pY, pWidth, pHeight, p_i232259_6_, pMessage);
    }

    public void setPosition(int pX, int pY)
    {
        this.x = pX;
        this.y = pY;
    }

    public void setLayout(int pX, int pY, int pWidth, int pHeight)
    {
        this.x = pX;
        this.y = pY;
        this.width = pWidth;
        this.height = pHeight;
    }

    public int getLeft()
    {
        return this.x;
    }

    public int getTop()
    {
        return this.y;
    }

    public int getRight()
    {
        return this.x + this.width + padding;
    }

    public int getBottom()
    {
        return this.y + this.height + padding;
    }

    public int getPadding()
    {
        return padding;
    }

    public void setPadding(int padding)
    {
        this.padding = padding;
    }
}

Extend vanilla text widget to allow persistent use. Keeps state across screen resizing.


/*
 * Copyright 2016 Peter Kenji Yamanaka
 *
 * 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.pyamsoft.padlock.dagger.lock;

import com.pyamsoft.padlock.BuildConfig;
import com.pyamsoft.padlock.TestPadLock;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;

@RunWith(RobolectricTestRunner.class)
@Config(application = TestPadLock.class, sdk = 23, constants = BuildConfig.class)
public class LockInteractorTest {

  LockInteractor interactor;

  @Before public void setup() {
    interactor = new LockInteractorImpl() {
    };
  }

  /**
   * Test that the same string encoded twice produces the same result
   * @throws Exception
   */
  @Test public void testEncodeIndentity() throws Exception {
    final String encoded = interactor.encodeSHA256("TEST 1").toBlocking().first();
    assertEquals(encoded, interactor.encodeSHA256("TEST 1").toBlocking().first());
    assertTrue(interactor.checkSubmissionAttempt("TEST 1", encoded).toBlocking().first());
  }

  /**
   * Test that two different strings produces different results
   * @throws Exception
   */
  @Test public void testEncodeCorrectness() throws Exception {
    final String encoded = interactor.encodeSHA256("TEST 1").toBlocking().first();
    assertNotEquals(encoded, interactor.encodeSHA256("RANDOM").toBlocking().first());
    assertFalse(interactor.checkSubmissionAttempt("ANOTHER RANDOM", encoded).toBlocking().first());
  }
}

Add test for lock interactor


package leetcode.valid_parentheses;

public class Solution {
	public boolean isValid(String s) {
		StringBuilder sb = new StringBuilder();
		for(char c : s.toCharArray()){
			switch(c){
			case '(':
				sb.append(c);
				break;
			case '[':
				sb.append(c);
				break;
			case '{':
				sb.append(c);
				break;
			case ')':
				if(sb.length() > 0 && sb.charAt(sb.length() - 1) == '('){
					sb.setLength(sb.length() - 1);
				}else return false;
				break;
			case ']':
				if(sb.length() > 0 && sb.charAt(sb.length() - 1) == '['){
					sb.setLength(sb.length() - 1);
				}else return false;
				break;
			case '}':
				if(sb.length() > 0 && sb.charAt(sb.length() - 1) == '{'){
					sb.setLength(sb.length() - 1);
				}else return false;
				break;
			}
		}
		return sb.length() == 0;
	}

	public static void main(String[] args){
		System.err.println("ans: " + new Solution().isValid("{([][)]()()[][][]{}{}{}}"));
	}
}

Add java solution for 20. Valid Parentheses


package de.tudresden.inf.lat.born.protege.ui;

import java.awt.BorderLayout;

import org.protege.editor.owl.ui.view.cls.AbstractOWLClassViewComponent;
import org.semanticweb.owlapi.model.OWLClass;

import de.tudresden.inf.lat.born.main.BornStarter;

/**
 * This is the Protege view component of BORN.
 *
 * @author Julian Mendez
 */
public class Main extends AbstractOWLClassViewComponent {

	private static final long serialVersionUID = -5363687740449453246L;

	private BornStarter bornStarter = null;

	@Override
	public void disposeView() {
		this.bornStarter.removeListeners();
	}

	/**
	 * Initializes the data and GUI. This method is called when the view is
	 * initialized.
	 */
	@Override
	public void initialiseClassView() {
		this.bornStarter = new BornStarter(getOWLModelManager().getOWLOntologyManager());
		this.setLayout(new BorderLayout());
		add(this.bornStarter.getPanel().getView(), BorderLayout.CENTER);
	}

	@Override
	protected OWLClass updateView(OWLClass selectedClass) {
		return selectedClass;
	}

}

Add class to initialize from Protege


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

package tachyon.worker.block.allocator;

import com.google.common.base.Optional;
import com.google.common.base.Preconditions;

import tachyon.worker.block.BlockMetadataManager;
import tachyon.worker.block.meta.BlockMeta;

/**
 * Naive allocation strategy
 */
public class NaiveAllocator implements Allocator {
  private final BlockMetadataManager mMetadata;

  public NaiveAllocator(BlockMetadataManager metadata) {
    mMetadata = Preconditions.checkNotNull(metadata);
  }

  @Override
  public Optional<BlockMeta> allocateBlock(long userId, long blockId, long blockSize, int tierHint) {
    return mMetadata.addBlockMetaInTier(userId, blockId, blockSize, tierHint);
  }
}

Add a class of a naive implementation of Allocator interface


/*
 * Copyright 2020 Google LLC
 *
 * 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
 *
 *     https://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.android.gnd.ui.settings;

/** These keys should match 1:1 in res/xml/preferences.xml. */
public final class Keys {

  // General
  public static final String UPLOAD_MEDIA = "upload_media";
  public static final String OFFLINE_AREAS = "offline_areas";

  // Help
  public static final String VISIT_WEBSITE = "visit_website";
  public static final String FEEDBACK = "feedback";

  public static final String[] ALL_KEYS = {UPLOAD_MEDIA, OFFLINE_AREAS, VISIT_WEBSITE, FEEDBACK};
}

Add class to manage preference keys


package no.ssb.vtl.model;

/*-
 * ========================LICENSE_START=================================
 * Java VTL
 * %%
 * Copyright (C) 2016 - 2017 Hadrien Kohl
 * %%
 * 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.
 * =========================LICENSE_END==================================
 */

import com.google.common.collect.ImmutableMap;

import java.util.Map;

/**
 * Represents a VTL Function.
 */
public abstract class VTLFunction extends VTLExpression {

    private final Map<String, VTLExpression> context;

    protected VTLFunction(Map<String, VTLExpression> context) {
        this.context = context;
    }

    public static Builder create(Class<? extends VTLObject> returnType) {
        return new Builder(returnType);
    }

    @Override
    public Class<? extends VTLObject> getType() {
        return null;
    }

    @FunctionalInterface
    interface Body {
        VTLObject execute();
    }

    /**
     * Builder for VTLFunction.
     */
    private static class Builder {

        private final Class<? extends VTLObject> type;
        ImmutableMap.Builder<String, Class<? extends VTLObject>> signature;
        ImmutableMap.Builder<String, VTLObject> defaultValues;

        private Builder(Class<? extends VTLObject> type) {
            this.type = type;
        }

        public Builder withArgument(String name, Class<? extends VTLObject> type) {
            signature.put(name, type);
            return this;
        }

        public Builder withArgument(String name, VTLObject defaultValue) {
            defaultValues.put(name, defaultValue);
            return withArgument(name, defaultValue.getClass());
        }

        public VTLFunction build(Map<String, VTLExpression> context) {
            throw new UnsupportedOperationException("TODO");
        }
    }
}

Add a function class to the model


package com.hankcs.hanlp.algorithm;

import com.hankcs.hanlp.corpus.synonym.Synonym;
import com.hankcs.hanlp.dictionary.common.CommonSynonymDictionary.SynonymItem;
import org.junit.Assert;
import org.junit.Test;
import java.util.ArrayList;

public class EditDistanceTest {

    @Test
    public void testComputeCharArray() {
        Assert.assertEquals(2,
            EditDistance.compute("foo".toCharArray(), "oof".toCharArray()));
    }

    @Test
    public void testComputeString() {
        Assert.assertEquals(2, EditDistance.compute("foo", "oof"));
    }

    @Test
    public void testComputeList() {
        ArrayList<SynonymItem> synonymItems1 = new ArrayList<SynonymItem>();
        synonymItems1.add(new SynonymItem(new Synonym("", 32L), null, '='));

        ArrayList<SynonymItem> synonymItems2 = new ArrayList<SynonymItem>();
        synonymItems2.add(new SynonymItem(new Synonym("", 64L), null, '='));

        Assert.assertEquals(32L,
            EditDistance.compute(synonymItems1, synonymItems2));
    }

    @Test
    public void testComputeLong() {
        Assert.assertEquals(3074457345618258602L,
            EditDistance.compute(new long[]{}, new long[]{4L, 0L}));
        Assert.assertEquals(-15,
            EditDistance.compute(new long[]{-16}, new long[]{32}));
        Assert.assertEquals(0,
            EditDistance.compute(new long[]{16}, new long[]{16}));
    }

    @Test
    public void testComputeInt() {
        Assert.assertEquals(715827882,
            EditDistance.compute(new int[]{4, 0}, new int[]{}));
        Assert.assertEquals(6,
            EditDistance.compute(new int[]{4, 0}, new int[]{8, 16}));
        Assert.assertEquals(0,
            EditDistance.compute(new int[]{16}, new int[]{16}));
    }
}

Add unit tests for com.hankcs.hanlp.algorithm.EditDistance


/*
 * Copyright 2014 Real Logic Ltd.
 *
 * 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 uk.co.real_logic.aeron;

import uk.co.real_logic.aeron.util.BufferStrategy;

/**
 * Interface for encapsulating the strategy of mapping ByteBuffers for Session, Channel, and Term.
 *
 * This corresponds to BufferManagementStrategy, but doesn't deal with creating the files
 * which need to be mapped.
 */
public interface BufferUsageStrategy extends BufferStrategy
{
}

Add in the buffer usage strategy (client API equivalent of Buffer Management strategy)


package pipe.models.visitor;

import org.junit.Before;
import org.junit.Test;
import pipe.models.*;
import pipe.views.viewComponents.RateParameter;

import java.awt.*;
import java.util.LinkedList;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class PetriNetComponentRemovalVisitorTest {
    PetriNet mockNet;
    PetriNetComponentRemovalVisitor visitor;

    @Before
    public void setUp() {
        mockNet = mock(PetriNet.class);
        visitor = new PetriNetComponentRemovalVisitor(mockNet);
    }

    @Test
    public void testDeletesNormalArc() throws Exception {
        Place place = new Place("","");
        Transition transition = new Transition("","");
        NormalArc arc = new NormalArc(place, transition, new LinkedList<Marking>());
        arc.accept(visitor);
        verify(mockNet).removeArc(arc);

    }

    @Test
    public void testDeletesInhibitorArc() throws Exception {
        Place place = new Place("","");
        Transition transition = new Transition("","");
        InhibitorArc arc = new InhibitorArc(place, transition, new LinkedList<Marking>());
        arc.accept(visitor);
        verify(mockNet).removeArc(arc);
    }

    @Test
    public void testDeletesPlace() throws Exception {
        Place place = new Place("","");
        place.accept(visitor);
        verify(mockNet).removePlace(place);
    }

    @Test
    public void testDeletesTransition() throws Exception {
        Transition transition = new Transition("","");
        transition.accept(visitor);
        verify(mockNet).removeTransition(transition);
    }

    @Test
    public void testDeletesAnnotation() throws Exception {
        Annotation annotation = new Annotation(0, 0, "", 0, 0, false);
        annotation.accept(visitor);
        verify(mockNet).removeAnnotaiton(annotation);

    }

    //TODO: CHange RateParameter to model then test this
//    @Test
//    public void testDeletesRateParameter() throws Exception {
//        RateParameter parameter = new RateParameter("", 0, 0, 0);
//        parameter.accept
//
//    }

    @Test
    public void testDeletesToken() throws Exception {
        Token token = new Token("", false, 0, new Color(0, 0, 0));
        token.accept(visitor);
        verify(mockNet).removeToken(token);
    }

//    TODO: MAKE STATEGROUP HAVE VISITOR PATTERN
//    @Test
//    public void testRemoveStateGroup() throws Exception {
//
//    }
}

Add better unit tests for PetriNetComponentRemovalVisitor


/*
 * 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.jdbi.v3.core;

import org.junit.Test;

import java.util.UUID;

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

public class TestVendorArrays {

    private void init(Jdbi jdbi) {
        jdbi.registerArrayElementTypeName(Integer.class, "int")
                .registerArrayElementTypeName(String.class, "varchar");
    }

    @Test
    public void testHsqlDb() {
        Jdbi jdbi = Jdbi.create("jdbc:hsqldb:mem:" + UUID.randomUUID());
        init(jdbi);

        try (Handle handle = jdbi.open()) {
            handle.execute("create table player_stats (" +
                    "name varchar(64) primary key, " +
                    "seasons varchar(36) array, " +
                    "points int array)");
            handle.createUpdate("insert into player_stats (name,seasons,points) values (?,?,?)")
                    .bind(0, "Jack Johnson")
                    .bind(1, new String[]{"2013-2014", "2014-2015", "2015-2016"})
                    .bind(2, new Integer[]{42, 51, 50})
                    .execute();

            String[] seasons = handle.createQuery("select seasons from player_stats")
                    .bind("name", "Jack Johnson")
                    .mapTo(String[].class)
                    .findOnly();
            assertThat(seasons).containsExactly("2013-2014", "2014-2015", "2015-2016");
        }
    }
}

Add a test for arrays' support in HSQLDB


/*
 * (C) Copyright 2017 Boni Garcia (http://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia.wdm.test;

import static java.lang.Thread.sleep;
import static java.util.concurrent.TimeUnit.SECONDS;

import java.net.MalformedURLException;
import java.net.URL;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

/**
 * Test for WebRTC with Firefox in Selenium Grid.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class RemoteWebRtcFirefoxTest {

    private WebDriver driver;

    @Before
    public void setupTest() throws MalformedURLException {
        DesiredCapabilities capability = DesiredCapabilities.firefox();
        FirefoxProfile profile = new FirefoxProfile();
        profile.setPreference("media.navigator.permission.disabled", true);
        profile.setPreference("media.navigator.streams.fake", true);
        capability.setCapability(FirefoxDriver.PROFILE, profile);
        driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"),
                capability);
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() throws InterruptedException {
        // Test data
        int timeout = 30;
        String sutUrl = "https://webrtc.github.io/samples/src/content/devices/input-output/";

        // Implicit timeout
        driver.manage().timeouts().implicitlyWait(timeout, SECONDS);
        driver.manage().timeouts().implicitlyWait(timeout, SECONDS);

        // Open page
        driver.get(sutUrl);

        // Wait 5 seconds
        sleep(5000);
    }

}

Add remote test for WebRTC with Firefox


/*
 * Copyright 2016 The Winston 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 com.s13g.winston.common;

/**
 * Helper to do basic type conversion.
 */
public final class TypeConversion {

  private TypeConversion() {
  }

  /** Converts strings to boolean. */
  public static boolean stringToBoolean(String value) throws IllegalFormatException {
    value = value.toLowerCase();
    if ("0".equals(value) || "false".equals(value)) {
      return false;
    } else if ("1".equals(value) || "true".equals(value)) {
      return true;
    } else {
      throw new IllegalFormatException("Illegal boolean value: '" + value + "'.");
    }
  }

  public static class IllegalFormatException extends Exception {
    IllegalFormatException(String messge) {
      super(messge);
    }
  }
}

Add basic type conversion for REST requests.


package com.fasterxml.jackson.failing;

import com.fasterxml.jackson.annotation.*;

import com.fasterxml.jackson.databind.*;

import java.util.*;

public class TestIssue877TypingWithId extends BaseMapTest
{
    interface BaseInterface { }

    @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
    static class BaseInterfaceImpl implements BaseInterface {

        @JsonProperty
        private List<BaseInterfaceImpl> myInstances = new ArrayList<BaseInterfaceImpl>();

        void addInstance(BaseInterfaceImpl instance) {
            myInstances.add(instance);
        }
    }

    static class LisWrappert<T extends BaseInterface> {

        @JsonProperty
        private List<T> myList = new ArrayList<T>();

        void add(T t) {
            myList.add(t);
        }

        int size() {
            return myList.size();
        }
    }

    public void testIssue877() throws Exception
    {
        // make two instances
        BaseInterfaceImpl one = new BaseInterfaceImpl();
        BaseInterfaceImpl two = new BaseInterfaceImpl();

        // add them to each other's list to show identify info being used
        one.addInstance(two);
        two.addInstance(one);

        // make a typed version of the list and add the 2 instances to it
        LisWrappert<BaseInterfaceImpl> myList = new LisWrappert<BaseInterfaceImpl>();
        myList.add(one);
        myList.add(two);

        // make an object mapper that will add class info in so deserialisation works
        ObjectMapper om = new ObjectMapper();
        om.enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping.NON_FINAL, "@class");

        // write and print the JSON
        String json = om.writerWithDefaultPrettyPrinter().writeValueAsString(myList);

        /*
        System.out.println("JSON:\n"+json);
        */

        LisWrappert<BaseInterfaceImpl> result;

        result = om.readValue(json, myList.getClass());

        assertNotNull(result);
        // see what we get back
        System.out.println("deserialised list size = " + result.size());
    }
}

Add a test to reproduce


package ru.ifmo.nds;

import java.io.IOException;
import java.util.Random;

public class RunTestInfinitely {
    private static void run(NonDominatedSorting sorting, double[][][] tests, int[] ranks) throws IOException {
        while (System.in.available() == 0) {
            long t0 = System.nanoTime();
            int sum = 0;
            for (double[][] test : tests) {
                sorting.sort(test, ranks);
                for (int i : ranks) sum += i;
            }
            long time = System.nanoTime() - t0;
            System.out.println("Time " + (time / 1e9) + " s, checksum " + sum);
        }
    }

    public static void main(String[] args) throws IOException {
        NonDominatedSortingFactory factory = IdCollection.getNonDominatedSortingFactory(args[0]);
        int n = Integer.parseInt(args[1]);
        int d = Integer.parseInt(args[2]);
        int count = Integer.parseInt(args[3]);

        double[][][] tests = new double[count][n][d];
        int[] ranks = new int[n];
        Random random = new Random(8234925);

        for (int i = 0; i < count; ++i) {
            for (int j = 0; j < n; ++j) {
                for (int k = 0; k < d; ++k) {
                    tests[i][j][k] = random.nextDouble();
                }
            }
        }

        NonDominatedSorting sorting = factory.getInstance(n, d);
        run(sorting, tests, ranks);
    }
}

Add a coarse testing facility to run some tests infinitely many times.


/*
 * Copyright (C) 2012 Brian Muramatsu
 *
 * 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.btmura.android.reddit.content;

import java.io.IOException;

import com.btmura.android.reddit.net.RedditApi;
import com.btmura.android.reddit.net.RedditApi.AccountResult;

import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;

/**
 * {@link AsyncTaskLoader} that loads a user's account info.
 */
public class UserInfoLoader extends AsyncTaskLoader<AccountResult> {

    public static final String TAG = "UserInfoLoader";

    private final String user;
    private AccountResult result;

    public UserInfoLoader(Context context, String user) {
        super(context.getApplicationContext());
        this.user = user;
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        if (result != null) {
            deliverResult(result);
        } else {
            forceLoad();
        }
    }

    @Override
    public AccountResult loadInBackground() {
        try {
            return RedditApi.aboutUser(user, null);
        } catch (IOException e) {
            Log.e(TAG, e.getMessage(), e);
        }
        return null;
    }
}

Add loader that grabs a user's info


/*
 * Copyright 2008 The Apache Software Foundation
 *
 * 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.
 */
/**Provides row-level filters applied to HRegion scan results during calls to {@link org.apache.hadoop.hbase.client.Scanner#next()}.

<p>Use {@link org.apache.hadoop.hbase.filter.StopRowFilter} to stop the scan once rows exceed the supplied row key.
Filters will not stop the scan unless hosted inside of a {@link org.apache.hadoop.hbase.filter.WhileMatchRowFilter}.
Supply a set of filters to apply using {@link org.apache.hadoop.hbase.filter.RowFilterSet}.
</p>
*/
package org.apache.hadoop.hbase.filter;

Add package-level doc. for filters


package gherkin.formatter;

import java.util.List;

public class StepPrinter {
    public void writeStep(NiceAppendable out, Format textFormat, Format argFormat, String stepName, List<Argument> arguments) {
        int textStart = 0;
        for (Argument argument : arguments) {
            if (argument.getOffset() != 0) {
                String text = stepName.substring(textStart, argument.getOffset());
                out.append(textFormat.text(text));
            }
            String val = argument.getVal();
            out.append(argFormat.text(val));
            textStart = argument.getOffset() + argument.getVal().length();
        }
        if (textStart != stepName.length()) {
            String text = stepName.substring(textStart, stepName.length());
            out.append(textFormat.text(text));
        }
    }
}

package gherkin.formatter;

import java.util.List;

public class StepPrinter {
    public void writeStep(NiceAppendable out, Format textFormat, Format argFormat, String stepName, List<Argument> arguments) {
        int textStart = 0;
        for (Argument argument : arguments) {
            // can be -1 if the argument is missing.
            if (argument.getOffset() > 0) {
                String text = stepName.substring(textStart, argument.getOffset());
                out.append(textFormat.text(text));
            }
            String val = argument.getVal();
            // val can be null if the argument isn't there, for example @And("(it )?has something")
            if (val != null) {
                out.append(argFormat.text(val));
                textStart = argument.getOffset() + argument.getVal().length();
            }
        }
        if (textStart != stepName.length()) {
            String text = stepName.substring(textStart, stepName.length());
            out.append(textFormat.text(text));
        }
    }
}

Fix for exception when an argument is missing (vs just being empty)


import java.util.LinkedList;
import java.util.Queue;

public class MyStack {

    private Queue<Integer> queue;

    /** Initialize your data structure here. */
    public MyStack() {
        queue = new LinkedList<Integer>();
    }

    /** Push element x onto stack. */
    public void push(int x) {

        queue.add(x);

        for (int i = 1; i < queue.size(); i++) {
            queue.add(queue.remove());
        }

    }

    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue.remove();
    }

    /** Get the top element. */
    public int top() {
        return queue.peek();
    }

    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue.isEmpty();
    }

}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */

Create : 225 Implement Stack using Queues


package net.lifove.research.utils;

import static org.junit.Assert.*;
import net.lifove.research.utils.WekaUtils;

import org.junit.Test;

import weka.core.Instances;

public class CrossPredictionTest {

	@Test
	public void testCrossPrediciton(){
		//Instances srcInstances = WekaUtils.loadArff("../../Documents/temp/ODP/arffsManuallyCleaned/7/train.arff");
		//Instances tarInstances = WekaUtils.loadArff("../../Documents/temp/ODP/arffsManuallyCleaned/7/test.arff");

		Instances srcInstances = WekaUtils.loadArff("/Users/JC/Documents/HKUST/Research/CDDP/workspace/CrossPredictionSimulator/data/AEEEM/EQ.arff");
		Instances tarInstances = WekaUtils.loadArff("/Users/JC/Documents/HKUST/Research/CDDP/workspace/CrossPredictionSimulator/data/AEEEM/JDT.arff");

		Measure m = SimpleCrossPredictor.crossPrediction(srcInstances,tarInstances,"weka.classifiers.functions.Logistic","buggy");
		System.out.println(m.AUC);
		m = SimpleCrossPredictor.crossPrediction(srcInstances,tarInstances,"weka.classifiers.functions.Logistic","clean");
		System.out.println(m.AUC);
		m = SimpleCrossPredictor.crossPrediction(srcInstances,tarInstances,"weka.classifiers.trees.J48","clean");
		System.out.println(m.AUC);
		m = SimpleCrossPredictor.crossPrediction(srcInstances,tarInstances,"weka.classifiers.trees.J48","buggy");
		System.out.println(m.AUC);
	}
}

Add cross prediciton test case


package de.slikey.effectlib.effect;

import org.bukkit.Location;
import org.bukkit.util.Vector;

import de.slikey.effectlib.EffectManager;
import de.slikey.effectlib.EffectType;
import de.slikey.effectlib.util.ParticleEffect;

public class ArcLocationEffect extends LocationEffect {

	/**
	 * ParticleType of spawned particle
	 */
	public ParticleEffect particle = ParticleEffect.FLAME;

	/**
	 * Height of the arc in blocks
	 */
	public float height = 2;

	/**
	 * Particles per arc
	 */
	public int particles = 100;

	protected final Vector link;
	protected final float lenght;
	protected int step = 0;

	public ArcLocationEffect(EffectManager effectManager, Location start, Location stop) {
		super(effectManager, start);
		link = stop.toVector().subtract(start.toVector());
		lenght = (float) link.length();

		type = EffectType.REPEATING;
		period = 1;
		iterations = 200;
	}

	@Override
	public void onRun() {
		float pitch = (float) (4 * height / Math.pow(lenght, 2));
		for (int i = 0; i < particles; i++) {
			Vector v = link.clone().normalize().multiply((float) lenght * i / particles);
			float x = ((float) i / particles) * lenght - lenght / 2;
			float y = (float) (-pitch * Math.pow(x, 2) + height);
			location.add(v);
			location.add(0, y, 0);
			particle.display(location, visibleRange);
			location.subtract(0, y, 0);
			location.subtract(v);

			step++;
		}
	}

}

Create ArcEffect. Creates an arc from location to location with custom height.


package com.jmb.springfactory.model.bo;

public class BusinessObjectBase {

  private String id;

  public String getId() {
    return id;
  }

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

Create a new base business object to represente object in business layer


package router.client;

import javax.annotation.Nonnull;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.testng.PowerMockObjectFactory;
import org.testng.IObjectFactory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.ObjectFactory;
import org.testng.annotations.Test;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;

@PrepareForTest( { RouteDefinition.class, RegExp.class } )
public class RouteDefinitionTest
{
  @ObjectFactory
  public IObjectFactory getObjectFactory()
  {
    return new PowerMockObjectFactory();
  }

  @DataProvider( name = "pathToRegex" )
  public static Object[][] pathToRegexData()
  {
    return new Object[][]{
      { "X", "^X$" },
      { "/abc/1!", "^\\/abc\\/1!$" },
      { "/+$#-?()[]{}.*\\", "^\\/\\+\\$#\\-\\?\\(\\)\\[\\]\\{\\}\\.\\*\\\\$" },
      };
  }

  @Test( dataProvider = "pathToRegex" )
  public void pathToRegex( @Nonnull final String path, @Nonnull final String regex )
    throws Exception
  {
    final RegExp mock = PowerMockito.mock( RegExp.class );
    PowerMockito.whenNew( RegExp.class ).withArguments( eq( regex ) ).thenReturn( mock );

    final RegExp re = RouteDefinition.pathToRegex( path );

    assertEquals( re, mock );

    PowerMockito.verifyNew( RegExp.class ).withArguments( eq( regex ) );
  }
}

Introduce a very basic test


package to.etc.domui.hibernate.idgen;

import org.hibernate.HibernateException;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;
import to.etc.util.StringTool;

import java.io.Serializable;
import java.util.UUID;

/**
 * Create a String identifier that is based on an UUID, but which does
 * not use the very verbose string format of those things. Instead the
 * 128 bits are rendered as a base64 string (with the last 2 == signs
 * stripped), forming a 23 char identifier.
 *
 * To use the generator annotate your class(es) ID property as follows:
 *

 *  @GeneratedValue(generator = "uuid3")
 * 	@GenericGenerator(name = "uuid3", strategy = "to.etc.domui.hibernate.idgen.UUIDGenerator23")
 * 	@Id
 * 	@Column(name = "id", length = 23, nullable = false)
 * 	@Nullable @Override public String getId() {
 * 		return m_id;
 *  }
 *

 *
 * @author Frits Jalvingh
 * Created on 12-2-18.
 */
final public class UUIDGenerator23 implements IdentifierGenerator {
	@Override public Serializable generate(SessionImplementor sessionImplementor, Object o) throws HibernateException {
		UUID uuid = UUID.randomUUID();
		byte[] data = new byte[16];

		moveBytes(data, 0, uuid.getMostSignificantBits());
		moveBytes(data, 8, uuid.getLeastSignificantBits());
		String str = StringTool.encodeBase64ToString(data);

		return str.substring(0, 23);				// Strip the ==
	}

	private void moveBytes(byte[] bytes, int offset, long bits) {
		for(int i = 8; --i >= 0;) {
			bytes[i + offset] = (byte) (bits & 0xff);
			bits = bits >> 8;
		}
	}

}

Add generic UUID ID generator for Hibernate that does not use that many characters.


package org.intermine.webservice.server.output;

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

import org.intermine.api.InterMineAPI;
import org.intermine.api.LinkRedirectManager;
import org.intermine.api.results.ResultElement;
import org.intermine.model.InterMineObject;
import org.intermine.web.logic.PortalHelper;
import org.json.JSONObject;

public class TableCellFormatter
{

    private static final String CELL_KEY_URL = "url";
    private static final String CELL_KEY_VALUE = "value";
    private static final String CELL_KEY_CLASS = "class";
    private static final String CELL_KEY_ID = "id";

    private final LinkRedirectManager redirector;
    private final InterMineAPI im;

    public TableCellFormatter(InterMineAPI im) {
        this.im = im;
        this.redirector = im.getLinkRedirector();
    }

    /**
     * Get the JSONObject that represents each cell in the results row
     * @param cell The result element with the data
     * @return A JSONObject
     */
    public JSONObject toJSON(ResultElement cell) {
        Map<String, Object> mapping = new HashMap<String, Object>();
        if (cell == null || cell.getId() == null) {
            mapping.put(CELL_KEY_URL, null);
            mapping.put(CELL_KEY_VALUE, null);
        } else {
            String link = null;
            if (redirector != null) {
                link = redirector.generateLink(im, (InterMineObject) cell.getObject());
            }
            if (link == null) {
                link = PortalHelper.generateReportPath(cell);
            }
            mapping.put(CELL_KEY_URL, link);
            mapping.put(CELL_KEY_CLASS, cell.getType());
            mapping.put(CELL_KEY_ID, cell.getId());
            mapping.put(CELL_KEY_VALUE, cell.getField());
        }
        JSONObject ret = new JSONObject(mapping);
        return ret;
    }
}

Refactor json cell formatting into own class


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps.CollapseNumeric;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.NumericType;
import net.imglib2.view.Views;
import net.imglib2.view.composite.CompositeIntervalView;
import net.imglib2.view.composite.NumericComposite;

public class DefaultCollapseNummeric2CompositeIntervalView<T extends NumericType<T>>
		extends
		AbstractView<RandomAccessibleInterval<T>, CompositeIntervalView<T, NumericComposite<T>>>
		implements
		CollapseNumeric<RandomAccessibleInterval<T>, CompositeIntervalView<T, NumericComposite<T>>> {

	@Override
	public CompositeIntervalView<T, NumericComposite<T>> compute(
			RandomAccessibleInterval<T> input) {
		return Views.collapseNumeric(input);
	}

}

Add default implementation of CollapseNumeric to CompositeIntervalView.


package org.springframework.test.integration;

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

import java.io.IOException;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.bootstrap.SpringApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.site.configuration.ApplicationConfiguration;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

public class StaticAssetRequestMappingTest {

	private static ConfigurableApplicationContext context;

	@BeforeClass
	public static void start() throws Exception {
		Future<ConfigurableApplicationContext> future = Executors
				.newSingleThreadExecutor().submit(
						new Callable<ConfigurableApplicationContext>() {
							@Override
							public ConfigurableApplicationContext call() throws Exception {
								return (ConfigurableApplicationContext) SpringApplication
										.run(ApplicationConfiguration.class);
							}
						});
		context = future.get(30, TimeUnit.SECONDS);
	}

	@AfterClass
	public static void stop() {
		if (context != null) {
			context.close();
		}
	}

	@Test
	public void getStyleSheet() throws Exception {
		ResponseEntity<String> response = getRestTemplate().getForEntity(
				"http://localhost:8080/css/getting-started.css", String.class);
		assertEquals(HttpStatus.OK, response.getStatusCode());
		assertTrue(response.getHeaders().getContentType()
				.isCompatibleWith(MediaType.valueOf("text/css")));
		assertTrue(response.getBody().contains("h1,h2,h3,h4,h5,h6"));
	}

	private RestTemplate getRestTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		restTemplate.setErrorHandler(new DefaultResponseErrorHandler() {
			@Override
			public boolean hasError(ClientHttpResponse response) throws IOException {
				return false;
			}
		});
		return restTemplate;
	}

}

Fix mime type for css (and test)


package org.robockets.stronghold.robot.autonomous;

import org.robockets.stronghold.robot.Direction;
import org.robockets.stronghold.robot.drivetrain.AssistedDrive;
import org.robockets.stronghold.robot.drivetrain.AssistedRotateType;
import org.robockets.stronghold.robot.drivetrain.AssistedTranslateType;

import edu.wpi.first.wpilibj.command.CommandGroup;

/**
 *
 */
public class DrawBridge extends CommandGroup {

    public DrawBridge(Direction direction) {
    	if (direction == Direction.BACKWARD) {
    		addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, -1, 0)); // Dummy inputs for distance and relativeAngle
    	} else {
    		addSequential(new AssistedDrive(AssistedTranslateType.ENCODER, AssistedRotateType.ENCODER, 1, 0)); // Dummy inputs for distance and relativeAngle)
    	}
    }
}

Add autonomous command for drawbridge.


package com.codeborne.selenide.conditions;

import com.codeborne.selenide.Driver;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebElement;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class ExactTextCaseSensitiveTest {

  private final Driver driver = mock(Driver.class);
  private final WebElement element = mock(WebElement.class);

  @BeforeEach
  void setUp() {
    when(element.getText()).thenReturn("One");
  }

  @Test
  void shouldMatchExpectedTextWithSameCase() {
    assertThat(new ExactTextCaseSensitive("One").apply(driver, element)).isEqualTo(true);
  }

  @Test
  void shouldNotMatchExpectedTextWithDifferentCase() {
    assertThat(new ExactTextCaseSensitive("one").apply(driver, element)).isEqualTo(false);
  }

  @Test
  void shouldNotMatchDifferentExpectedText() {
    assertThat(new ExactTextCaseSensitive("Two").apply(driver, element)).isEqualTo(false);
  }

  @Test
  void shouldHaveCorrectToString() {
    assertThat(new ExactTextCaseSensitive("One")).hasToString("exact text case sensitive 'One'");
  }

}

Add tests for ExactTextCaseSensitive condition


package com.enginemobi.core.generic.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.EntityManagerFactoryUtils;
import org.springframework.orm.jpa.EntityManagerHolder;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;

@Component
public class EntityManagerUtils {

	@Autowired
	private EntityManagerFactory entityManagerFactory;

	@PersistenceContext
	private EntityManager entityManager;

	public EntityManager openEntityManager() {
		if (TransactionSynchronizationManager.hasResource(entityManagerFactory)) {
			return ((EntityManagerHolder) TransactionSynchronizationManager.getResource(entityManagerFactory)).getEntityManager();
		} else {
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			TransactionSynchronizationManager.bindResource(entityManagerFactory, new EntityManagerHolder(entityManager));
			return entityManager;
		}
	}

	public void closeEntityManager() {
		if (TransactionSynchronizationManager.hasResource(entityManagerFactory)) {
			EntityManagerHolder entityManagerHolder = (EntityManagerHolder) TransactionSynchronizationManager.unbindResource(entityManagerFactory);
			EntityManagerFactoryUtils.closeEntityManager(entityManagerHolder.getEntityManager());
		}
	}

	public EntityManager getEntityManager() {
		return entityManager;
	}
}

Add entity manager utils for unit testing


/**
 * Copyright 2008-2017 Juho Jeong
 *
 * 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.aspectran.console.inout;

import java.io.IOException;

/**‰
 *
Created: 2017. 3. 5.

 */
public class SystemConsoleInoutTest {

	public static void main(String argv[]) throws IOException {
		ConsoleInout consoleInout = new SystemConsoleInout();
		String prompt = "System > ";
		while (true) {
			consoleInout.readPassword(prompt);
		}
	}

}

Add test cases for SystemConsoleInout


/*
 * 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 to test JOrphanUtils methods
 */

package org.apache.jorphan.exec;

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

import junit.framework.TestCase;

public class TestKeyToolUtils extends TestCase {

    public TestKeyToolUtils() {
        super();
    }

    public TestKeyToolUtils(String arg0) {
        super(arg0);
    }

    /*
     * Check the assumption that a missing executable will generate
     * either an IOException or status which is neither 0 nor 1
     *
     */
    public void testCheckKeytool() throws Exception {
        SystemCommand sc = new SystemCommand(null, null);
        List<String> arguments = new ArrayList<String>();
        arguments.add("xyzqwas"); // should not exist
        try {
            int status = sc.run(arguments);
            if (status == 0 || status ==1) {
                fail("Unexpected status " + status);
            }
            System.out.println("testCheckKeytool:status="+status);
        } catch (IOException e) {
            System.out.println("testCheckKeytool:Exception="+e);
        }
    }
}

Test assumptions regarding keytool check


package com.m4gik.util;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;

import java.util.Arrays;
import java.util.Collection;

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

/**
 *
 * This class contains JUnit tests for class {@link Util}.
 *
 * @author Michał Szczygieł <michal.szczygiel@wp.pl>
 *
 */
@RunWith(Parameterized.class)
public class UtilTest {

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][] {
                { new String("test").getBytes() },
                { new Integer(8).byteValue() } });
    }

    private final Object input;

    public UtilTest(Object input) {
        this.input = input;
    }

    @Test
    public void testInputIsNotNull() {
        assertThat(input, is(notNullValue()));
    }

}

Create TDD test for utils.


/*
Copyright (c) 2016, Colorado State University
All rights reserved.

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 holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/

package io.sigpipe.sing.stat;

public class OnlineKDEException extends Exception {

    public OnlineKDEException() {
        super();
    }

    public OnlineKDEException(String s) {
        super(s);
    }

    public OnlineKDEException(String s, Throwable t) {
        super(s, t);
    }

}

Add generic Online KDE exception


package search;

import search.BinarySearch; 		// My implementation of binary search in package search
/*
	This class tests class BinarySearch
*/

class TestSearch{

	// Tests binary search

	public static void testBinarySearch(){

		// Define array reference
		int[] A = null;

		// Should throw NullPointerException
		try{
			BinarySearch.find(A, 50);
		}
		catch(NullPointerException e){
			System.out.println(e);
		}

		// Allocate 100 integers
		A = new int[100];

		// Assiging values
		for(int i=0;i<100;i++)
			A[i] = 2*i;

		// Search for values using binary search
		for(int i=0;i<100;i++){

			// Search for key 2*i
			int index = BinarySearch.find(A, 2*i);

			System.out.println(2*i + " found at: "+index);

		}

		// Search for keys that are not present in array
		System.out.println(250 + " found at: "+BinarySearch.find(A, 250));
		System.out.println((-5) + " found at: "+BinarySearch.find(A, -5));
		System.out.println(53 + " found at: "+BinarySearch.find(A, -53));

	}

	public static void main(String args[]){

		// Call testBinarySearch
		testBinarySearch();

	}

}

Add test class for binary search


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem76;

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;

/**
 * Given an array full of integers implement a insert sort algorithm to sort the content inside
 * the array.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class InsertionSort extends SortingAlgorithm {

}

/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem76;

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;

/**
 * Given an array full of integers implement a insert sort algorithm to sort the content inside
 * the array.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class InsertionSort extends SortingAlgorithm {

  /**
   * Insertion sort is a simple sorting algorithm that is relatively efficient for small lists and
   * mostly sorted lists, and often is used as part of more sophisticated algorithms. It works by
   * taking elements from the list one by one and inserting them in their correct position into a
   * new sorted list. In arrays, the new list and the remaining elements can share the array's
   * space, but insertion is expensive, requiring shifting all following elements over by one.
   */
  @Override public void sort(int[] numbers) {
    validateInput(numbers);

    int i;
    for (i = 1; i < numbers.length; i++) {
      int tmp = numbers[i];
      int j = i;
      while (j > 0 && numbers[j - 1] > tmp) {
        numbers[j] = numbers[j - 1];
        j--;
      }
      numbers[j] = tmp;
    }
  }
}

Add solution to problem 76


/*
 *
 *
 * Copyright (C) 2007 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2007 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.service;

import junit.framework.TestCase;

import org.easymock.classextension.EasyMock;
import org.easymock.classextension.IMocksControl;
import org.sipfoundry.sipxconfig.device.ModelSource;

public class AddServiceTaskTest extends TestCase {

    public void testAddService() {
        ServiceDescriptor turkeyDesctriptor = new ServiceDescriptor("bird", "turkey");
        IMocksControl serviceSourceControl = EasyMock.createControl();
        ModelSource<ServiceDescriptor> serviceSource = serviceSourceControl.createMock(ModelSource.class);
        serviceSource.getModel("turkey");
        serviceSourceControl.andReturn(turkeyDesctriptor).anyTimes();
        serviceSourceControl.replay();

        ConfiguredService turkey = new UnmanagedService();
        turkey.setDescriptor(turkeyDesctriptor);

        IMocksControl serviceManagerControl = EasyMock.createStrictControl();
        ServiceManager serviceManager = serviceManagerControl.createMock(ServiceManager.class);

        // already a service
        serviceManager.getServiceByName("Thanksgiving");
        serviceManagerControl.andReturn(turkey);
        serviceManagerControl.replay();
        AddServiceTask task = new AddServiceTask();
        task.setServiceManager(serviceManager);
        task.setServicesSource(serviceSource);
        try {
            task.addService("Thanksgiving", "chicken", "1.1.1.1");
            fail();
        } catch (IllegalArgumentException expected) {
        }
        serviceManagerControl.verify();

        // update service
        serviceManagerControl.reset();
        serviceManager.getServiceByName("Thanksgiving");
        serviceManagerControl.andReturn(turkey);
        serviceManager.saveService(turkey);
        serviceManagerControl.replay();
        turkey.setName("Thanksgiving");
        task.addService("Thanksgiving", "turkey", "1.1.1.1");
        serviceManagerControl.verify();

        // add a service
        serviceManagerControl.reset();
        serviceManager.getServiceByName("Thanksgiving");
        serviceManagerControl.andReturn(null);
        serviceManager.newService(turkeyDesctriptor);
        serviceManagerControl.andReturn(turkey);
        serviceManager.saveService(turkey);
        serviceManagerControl.replay();
        turkey.setName("Thanksgiving");
        task.addService("Thanksgiving", "turkey", "1.1.1.1");
        serviceManagerControl.verify();
    }

    public void testAssertArgument() {
        AddServiceTask.assertArgument(new String[] {"x"}, 0, "x");
        try {
            AddServiceTask.assertArgument(new String[0], 0, "x");
            fail();
        } catch (IllegalArgumentException expected) {
            assertTrue(true);
        }
    }
}

Add forgotten unit test for adding a new service task


// Copyright 2018 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.devtools.build.lib.skyframe.serialization;

import com.google.protobuf.CodedInputStream;
import com.google.protobuf.CodedOutputStream;
import java.io.IOException;

/** Codec for {@link Long}. */
class LongCodec implements ObjectCodec<Long> {

  @Override
  public Class<Long> getEncodedClass() {
    return Long.class;
  }

  @Override
  public void serialize(SerializationContext context, Long value, CodedOutputStream codedOut)
      throws IOException {
    codedOut.writeInt64NoTag(value);
  }

  @Override
  public Long deserialize(DeserializationContext context, CodedInputStream codedIn)
      throws IOException {
    return codedIn.readInt64();
  }
}

Add codec for Long (needed by TargetCompleteEvent).


package com.github.andlyticsproject;

import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.widget.TextView;

public class Style {

    private static Style instance;
    private static Typeface tf;

    private Style(AssetManager mgr){
        tf = Typeface.createFromAsset(mgr, "fonts/DroidSansBold.ttf");
    }

    public static Style getInstance(AssetManager mgr) {
        if(instance == null) {
            instance = new Style(mgr);
        }
        return instance;
    }

    public void styleHeadline(final TextView headline) {
        //headline.setTypeface(tf);
    }
}

package com.github.andlyticsproject;

import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.widget.TextView;

public class Style {

    private static Style instance;
    private static Typeface tf;

    private Style(AssetManager mgr){

    }

    public static Style getInstance(AssetManager mgr) {
        if(instance == null) {
            instance = new Style(mgr);
        }
        return instance;
    }

    public void styleHeadline(final TextView headline) {
        //headline.setTypeface(tf);
    }
}

Fix for fonts (Class might be removed in the future b/c unnecessary


/*
 * Copyright 2017, 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.server.entity;

import com.google.protobuf.StringValue;
import org.junit.Before;
import org.junit.Test;
import org.spine3.server.BoundedContext;
import org.spine3.server.aggregate.AggregatePart;
import org.spine3.server.aggregate.AggregateRoot;

import java.lang.reflect.Constructor;

import static org.junit.Assert.assertNotNull;
import static org.spine3.base.Identifiers.newUuid;

/**
 * @author Illia Shepilov
 */
public class AbstractEntityShould {

    private BoundedContext boundedContext;
    private AnAggregateRoot root;
    private String id;

    @Before
    public void setUp() {
        boundedContext = BoundedContext.newBuilder()
                                       .build();
        id = newUuid();
        root = new AnAggregateRoot(boundedContext, id);
    }

    @Test
    public void create_aggregate_part_entity() throws NoSuchMethodException {
        final Constructor<AnAggregatePart> constructor =
                AnAggregatePart.class.getDeclaredConstructor(String.class, AnAggregateRoot.class);
        final AggregatePart aggregatePart =
                AbstractEntity.createAggregatePartEntity(constructor, id, root);
        assertNotNull(aggregatePart);
    }

    @Test
    public void create_aggregate_root_entity(){
        final AnAggregateRoot aggregateRoot =
                AbstractEntity.createAggregateRootEntity(id, boundedContext, AnAggregateRoot.class);
        assertNotNull(aggregateRoot);
    }

    static class AnAggregatePart extends AggregatePart<String, StringValue, StringValue.Builder> {

        /**
         * {@inheritDoc}
         *
         * @param id
         * @param root
         */
        protected AnAggregatePart(String id, AnAggregateRoot root) {
            super(id, root);
        }
    }

    private static class AnAggregateRoot extends AggregateRoot<String> {
        /**
         * Creates an new instance.
         *
         * @param boundedContext the bounded context to which the aggregate belongs
         * @param id             the ID of the aggregate
         */
        protected AnAggregateRoot(BoundedContext boundedContext, String id) {
            super(boundedContext, id);
        }
    }
}

Add tests for the `AbstractEntity` class.


/*
 * (C) Copyright 2021 Boni Garcia (https://bonigarcia.github.io/)
 *
 * 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.github.bonigarcia.wdm.test.extensions;

import static io.github.bonigarcia.wdm.WebDriverManager.zipFolder;
import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

import io.github.bonigarcia.wdm.WebDriverManager;

class InstallBrowserWatcherFirefoxTest {

    WebDriver driver;

    Path zippedExtension;

    @BeforeEach
    void setup() throws URISyntaxException {
        Path extensionFolder = Paths
                .get(ClassLoader.getSystemResource("web-extension").toURI());
        zippedExtension = zipFolder(extensionFolder);

        driver = WebDriverManager.firefoxdriver().create();
        ((FirefoxDriver) driver).installExtension(zippedExtension, true);
    }

    @AfterEach
    void teardown() throws InterruptedException, IOException {
        // FIXME: pause for manual browser inspection
        Thread.sleep(Duration.ofSeconds(3).toMillis());

        Files.delete(zippedExtension);

        driver.quit();
    }

    @Test
    void testExtensions() {
        driver.get("https://bonigarcia.dev/selenium-webdriver-java/");

        WebElement h1 = driver.findElement(By.tagName("h1"));
        assertThat(h1.getText())
                .isNotEqualTo("Hands-On Selenium WebDriver with Java");
    }

}

Include test installing browser extension in Firefox


package net.thechunk.playpen.netty.handlers;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderException;
import net.thechunk.playpen.protocol.Protocol;
import net.thechunk.playpen.utils.AuthUtils;

public class AuthenticatedMessageVerificationHandler extends SimpleChannelInboundHandler<Protocol.AuthenticatedMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Protocol.AuthenticatedMessage msg) throws Exception {
        if (!AuthUtils.validateHash(msg)) {
            throw new DecoderException("Hash " + msg.getHash() + " is invalid (correct hash: " +
                    AuthUtils.createHash(msg.getUuid(), msg.getPayload().toByteArray()));
        }
    }
}

Revert "can't use dedicated handler just yet, will have to be local vs network specific"


/*
 * Copyright 2017, OpenCensus 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 io.opencensus.tags;

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

import com.google.common.collect.Lists;
import io.opencensus.tags.Tag.TagString;
import io.opencensus.tags.TagKey.TagKeyString;
import io.opencensus.tags.TagValue.TagValueString;
import java.util.Iterator;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link Internal}. */
@RunWith(JUnit4.class)
public final class InternalTest {

  @Test
  public void getTags() {
    final Iterator<Tag> iterator =
        Lists.<Tag>newArrayList(
                TagString.create(TagKeyString.create("k"), TagValueString.create("v")))
            .iterator();
    TagContext ctx =
        new TagContext() {
          @Override
          protected Iterator<Tag> iterator() {
            return iterator;
          }
        };
    assertThat(Internal.getTags(ctx)).isSameAs(iterator);
  }
}

Add a test for Internal.getTags().


/*
 * Copyright (c) OSGi Alliance (2008, 2009). 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 org.osgi.service.blueprint.container;

/**
 * Provides access to the type conversions (both predefined and user registered)
 * that are defined for the blueprint container.
 */
public interface Converter {

	/**
	 * Check if the converter is able to convert the given value to the specified
	 * type.
	 *
	 * @return true if the conversion is possible, false otherwise.
	 */
	boolean canConvert(Object fromValue, Class toType);

	/**
	 * Convert an object to an instance of the given class, using the built-in and
	 * user-registered type converters as necessary.
	 * @param fromValue the object to be converted
	 * @param toType the type that the instance is to be converted to
	 * @return an instance of the class 'toType'
	 * @throws Exception if the conversion cannot succeed. This exception is
	 * checked because callers should expect that not all source objects
	 * can be successfully converted.
	 */
	Object convert(Object fromValue, Class toType) throws Exception;

}

Update the conversion spec (use a single interface inside the org.osgi.service.blueprint.container package)


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

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import org.apache.taverna.mobile.R;

import butterknife.BindView;
import butterknife.ButterKnife;

public class FavouriteWorkflowDetailActivity extends AppCompatActivity {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_workflow);

        ButterKnife.bind(this);

        setSupportActionBar(mToolbar);

        ActionBar actionbar = getSupportActionBar();

        if (actionbar != null) {
            actionbar.setHomeButtonEnabled(true);
            actionbar.setDisplayHomeAsUpEnabled(true);
            actionbar.setTitle(getIntent().getStringExtra("title"));
        }

        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.frame_container
                            , FavouriteWorkflowDetailFragment.newInstance(getIntent().getStringExtra("id")))
                    .commit();
        }

    }
}

Add Favourite workflow detail activity


package com.epam.itweek.boosenger;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class BoosengerApplication {

    public static void main(String[] args) {
        SpringApplication.run(BoosengerApplication.class, args);
    }
}

Add Spring Boot application class


/*
 * EmergentMUD - A modern MUD with a procedurally generated world.
 * Copyright (C) 2016 Peter Keeler
 *
 * This file is part of EmergentMUD.
 *
 * EmergentMUD is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * EmergentMUD is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.emergentmud.core.event;

import com.emergentmud.core.model.Entity;
import com.emergentmud.core.model.stomp.GameOutput;
import com.emergentmud.core.repository.EntityRepository;
import com.emergentmud.core.util.EntityUtil;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationContextEvent;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.util.List;

@Component
public class GameShutdownListener implements ApplicationListener<ApplicationContextEvent> {
    private EntityRepository entityRepository;
    private EntityUtil entityUtil;

    @Inject
    public GameShutdownListener(EntityRepository entityRepository, EntityUtil entityUtil) {
        this.entityRepository = entityRepository;
        this.entityUtil = entityUtil;
    }

    @Override
    public void onApplicationEvent(ApplicationContextEvent event) {
        if (event instanceof ContextClosedEvent || event instanceof ContextStoppedEvent) {
            List<Entity> everyone = entityRepository.findByRoomIsNotNull();
            GameOutput output = new GameOutput("[red]EmergentMUD is shutting down. Please check back later!")
                    .append("")
                    .append("> ");

            entityUtil.sendMessageToListeners(everyone, output);
        }
    }
}

Add a shutdown listener to print a quick message right before the game disconnects everyone.


/*-
 * Copyright (c) 2014 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.fedoraproject.xmvn.tools.install.condition;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import org.junit.Test;

/**
 * @author Mikolaj Izdebski
 */
public class BooleanExpressionTest
{
    @Test
    public void testBasicExpressions()
    {
        Context context = new Context( Collections.<String, String> emptyMap() );

        BooleanExpression trueExpression = new BooleanLiteral( true );
        assertTrue( trueExpression.getValue( context ) );

        BooleanExpression falseExpression = new BooleanLiteral( false );
        assertFalse( falseExpression.getValue( context ) );

        BooleanExpression andExpression = new And( trueExpression, falseExpression );
        assertFalse( andExpression.getValue( context ) );

        BooleanExpression orExpression = new Or( trueExpression, falseExpression );
        assertTrue( orExpression.getValue( context ) );

        BooleanExpression xorExpression = new Xor( trueExpression, falseExpression );
        assertTrue( xorExpression.getValue( context ) );
    }

    @Test
    public void testProperties()
    {
        Map<String, String> properties = new LinkedHashMap<>();
        properties.put( "foo", "bar" );
        properties.put( "baz", "" );
        Context context = new Context( properties );

        StringExpression fooProperty = new Property( "foo" );
        assertEquals( "bar", fooProperty.getValue( context ) );

        StringExpression bazProperty = new Property( "baz" );
        assertEquals( "", bazProperty.getValue( context ) );

        StringExpression xyzzyProperty = new Property( "xyzzy" );
        assertEquals( null, xyzzyProperty.getValue( context ) );

        BooleanExpression fooDefined = new Defined( "foo" );
        assertTrue( fooDefined.getValue( context ) );

        BooleanExpression bazDefined = new Defined( "baz" );
        assertTrue( bazDefined.getValue( context ) );

        BooleanExpression xyzzyDefined = new Defined( "xyzzy" );
        assertFalse( xyzzyDefined.getValue( context ) );
    }
}

Add tests for installer conditions


/*
 * Copyright (C) 2014 Pedro Vicente Gómez Sánchez.
 *
 * 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.github.pedrovgs.problem51;

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

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseStringTest {

  private ReverseString reverseString;

  @Before public void setUp() {
    reverseString = new ReverseString();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullStrings() {
    reverseString.reverse(null);
  }

  @Test public void shouldReturnAnEmptyStringIfTheInputIsEmpty() {
    String result = reverseString.reverse("");

    assertEquals("", result);
  }

  @Test public void shouldReturnTheSameStringIfTheInputStringContainsJustOneChar() {
    String result = reverseString.reverse("a");

    assertEquals("a", result);
  }

  @Test public void shouldReverseString() {
    String result = reverseString.reverse("Pedro");

    assertEquals("ordeP", result);
  }
}

Add some tests to problem 51


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

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

import java.net.URI;

import javax.jms.DeliveryMode;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TransactionRolledBackException;

import org.apache.activemq.broker.jmx.QueueViewMBean;
import org.apache.qpid.jms.support.AmqpTestSupport;
import org.junit.Test;

/**
 * Test MessageProducer behavior when in a TX and failover occurs.
 */
public class JmsTxProducerFailoverTest extends AmqpTestSupport {

    @Override
    protected boolean isPersistent() {
        return true;
    }

    @Test
    public void testTxProducerSendWorksButCommitFails() throws Exception {
        URI brokerURI = new URI("failover://("+ getBrokerAmqpConnectionURI() +")?maxReconnectDelay=1000");

        connection = createAmqpConnection(brokerURI);
        connection.start();

        final int MSG_COUNT = 20;
        final Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        Queue queue = session.createQueue(name.getMethodName());
        final MessageProducer producer = session.createProducer(queue);
        producer.setDeliveryMode(DeliveryMode.PERSISTENT);

        QueueViewMBean proxy = getProxyToQueue(name.getMethodName());
        assertEquals(0, proxy.getQueueSize());

        for (int i = 0; i < MSG_COUNT / 2; ++i) {
            LOG.debug("Producer sening message #{}", i + 1);
            producer.send(session.createTextMessage("Message: " + i));
        }

        assertEquals(0, proxy.getQueueSize());

        stopPrimaryBroker();
        restartPrimaryBroker();

        proxy = getProxyToQueue(name.getMethodName());
        assertEquals(0, proxy.getQueueSize());

        for (int i = MSG_COUNT / 2; i < MSG_COUNT; ++i) {
            LOG.debug("Producer sening message #{}", i + 1);
            producer.send(session.createTextMessage("Message: " + i));
        }

        try {
            session.commit();
            fail("Session commit should have failed with TX rolled back.");
        } catch (TransactionRolledBackException rb) {
            LOG.info("Transacted commit failed after failover: {}", rb.getMessage());
        }

        assertEquals(0, proxy.getQueueSize());
    }
}

Add a start on testing TX producer with failover.


package org.camunda.bpm.extension.junit5;

import org.camunda.bpm.extension.junit5.test.ProcessEngineExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtensionContext;

/**
 * @author Martin Schimak
 */
public class ProcessEngineExtensionDeploymentIdAccess {

  @Test
  public void testDeploymentIdWriteableForExtensions() {

    class ProcessEngineExtensionExtension extends org.camunda.bpm.extension.junit5.test.ProcessEngineExtension {

      @Override
      public void beforeTestExecution(ExtensionContext context) {
        // here I could decide to override the way the deployment is created, e.g.
        // add mocked call activities etc, therefore I need deploymentId accessible
        // Note: in case the write access is removed, this will not compile anymore
        this.deploymentId = "xyz";
      }

    }

  }

  @Test
  public void testDeploymentIdReadableForExtensionsAndWrappers() {

    class ProcessEngineExtensionExtension extends org.camunda.bpm.extension.junit5.test.ProcessEngineExtension {

      @Override
      public void afterTestExecution(ExtensionContext context) {
        // here I could decide to override the way the deployment is removed
        // Note: in case the write access is removed, this will not compile anymore
        String deploymentId = this.deploymentId;
      }

    }

    class ProcessEngineExtensionWrapper {

      ProcessEngineExtension wrapped = ProcessEngineExtension.builder().build();

      {
        // here I could decide to access the deployment. e.g. to look at the
        // runtime or history data of the current deployment before it is removed
        // Note: in case this read access is removed, this will not compile anymore
        String deploymentId = wrapped.getDeploymentId();
      }

    }

  }

}

Add unit test to document read/write access to deployment id and protect it against regression


package flyway.myplaces;

import fi.nls.oskari.db.DatasourceHelper;
import fi.nls.oskari.geoserver.GeoserverPopulator;
import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
import org.json.JSONObject;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;

public class V1_0_13__add_formatting_metadata implements JdbcMigration {

    public void migrate(Connection ignored) throws Exception {
        // myplaces _can_ use other db than the default one
        // -> Use connection to default db for this migration
        DataSource ds = DatasourceHelper.getInstance().getDataSource();
        if (ds == null) {
            ds = DatasourceHelper.getInstance().createDataSource();
        }
        Connection conn = ds.getConnection();
        JSONObject attributes = GeoserverPopulator.addMyplacesAttributes(GeoserverPopulator.createUserContentAttributes());
        final String sql = "update oskari_maplayer set attributes =? where name = 'oskari:my_places';";

        try (final PreparedStatement statement = conn.prepareStatement(sql)) {
            statement.setString(1, attributes.toString());
            statement.execute();
        }
    }

}

Update attributes for myplaces baselayer


public class ExcelSheetColumnNumber {
  public int titleToNumber(String s) {
    int length = s.length();
    int number = 0;

    for (int i = 0; i < length; i++) {
      number += (s.charAt(i) - 'A' + 1) * Math.pow(26, length - i - 1);
    }

    return number;
  }
}

Add excell sheet column number