package net.robobalasko.dfa.core;

import net.robobalasko.dfa.core.exceptions.MultipleStartNodesException;
import net.robobalasko.dfa.core.exceptions.NodeConnectionException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.LinkedList;

import static org.junit.Assert.*;

public class NodeConnectionStateTest {

    private NodeConnectionState nodeConnectionState;

    @Before
    public void setUp() {
        nodeConnectionState = new NodeConnectionState();
    }

    @Test
    public void testResetConnectionStateSucceeds() {
        nodeConnectionState.resetConnectionState();
        assertNull(nodeConnectionState.getStartNode());
        assertNull(nodeConnectionState.getEndNode());
        assertFalse(nodeConnectionState.isConnecting());
    }

    @Test(expected = NodeConnectionException.class)
    public void testConnectNodesFails() throws MultipleStartNodesException, NodeConnectionException {
        nodeConnectionState.connectNodes();
    }

    @Test
    public void testConnectNodesSucceeds() throws MultipleStartNodesException, NodeConnectionException {
        StateNode firstNode = new StateNode('a', false, false, new LinkedList<StateNode>(), null);
        StateNode secondNode = new StateNode('b', false, false, new LinkedList<StateNode>(), null);
        nodeConnectionState.setStartNode(firstNode);
        nodeConnectionState.setEndNode(secondNode);
        nodeConnectionState.connectNodes();
        assertEquals('a', nodeConnectionState.getStartNode().getName());
        assertEquals('b', nodeConnectionState.getEndNode().getName());
    }

    @Test
    public void testSetStartNode() {
        StateNode startNode = new StateNode('a', false, false, null, null);
        nodeConnectionState.setStartNode(startNode);
        assertEquals('a', nodeConnectionState.getStartNode().getName());
        assertTrue(nodeConnectionState.getStartNode().isActive());
        assertTrue(nodeConnectionState.isConnecting());
    }

    @Test
    public void testSetEndNode() {
        StateNode endNode = new StateNode('b', false, false, null, null);
        nodeConnectionState.setEndNode(endNode);
        assertEquals('b', nodeConnectionState.getEndNode().getName());
        assertTrue(nodeConnectionState.getEndNode().isActive());
    }

    @After
    public void tearDown() {
        nodeConnectionState = null;
    }

}

Add tests for NodeConnectionState class.


/*
 * 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.tika.io;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import junit.framework.TestCase;

public class TikaInputStreamTest extends TestCase {

    public void testFileBased() throws IOException {
        File file = createTempFile("Hello, World!");
        InputStream stream = new TikaInputStream(file);

        assertEquals(
                "The file returned by the getFile() method should"
                + " be the file used to instantiate a TikaInputStream",
                file, TikaInputStream.get(stream).getFile());

        assertEquals(
                "The contents of the TikaInputStream should equal the"
                + " contents of the underlying file",
                "Hello, World!", readStream(stream));

        stream.close();
        assertTrue(
                "The close() method must not remove the file used to"
                + " instantiate a TikaInputStream",
                file.exists());

        file.delete();
    }

    public void testStreamBased() throws IOException {
        InputStream input =
            new ByteArrayInputStream("Hello, World!".getBytes("UTF-8"));
        InputStream stream = new TikaInputStream(input);

        File file = TikaInputStream.get(stream).getFile();
        assertTrue(file != null && file.isFile());

        assertEquals(
                "The contents of the file returned by the getFile method"
                + " should equal the contents of the TikaInputStream",
                "Hello, World!", readFile(file));

        assertEquals(
                "The contents of the TikaInputStream should not get modified"
                + " by reading the file first",
                "Hello, World!", readStream(stream));

        stream.close();
        assertFalse(
                "The close() method must remove the temporary file created"
                + " by a TikaInputStream",
                file.exists());
    }

    private File createTempFile(String data) throws IOException {
        File file = File.createTempFile("tika-", ".tmp");
        OutputStream stream = new FileOutputStream(file);
        try {
            stream.write(data.getBytes("UTF-8"));
        } finally {
            stream.close();
        }
        return file;
    }

    private String readFile(File file) throws IOException {
        InputStream stream = new FileInputStream(file);
        try {
            return readStream(stream);
        } finally {
            stream.close();
        }
    }

    private String readStream(InputStream stream) throws IOException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        IOUtils.copy(stream, buffer);
        return buffer.toString("UTF-8");
    }

}

TIKA-153: Allow passing of files or memory buffers to parsers

Add an initial test case for verifying the TikaInputStream functionality

git-svn-id: fa8893aa956664a85c8d981696777ef1db2d462a@938495 13f79535-47bb-0310-9956-ffa450edef68


package info.u_team.u_team_test.init;

import net.minecraftforge.event.world.BiomeLoadingEvent;
import net.minecraftforge.eventbus.api.*;

public class TestBiomeLoadingFeatures {

	private static void biomeLoadingAddition(BiomeLoadingEvent event) {
	}

	public static void registerForge(IEventBus bus) {
		bus.addListener(EventPriority.HIGH, TestBiomeLoadingFeatures::biomeLoadingAddition);
	}

}

Add test biome loading features

Add test biome loading features


package org.spoofax.interpreter.library.ssl;

import io.usethesource.capsule.Map;
import io.usethesource.capsule.Set;

import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.core.InterpreterException;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;
import java.util.Iterator;

public class SSL_immutable_map_intersect_set extends AbstractPrimitive {

    protected SSL_immutable_map_intersect_set() {
        super("SSL_immutable_map_intersect_set", 1, 1);
    }

    @Override
    public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs)
            throws InterpreterException {
        if(!(env.current() instanceof StrategoImmutableMap)) {
            return false;
        }
        if(!(targs[0] instanceof StrategoImmutableSet)) {
            return false;
        }

        final Map.Transient<IStrategoTerm, IStrategoTerm> one = ((StrategoImmutableMap) env.current()).backingMap.asTransient();
        final Set.Immutable<IStrategoTerm> other = ((StrategoImmutableSet) targs[0]).backingSet;
        for(Iterator<IStrategoTerm> iterator = one.keyIterator(); iterator.hasNext(); ) {
            IStrategoTerm key = iterator.next();
            if(!other.contains(key)) {
                iterator.remove();
            }
        }

        env.setCurrent(new StrategoImmutableMap(one.freeze()));
        return true;
    }
}

Add map masking operation: intersecting with a set


import java.util.*;
class CoxeterElement {
    private int[] expression;
    private int rank = 0;
    private int length;

    public CoxeterElement(int[] input, int rank) {
	boolean validElement = true;

	// Check all generators are legal
	for(int i = 0; i < input.length; i++) {
	    if ((input[i] > rank) | (input[i] < 1)) {
		validElement = false;
	    }
	}

	if (validElement) {
	    this.rank = rank;
	    this.length = input.length;
	    this.expression = new int[length];
	    for(int i = 0; i < input.length; i++) {
		expression[i] = input[i];
	    }
	}
	else {
	    System.out.println("Invalid element");
	}
    }

    public Element toPermutation() {
	int[] permutation = new int[rank];
	int temp;
	int generator;
	Element answer;

	for (int i = 0; i < rank; i++) {
	    permutation[i] = i + 1;
	}
	for (int i = 0; i < length; i++) {
	    generator = expression[i];
	    if (generator > 1) {
		temp = permutation[generator - 2];
		permutation[generator - 2] = permutation[generator - 1];
		permutation[generator - 1] = temp;
	    }
	    else {
		temp = permutation[0];
		permutation[0] = -1*permutation[1];
		permutation[1] = -1*temp;
	    }
	}
	answer = new Element(permutation);
	return answer;
    }

}

Add class to deal with expressions in terms of generators


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

/**
 * @author Franz Wilhelmstötter
 * @version !__version__!
 * @since !__version__!
 */
public class Springsteen {
}

Implement a variation of the Knapsack problem.

https://programmers.stackexchange.com/questions/326378/finding-the-best-combination-of-sets-that-gives-the-maximum-number-of-unique-ite


package com.papier.jurani;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by Angellica on 3/23/2016.
 */
public class ChosenTargetActivity extends AppCompatActivity {

    private String chosenPlayer;
    private String chosenTask;
    private String chosenTarget;
    private TextView thePlayer;
    private TextView theTask;
    private TextView theTarget;
    private Button repeatGame;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chosen_target);
        Toolbar toolbar = (Toolbar) findViewById(R.id.chosen_target_toolbar);
        setSupportActionBar(toolbar);

        chosenPlayer = getIntent().getExtras().getString("player");
        chosenTask = getIntent().getExtras().getString("task");
        chosenTarget = getIntent().getExtras().getString("target");

        thePlayer = (TextView) findViewById(R.id.player_text);
        thePlayer.setText(chosenPlayer);

        theTask = (TextView) findViewById(R.id.task_text);
        theTask.setText(chosenTask);

        theTarget = (TextView) findViewById(R.id.chosen_target);
        theTarget.setText(chosenTarget);

        repeatGame = (Button) findViewById(R.id.repeat_game_button);
        repeatGame.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }
}

Add new activity: chosen target activity.


package imagej.core.tools.global;

import imagej.ImageJ;
import imagej.ext.display.event.input.KyPressedEvent;
import imagej.ext.module.ModuleInfo;
import imagej.ext.module.ModuleService;
import imagej.ext.tool.AbstractTool;
import imagej.ext.tool.Tool;
import imagej.util.Log;

@Tool(name = "Keyboard Shortcuts", global = true, priority = Integer.MIN_VALUE)
public class AcceleratorHandler extends AbstractTool {

	private final ModuleService moduleService;

	public AcceleratorHandler() {
		moduleService = ImageJ.get(ModuleService.class);
	}

	@Override
	public boolean onKeyDown(final KyPressedEvent evt) {
		// TODO: enquire the OptionService whether the Control modifier should be
		// forced
		final ModuleInfo moduleInfo =
			moduleService.getModuleForAccelerator(evt.getAcceleratorString(true));
		if (moduleInfo == null) return false;
		moduleService.run(moduleInfo);
		return true;
	}
}

Add a global tool that handles accelerators in image windows

This tool actually can fake the Control key.

Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de>

This used to be revision r4194.


/*******************************************************************************
 * This file is part of OpenNMS(R).
 *
 * Copyright (C) 2012-2016 The OpenNMS Group, Inc.
 * OpenNMS(R) is Copyright (C) 1999-2016 The OpenNMS Group, Inc.
 *
 * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.
 *
 * OpenNMS(R) 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.
 *
 * OpenNMS(R) 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 OpenNMS(R).  If not, see:
 *      http://www.gnu.org/licenses/
 *
 * For more information contact:
 *     OpenNMS(R) Licensing <license@opennms.org>
 *     http://www.opennms.org/
 *     http://www.opennms.com/
 *******************************************************************************/

package org.opennms.features.topology.plugins.topo.bsm;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class ReductionKeyVertexTest {

    @Test
    public void canGetLabelFromReductionKey() {
        assertEquals("nodeDown:10", ReductionKeyVertex.getLabelFromReductionKey("uei.opennms.org/nodes/nodeDown::10"));
        assertEquals("nodeLostService:DNS", ReductionKeyVertex.getLabelFromReductionKey("uei.opennms.org/nodes/nodeLostService::9:2600:5800:f2a2:0000:02d0:b7ff:fe25:3e1c:DNS"));
        assertEquals("dataCollectionFailed:48", ReductionKeyVertex.getLabelFromReductionKey("uei.opennms.org/nodes/dataCollectionFailed::48"));
        assertEquals("this_is_a_really_long_re", ReductionKeyVertex.getLabelFromReductionKey("this_is_a_really_long_reduction_key_that_shouldnt_match_the_know_pattern"));
    }
}

BSM-177: Add test to validate the getLabelFromReductionKey() function.


/*
 * Copyright (c) 2017 3TUSK, Seraph-JACK, yesterday17, et al.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

package info.tritusk.mooncakecraft.crafting;

import com.google.gson.JsonObject;
import net.minecraft.init.Items;
import net.minecraft.inventory.InventoryCrafting;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.IRecipe;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.item.crafting.ShapelessRecipes;
import net.minecraft.util.NonNullList;
import net.minecraftforge.common.crafting.IRecipeFactory;
import net.minecraftforge.common.crafting.JsonContext;
import net.minecraftforge.oredict.ShapelessOreRecipe;

public class RemainBottleRecipeFactory implements IRecipeFactory{

    @Override
    public IRecipe parse(JsonContext context, JsonObject json) {
        ShapelessOreRecipe recipe = ShapelessOreRecipe.factory(context, json);

        return new RemainBottleRecipe("mooncakecraft:remain_bottle", recipe.getRecipeOutput(), recipe.getIngredients());
    }

    public static class RemainBottleRecipe extends ShapelessRecipes {
        public RemainBottleRecipe(String group, ItemStack output, NonNullList<Ingredient> ingredients) {
            super(group, output, ingredients);
        }

        @Override
        public NonNullList<ItemStack> getRemainingItems(InventoryCrafting inv)
        {
            NonNullList<ItemStack> nonnulllist = NonNullList.<ItemStack>withSize(inv.getSizeInventory(), ItemStack.EMPTY);

            for (int i = 0; i < nonnulllist.size(); ++i)
            {
                ItemStack itemstack = inv.getStackInSlot(i);

                if(itemstack.isItemEqual(new ItemStack(Items.POTIONITEM))) {
                    nonnulllist.set(i, new ItemStack(Items.GLASS_BOTTLE, 1));
                    continue;
                }

                nonnulllist.set(i, net.minecraftforge.common.ForgeHooks.getContainerItem(itemstack));
            }

            return nonnulllist;
        }
    }
}

Remove IRecipe and uses IRecipeFactory & Recipe files instead.


package org.apache.logging.log4j.core.config;

import java.util.Comparator;

import org.apache.logging.log4j.core.util.Assert;

/**
 * Comparator for classes annotated with {@link Order}.
 *
 * @since 2.1
 */
public class OrderComparator implements Comparator<Class<?>> {
    @Override
    public int compare(final Class<?> lhs, final Class<?> rhs) {
        final Order lhsOrder = Assert.requireNonNull(lhs, "lhs").getAnnotation(Order.class);
        final Order rhsOrder = Assert.requireNonNull(rhs, "rhs").getAnnotation(Order.class);
        if (lhsOrder == null && rhsOrder == null) {
            // both unannotated means we can't really compare them
            return 0;
        }
        // if only one class is @Order-annotated, then prefer that one
        if (rhsOrder == null) {
            return -1;
        }
        if (lhsOrder == null) {
            return 1;
        }
        // larger value means higher priority
        return Integer.signum(rhsOrder.value() - lhsOrder.value());
    }
}

Add Comparator for @Order-annotated classes.


package de.asw.courses.web2016.demo.backend.servlet.introspect;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/introspect/*")
public class HttpRequestIntrospectionServlet extends HttpServlet {

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String httpMethod = req.getMethod();
		String requestUri = req.getRequestURI();

		String queryString = req.getQueryString();

		PrintWriter out = resp.getWriter();

		out.println("Request");
		out.printf("%s %s?%s%n", httpMethod, requestUri, queryString);
		out.println();

		out.println("Headers");
		for (String headerName : Collections.list(req.getHeaderNames())) {
			String headerValue = req.getHeader(headerName);
			out.printf("%s %s%n", headerName, headerValue);
		}
		out.println();

		out.println("Parameters");
		for (String parameterName : Collections.list(req.getParameterNames())) { // req.getParameterMap()
			String parameterValue = Arrays.toString(req.getParameterValues(parameterName));
			out.printf("%s %s%n", parameterName, parameterValue);
		}
		out.println();

		out.println("Request Body");
		try (Scanner scanner = new Scanner(req.getReader())) {
			while (scanner.hasNextLine()) {
				System.out.println(scanner.nextLine());
			}
		}
	}
}

Add example for http servlet request introspection


package at.ac.tuwien.inso.method_security_tests;

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

import at.ac.tuwien.inso.service.TagService;

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

    @Autowired
    private TagService tagService;

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void searchForSubjectsNotAuthenticated() {
        tagService.findAll();
    }

    @Test
    @WithMockUser
    public void searchForSubjectsAuthenticated() {
        tagService.findAll();
    }
}

Add tests for TagService method security


/* ********************************************************************
    Licensed to Jasig under one or more contributor license
    agreements. See the NOTICE file distributed with this work
    for additional information regarding copyright ownership.
    Jasig 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.bedework.util.elasticsearch;

import org.bedework.util.jmx.ConfBaseMBean;

/** Parameters for interactiosn with elastic search
 *
 * @author douglm
 *
 */
public interface EsCtlMBean extends ConfBaseMBean, IndexProperties {
  String serviceName = "org.bedework:service=esctl";

  /**
   * @return list of indexes maintained by indexer.
   */
  String listIndexes();
}

Fix up case of name

Fix up case of name


/*
 * 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.
 */

/* $Id$ */

package org.apache.xmlgraphics.ps.dsc.events;

import java.awt.Rectangle;
import java.awt.geom.Rectangle2D;

import junit.framework.TestCase;

import org.apache.xmlgraphics.ps.dsc.DSCCommentFactory;

public class DSCCommentBoundingBoxTestCase extends TestCase {

    public void testBoundingBox() throws Exception {
        DSCComment comment = DSCCommentFactory.createDSCCommentFor("BoundingBox");
        DSCCommentBoundingBox bbox = (DSCCommentBoundingBox)comment;
        bbox.parseValue("289 412 306 429");
        Rectangle refRect = new Rectangle(289, 412, 306 - 289, 429 - 412);
        assertEquals(refRect, bbox.getBoundingBox());

        comment = DSCCommentFactory.createDSCCommentFor("BoundingBox");
        bbox = (DSCCommentBoundingBox)comment;
        bbox.parseValue("289.12 412.2 306.777 429.11");
        Rectangle2D refRect2D = new Rectangle2D.Double(
                289.12, 412.2, 306.777 - 289.12, 429.11 - 412.2);
        assertEquals(refRect2D, bbox.getBoundingBox());

        comment = DSCCommentFactory.createDSCCommentFor("HiResBoundingBox");
        bbox = (DSCCommentHiResBoundingBox)comment;
        bbox.parseValue("289.12 412.2 306.777 429.11");
        refRect2D = new Rectangle2D.Double(
                289.12, 412.2, 306.777 - 289.12, 429.11 - 412.2);
        assertEquals(refRect2D, bbox.getBoundingBox());
    }

}

Test case for the BoundingBox implementation.

git-svn-id: c1447309447e562cc43d70ade9fe6c70ff9b4cec@592750 13f79535-47bb-0310-9956-ffa450edef68


package dev.codefoundry.string;

public class DeleteCharsToEqualizeStrings {
	public int solve(String a, String b) {
        int[][] dp = new int[a.length() + 1][b.length() + 1];

        for (int i = 0; i <= a.length(); i++) {
            for (int j = 0; j <= b.length(); j++) {
                if (i == 0 || j == 0) {
                    dp[i][j] = i + j;
                } else if (a.charAt(i - 1) == b.charAt(j - 1)) {
                    dp[i][j] = dp[i - 1][j - 1];
                } else {
                    dp[i][j] = 1 + Math.min(dp[i][j - 1], dp[i - 1][j]);
                }
            }
        }

        return dp[a.length()][b.length()];
    }

	public static void main(String[] args) {
		System.out.println(new DeleteCharsToEqualizeStrings().solve("a", "bb"));
	}
}

Delete Chars to equalize strings

Delete Chars to equalize strings


/*
 * $Id$
 */

/*

 Copyright (c) 2000-2016 Board of Trustees of Leland Stanford Jr. University,
 all rights reserved.

 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
 STANFORD UNIVERSITY 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.

 Except as contained in this notice, the name of Stanford University shall not
 be used in advertising or otherwise to promote the sale, use or other dealings
 in this Software without prior written authorization from Stanford University.

 */

package org.lockss.plugin.highwire;

import org.lockss.filter.pdf.ExtractingPdfFilterFactory;
import org.lockss.pdf.*;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.util.Logger;

/**
 * A pdf filter that handles the more challenging PDFs of child plugins where pdfplus
 * files have non-substantive changes (annotation uris, ordering, etc). In this
 * case scrape out the content text for comparison.
 * This code modified from BaseAtyponScrapingPdfFilterFactory  @author alexohlson
 *
 */
public class HighWireDrupalScrapingPdfFilterFactory extends ExtractingPdfFilterFactory {

  private static final Logger log = Logger.getLogger(HighWireDrupalScrapingPdfFilterFactory.class);

  /*
   * Many pdf files have the CreationDate and ModDate and the two ID numbers in the trailer
   * vary from collection to collection. Filter them out to avoid incorrect hash failures.
   * This is a scraping filter to it also returns just the actual pdf content and not the layout.
   */
  @Override
  public void transform(ArchivalUnit au, PdfDocument pdfDocument)
      throws PdfException {

    pdfDocument.unsetCreationDate();
    pdfDocument.unsetModificationDate();
    pdfDocument.unsetMetadata();
    pdfDocument.unsetCreator();
    pdfDocument.unsetProducer();
    pdfDocument.unsetAuthor();
    pdfDocument.unsetTitle();
    pdfDocument.unsetSubject();
    pdfDocument.unsetKeywords();
    PdfUtil.normalizeTrailerId(pdfDocument);
    PdfUtil.normalizeAllTokenStreams(pdfDocument);
  }
}

Use Drupal PDF hash filter

Use Drupal PDF hash filter


/*
 * 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 info.avalon566.shardingscaling.sync.mysql.binlog.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;
import org.junit.Before;
import org.junit.Test;
import java.math.BigDecimal;

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

public class DecimalValueDecoderTest {

    private int meta;

    @Before
    public void setUp() {
        meta = 14 << 8;
        meta += 4;
    }

    @Test
    public void assertDecodePositiveNewDecimal() {
        byte[] newDecimalBytes = ByteBufUtil.decodeHexDump("810DFB38D204D2");
        ByteBuf newDecimalByteBuf = Unpooled.buffer(newDecimalBytes.length);
        newDecimalByteBuf.writeBytes(newDecimalBytes);
        BigDecimal actual = (BigDecimal) DecimalValueDecoder.decodeNewDecimal(meta, newDecimalByteBuf);
        assertThat(actual.toString(), is("1234567890.1234"));
    }

    @Test
    public void assertDecodeNegativeNewDecimal() {
        byte[] newDecimalBytes = ByteBufUtil.decodeHexDump("7EF204C72DFB2D");
        ByteBuf newDecimalByteBuf = Unpooled.buffer(newDecimalBytes.length);
        newDecimalByteBuf.writeBytes(newDecimalBytes);
        BigDecimal actual = (BigDecimal) DecimalValueDecoder.decodeNewDecimal(meta, newDecimalByteBuf);
        assertThat(actual.toString(), is("-1234567890.1234"));
    }
}

Add unit test for DecimalValueDecoder

Add unit test for DecimalValueDecoder


/**
 *
 * Copyright 2021 Florian Schmaus
 *
 * 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.jivesoftware.smackx.jingle.element;

import static org.junit.jupiter.api.Assertions.assertEquals;

import org.jivesoftware.smack.packet.StreamOpen;

import org.junit.jupiter.api.Test;

public class JingleTest {

    @Test
    public void noRedundantNamespaceTest() {
        Jingle.Builder jingleBuilder = Jingle.builder("test-id");
        jingleBuilder.setSessionId("MySession");
        jingleBuilder.setAction(JingleAction.content_accept);

        JingleContent.Builder jingleContentBuilder = JingleContent.getBuilder();
        jingleContentBuilder.setName("Hello world");
        jingleContentBuilder.setCreator(JingleContent.Creator.initiator);

        jingleBuilder.addJingleContent(jingleContentBuilder.build());
        Jingle iq = jingleBuilder.build();

        String actualXml = iq.toXML(StreamOpen.CLIENT_NAMESPACE).toString();
        String expectedXml
                        = "<iq id='test-id' type='set'>"
                        + "<jingle xmlns='urn:xmpp:jingle:1' action='content-accept' sid='MySession'>"
                        + "<content creator='initiator' name='Hello world'/>"
                        + "</jingle></iq>";
        assertEquals(expectedXml, actualXml);
    }
}

[jingle] Add unit test to check that there are no redundant namespaces

Related to SMACK-917.


package de.fu_berlin.agdb.crepe.rest.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * A REST controller to serve data about the available locations
 * and allow the user to add new ones.
 */
@RestController
@RequestMapping("/locations")
public class LocationMetaDataController {

}

Add REST controller for new database schema


/*
 * 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.jackrabbit.oak.plugins.document;

import org.apache.jackrabbit.oak.plugins.document.util.Utils;
import org.apache.jackrabbit.oak.spi.state.NodeBuilder;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;

import static org.junit.Assert.assertNull;

@Ignore
public class UpdateLimitTest {

    @Rule
    public DocumentMKBuilderProvider builderProvider = new DocumentMKBuilderProvider();

    private DocumentNodeStore ns;
    private DocumentStore store;
    private String testId;

    @Before
    public void before() {
        ns = builderProvider.newBuilder().getNodeStore();
        store = ns.getDocumentStore();
        testId = Utils.getIdFromPath("/test");
    }

    @Test
    public void rebase() throws Exception {
        NodeBuilder builder = someChanges(ns.getRoot().builder());
        for (int i = 0; i < 20; i++) {
            ns.rebase(builder);
            assertNull(store.find(Collection.NODES, testId));
        }
    }

    @Test
    public void reset() {
        NodeBuilder builder = someChanges(ns.getRoot().builder());
        for (int i = 0; i < 20; i++) {
            ns.reset(builder);
            someChanges(builder);
            assertNull(store.find(Collection.NODES, testId));
        }
    }

    private NodeBuilder someChanges(NodeBuilder root) {
        NodeBuilder test = root.child("test");
        for (int i = 0; i < 23; i++) {
            test.child("node-" + i);
        }
        return root;
    }
}

Update count increases with rebase

OAK-4503: Update count increases with rebase

Add ignored test

git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1750052 13f79535-47bb-0310-9956-ffa450edef68


package de.terrestris.shogun2.service;

import de.terrestris.shogun2.dao.UserGroupDao;
import de.terrestris.shogun2.model.UserGroup;

public class UserGroupServiceTest extends
		AbstractSecuredPersistentObjectServiceTest<UserGroup, UserGroupDao<UserGroup>, UserGroupService<UserGroup, UserGroupDao<UserGroup>>> {

	/**
	 *
	 * @throws Exception
	 */
	public void setUpImplToTest() throws Exception {
		implToTest = new UserGroup();
	}

	@Override
	protected UserGroupService<UserGroup, UserGroupDao<UserGroup>> getCrudService() {
		return new UserGroupService<UserGroup, UserGroupDao<UserGroup>>();
	}

	@SuppressWarnings("unchecked")
	@Override
	protected Class<UserGroupDao<UserGroup>> getDaoClass() {
		return (Class<UserGroupDao<UserGroup>>) new UserGroupDao<UserGroup>().getClass();
	}

}

Add a test class for the UserGroupService


/*
 * Copyright (c) 2015 Inocybe and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.ovsdb.openstack.netvirt;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;

import java.net.HttpURLConnection;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import org.opendaylight.neutron.spi.NeutronFloatingIP;
import org.opendaylight.ovsdb.openstack.netvirt.api.Action;
import org.opendaylight.ovsdb.openstack.netvirt.impl.NeutronL3Adapter;

/**
 * Unit test for {@link FloatingIPHandler}
 */
@RunWith(MockitoJUnitRunner.class)
public class FloatingIPHandlerTest {

    @InjectMocks private FloatingIPHandler floatingHandler = mock(FloatingIPHandler.class, Mockito.CALLS_REAL_METHODS);
    @InjectMocks private NeutronL3Adapter neutronL3Adapter = mock(NeutronL3Adapter.class);

    @Test
    public void testCanCreateFloatingIP(){
        assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canCreateFloatingIP(mock(NeutronFloatingIP.class)));
    }

    @Test
    public void testCanUpdateFloatingIP(){
        assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canUpdateFloatingIP(mock(NeutronFloatingIP.class), mock(NeutronFloatingIP.class)));
    }

    @Test
    public void testCanDeleteFloatingIP(){
        assertEquals("Error, did not return the correct HTTP status code", HttpURLConnection.HTTP_OK, floatingHandler.canDeleteFloatingIP(mock(NeutronFloatingIP.class)));
    }

    @Test
    public void testProcessEvent(){
        NorthboundEvent ev = mock(NorthboundEvent.class);

        when(ev.getNeutronFloatingIP()).thenReturn(mock(NeutronFloatingIP.class));
        when(ev.getAction()).thenReturn(Action.UPDATE);

        verifyNoMoreInteractions(neutronL3Adapter);

        floatingHandler.processEvent((AbstractEvent) ev);

        verify(neutronL3Adapter, times(1)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.ADD);
        verify(neutronL3Adapter, times(0)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());;

        when(ev.getAction()).thenReturn(Action.DELETE);
        verify(neutronL3Adapter, times(0)).handleNeutronFloatingIPEvent(ev.getNeutronFloatingIP(), ev.getAction());;
    }
}

Add JUnit testing for FloatingIPHandler class.

Change-Id: I1a5dc5fb7c7bc9b4a856925bb0ff731bf0d48e8b
Signed-off-by: Alexis de Talhouët <3f85d13b1d0fb141169e8f22f55d7ee87dcd5f00@inocybe.com>


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

package io.michaelrocks.libphonenumber.android;

import java.io.InputStream;

class ResourceMetadataLoader implements MetadataLoader {
  private final Class<?> loaderClass;

  public ResourceMetadataLoader() {
    this(ResourceMetadataLoader.class);
  }

  public ResourceMetadataLoader(Class<?> loaderClass) {
    this.loaderClass = loaderClass;
  }

  @Override
  public InputStream loadMetadata(String metadataFileName) {
    return loaderClass.getResourceAsStream(metadataFileName);
  }
}

Implement a metadata loader that loads data from resources


package org.metaborg.core.project;

import java.util.Map;
import java.util.concurrent.ConcurrentMap;

import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.metaborg.core.config.ConfigRequest;
import org.metaborg.core.config.IProjectConfig;
import org.metaborg.core.config.IProjectConfigService;
import org.metaborg.core.messages.StreamMessagePrinter;
import org.metaborg.core.source.ISourceTextService;
import org.metaborg.util.log.ILogger;
import org.metaborg.util.log.LoggerUtils;

import com.google.common.collect.Maps;
import com.google.inject.Inject;

public class ConfigBasedProjectService implements IProjectService {
    private static final ILogger logger = LoggerUtils.logger(ConfigBasedProjectService.class);

    private final ConcurrentMap<FileName, IProject> projects = Maps.newConcurrentMap();

    private final ISourceTextService sourceTextService;
    private final IProjectConfigService projectConfigService;

    @Inject public ConfigBasedProjectService(ISourceTextService sourceTextService,
        IProjectConfigService projectConfigService) {
        this.sourceTextService = sourceTextService;
        this.projectConfigService = projectConfigService;
    }

    @Override public IProject get(FileObject resource) {
        IProject project = getProject(resource);
        if(project == null) {
            project = findProject(resource);
        }
        return project;
    }

    private IProject getProject(FileObject resource) {
        for(Map.Entry<FileName,IProject> entry : projects.entrySet()) {
            if(resource.getName().isAncestor(entry.getKey())) {
                return entry.getValue();
            }
        }
        return null;
    }

    private IProject findProject(FileObject resource) {
        try {
            FileObject dir = (resource.isFolder() ? resource : resource.getParent());
            while(dir != null) {
                FileName name = dir.getName();
                if(projectConfigService.available(dir)) {
                    final ConfigRequest<IProjectConfig> configRequest = projectConfigService.get(dir);
                    if(!configRequest.valid()) {
                        logger.error("Errors occurred when retrieving project configuration from project directory {}", dir);
                        configRequest.reportErrors(new StreamMessagePrinter(sourceTextService, false, false, logger));
                    }

                    final IProject project = new Project(dir, configRequest.config());
                    IProject prevProject;
                    if((prevProject = projects.putIfAbsent(name, project)) != null) {
                        logger.warn("Project with location {} already exists", name);
                        return prevProject;
                    }
                    return project;
                }
                dir = dir.getParent();
            }
        } catch(FileSystemException e) {
            logger.error("Error while searching for project configuration.",e);
        }
        logger.warn("No project configuration file was found for {}.",resource);
        return null;
    }
}

Add project service that searches for config file.


package org.jdesktop.swingx.painter;

import org.jdesktop.beans.AbstractBeanInfoTest;

public class AlphaPainterBeanInfoTest extends AbstractBeanInfoTest<AlphaPainter<Object>> {
    /**
     * {@inheritDoc}
     */
    @Override
    protected AlphaPainter<Object> createInstance() {
        return new AlphaPainter<Object>();
    }
}

Add bean test for AlphaPainter.

Add bean test for AlphaPainter.


import java.util.concurrent.TimeUnit;

import model.Model;

public class GameLoop {
	private Model model;
	public GameLoop(Model model){
		this.model = model;
	}
	public void startLoop(){
		this.gameLoop();
	}
	private void gameLoop(){
		while(true){
			model.update();
			try{
			TimeUnit.MILLISECONDS.sleep(18);
			}catch(Exception e){

			}
		}
	}
}

Put the gameloop class up

Put the gameloop class up


/**
 * 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.
 *
 * Copyright 2012-2014 the original author or authors.
 */
package org.assertj.core.api.iterable;

import static org.assertj.core.util.Arrays.array;

import org.assertj.core.api.AbstractIterableAssert;
import org.assertj.core.api.ConcreteIterableAssert;
import org.assertj.core.api.IterableAssertBaseTest;

import static org.mockito.Mockito.verify;

/**
 * Tests for <code>{@link AbstractIterableAssert#containsSubsequence(Object[])}</code>.
 *
 * @author Harry Cummings
 */
public class IterableAssert_containsSubsequence_Test extends IterableAssertBaseTest {

  @Override
  protected ConcreteIterableAssert<Object> invoke_api_method() {
	return assertions.containsSubsequence("Luke", "Leia");
  }

  @Override
  protected void verify_internal_effects() {
	verify(iterables).assertContainsSubsequence(getInfo(assertions), getActual(assertions), array("Luke", "Leia"));
  }
}

Add tests for containsSubsequence public API method.


package com.github.ivbaranov.rxbluetooth;

import android.bluetooth.BluetoothProfile;

/**
 * Event container class.  Contains state (whether the service was just connected or
 * disconnected), profile type and {@link BluetoothProfile}. When service state is {@link
 * State#DISCONNECTED} the mBluetoothProfile is null.
 */
public class ServiceEvent {

  public enum State {
    CONNECTED,
    DISCONNECTED
  }

  private State mState;
  private int mProfileType;
  private BluetoothProfile mBluetoothProfile;

  public ServiceEvent(State state, int profileType, BluetoothProfile bluetoothProfile) {
    mState = state;
    mProfileType = profileType;
    mBluetoothProfile = bluetoothProfile;
  }

  public State getState() {
    return mState;
  }

  public int getProfileType() {
    return mProfileType;
  }

  public BluetoothProfile getBluetoothProfile() {
    return mBluetoothProfile;
  }

  @Override public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;

    ServiceEvent that = (ServiceEvent) o;

    if (mProfileType != that.mProfileType) return false;
    if (mState != that.mState) return false;
    return !(mBluetoothProfile != null ? !mBluetoothProfile.equals(that.mBluetoothProfile)
        : that.mBluetoothProfile != null);
  }

  @Override public int hashCode() {
    int result = mState.hashCode();
    result = 31 * result + mProfileType;
    result = 31 * result + (mBluetoothProfile != null ? mBluetoothProfile.hashCode() : 0);
    return result;
  }

  @Override public String toString() {
    return "ServiceEvent{" +
        "mState=" + mState +
        ", mProfileType=" + mProfileType +
        ", mBluetoothProfile=" + mBluetoothProfile +
        '}';
  }
}

Add service event class. It contains state, profile type and profile proxy object.


/*
  Copyright 2016, Google, 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 com.example.translate;

// [START translate_quickstart]
// Imports the Google Cloud client library
import com.google.cloud.translate.Translate;
import com.google.cloud.translate.Translate.TranslateOption;
import com.google.cloud.translate.TranslateOptions;
import com.google.cloud.translate.Translation;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    Translate translate = TranslateOptions.builder().apiKey("YOUR_API_KEY").build().service();
    // The text to translate
    String text = "Hello, world!";
    // Translates some text into Russian
    Translation translation = translate.translate(
      text,
      TranslateOption.sourceLanguage("en"),
      TranslateOption.targetLanguage("ru")
    );
    System.out.printf("Text: %s%n", text);
    System.out.printf("Translation: %s%n", translation.translatedText());
  }
}
// [END translate_quickstart]

Add Translate API quickstart sample.

samples: Add Translate API quickstart sample.


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */

public class Solution {

    public ListNode reverseList(ListNode head) {

        ListNode reversedList = null;

        while (head != null) {

            ListNode next = head.next;
            head.next = reversedList;
            reversedList = head;
            head = next;

        }

        return reversedList;

    }

}

Create : 206 Reverse Linked List

Create : 206 Reverse Linked List


package leetcode.construct_binary_tree_from_preorder_and_inorder_traversal;

import common.TreeNode;

public class Solution {
	public TreeNode buildTree(int[] preorder, int[] inorder, int pre_from, int pre_to, int in_from, int in_to){
		if(in_from == in_to || pre_from == pre_to) return null;
		int rootval = preorder[pre_from];
		TreeNode root = new TreeNode(rootval);
		int rootidx;
		for(rootidx = in_from; rootidx < in_to && inorder[rootidx] != rootval; rootidx++);
		System.err.println(rootidx);
		root.left = buildTree(preorder, inorder, pre_from + 1, pre_from + 1 + (rootidx - in_from), in_from, rootidx);
		root.right = buildTree(preorder, inorder, pre_to + 1 - (in_to - rootidx), pre_to, rootidx + 1, in_to);
		return root;
	}
	public TreeNode buildTree(int[] preorder, int[] inorder) {
		if(inorder == null || preorder == null) return null;
    	return buildTree(preorder, inorder, 0, inorder.length, 0, preorder.length);
    }

    public static void inOrder(TreeNode cur){
    	if(cur != null){
    		inOrder(cur.left);
    		System.err.print(cur.val + "->");
    		inOrder(cur.right);
    	}
    }

    public static void preOrder(TreeNode cur){
    	if(cur != null){
    		System.err.print(cur.val + "->");
    		preOrder(cur.left);
    		preOrder(cur.right);
    	}
    }

    public static void main(String[] args){
    	int[] preorder = new int[]{1, 5, 4, 9, 3, 8, 6, 7};
    	int[] inorder = new int[]{4, 9, 5, 1, 8, 3, 7, 6};
    	TreeNode ret = new Solution().buildTree(preorder, inorder);
    	preOrder(ret);
    	System.err.println("");
    	inOrder(ret);
    	System.err.println("");
    }
}

Add java solution for 105. Construct Binary Tree from Preorder and Inorder Traversal

105. Construct Binary Tree from Preorder and Inorder Traversal: https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/


package com.thinkaurelius.titan.hadoop;

import com.thinkaurelius.titan.HBaseStorageSetup;
import com.thinkaurelius.titan.diskstorage.configuration.WriteConfiguration;
import org.apache.hadoop.hbase.util.VersionInfo;
import org.junit.AfterClass;
import org.junit.BeforeClass;

import java.io.IOException;

public class HBaseIndexManagementIT extends AbstractIndexManagementIT {

    @Override
    public WriteConfiguration getConfiguration() {
        return HBaseStorageSetup.getHBaseGraphConfiguration();
    }

    @BeforeClass
    public static void startHBase() throws IOException {
        HBaseStorageSetup.startHBase();
    }

    @AfterClass
    public static void stopHBase() {
        // Workaround for https://issues.apache.org/jira/browse/HBASE-10312
        if (VersionInfo.getVersion().startsWith("0.96"))
            HBaseStorageSetup.killIfRunning();
    }
}

Add HBase-backend MapReduce re(move)index tests

Similar to 008934d24585c9a65362d1b6147b0a68a7cee5f0, except the test
cases in this commit are backed by HBase instead of Cassandra.


/**
 * Copyright (c) 2015-present Jorge Díaz All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package jorgediazest.indexchecker.model;

import jorgediazest.util.data.Data;

/**
 * @author Jorge Díaz
 */
public class DDLRecordPermissionsHelper extends IndexCheckerPermissionsHelper {

	@Override
	protected String getPermissionsClassName(Data data) {
		return "com.liferay.dynamic.data.lists.model.DDLRecordSet";
	}

	@Override
	protected long getPermissionsClassPK(Data data) {
		return data.get("recordSetId", -1L);
	}
}

Fix DDLRecord issues: due some Liferay 7 changes, all records are detected as outdated


/*******************************************************************************
 * Copyright (c) 2016 IBM Corp.
 *
 * 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.ibm.liberty.starter.it.api.v1;

import static org.junit.Assert.assertTrue;

import java.io.File;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;

import org.junit.Assert;
import org.junit.Test;

public class MicroProfileAPIJarDownloadTest {

    @Test
    public void testRepoUrl() throws Exception {
        String url = "http://localhost:" + System.getProperty("liberty.test.port") + "/start/api/v1/repo/net/wasdev/wlp/starters/ms-builder/config/0.0.1/config-0.0.1.jar";
        Client client = ClientBuilder.newClient();
        Response response = client.target(url).request("application/zip").get();
        try {
            int responseStatus = response.getStatus();
            if (responseStatus != 200) {
                Assert.fail("Expected response status 200, instead found " + responseStatus + ". Response was " + response.readEntity(String.class));
            }
            assertTrue("Config class not found", findConfig(response));
        } finally {
            response.close();
        }

    }

    private boolean findConfig(Response resp) throws Exception {
        // Read the response into an InputStream
        InputStream entityInputStream = resp.readEntity(InputStream.class);
        // Create a new ZipInputStream from the response InputStream
        ZipInputStream zipIn = new ZipInputStream(entityInputStream);
        // This system property is being set in the liberty-starter-application/build.gradle file
        String tempDir = System.getProperty("liberty.temp.dir");
        File file = new File(tempDir + "/config.jar");
        System.out.println("Creating zip file: " + file.toString());
        file.getParentFile().mkdirs();
        ZipEntry inputEntry = null;
        boolean found = false;
        while ((inputEntry = zipIn.getNextEntry()) != null) {
            String entryName = inputEntry.getName();
            System.out.println("File: "+entryName);
            if ("org/eclipse/microprofile/config/Config.class".equals(entryName)) {
                System.out.println("Found Config.class file.");
                found = true;
            }
            zipIn.closeEntry();
        }
        zipIn.close();
        return found;
    }
}

Add integration test for jar files.

Add integration test for jar files.

Signed-off-by: Kate Stanley <59c12a62b1d23be702ac06d493bad7887a15d0c5@uk.ibm.com>


package com.test.graphs;

import com.graphs.GraphEdgeListRepresentation;

import junit.framework.TestCase;

public class TestGraphEdgeListRepresentation extends TestCase{

    public void testGraphEdgeListRepresentationOperations() {

        //Undirected graph
        GraphEdgeListRepresentation graph = new GraphEdgeListRepresentation(10, false);
        graph.addEdge(0, 1);
        graph.addEdge(0, 6);
        graph.addEdge(0, 8);
        graph.addEdge(1, 4);
        graph.addEdge(1, 6);
        graph.addEdge(1, 9);
        graph.addEdge(2, 4);
        graph.addEdge(2, 6);
        graph.addEdge(3, 4);
        graph.addEdge(3, 5);
        graph.addEdge(3, 8);
        graph.addEdge(4, 5);
        graph.addEdge(4, 9);
        graph.addEdge(7, 8);
        graph.addEdge(7, 9);
        assertEquals(15, graph.getE_Size());
        assertEquals(10, graph.getV_Size());
        assertEquals(true, graph.hasEdge(7, 8));
        assertEquals(true, graph.hasEdge(8, 7));
        assertEquals(false, graph.hasEdge(0, 5));
//        System.out.println(graph.toString());

      //Directed graph
        graph = new GraphEdgeListRepresentation(10, true);
        graph.addEdge(0, 1);
        graph.addEdge(0, 6);
        graph.addEdge(0, 8);
        graph.addEdge(1, 4);
        graph.addEdge(1, 6);
        graph.addEdge(1, 9);
        graph.addEdge(2, 4);
        graph.addEdge(2, 6);
        graph.addEdge(3, 4);
        graph.addEdge(3, 5);
        graph.addEdge(3, 8);
        graph.addEdge(4, 5);
        graph.addEdge(4, 9);
        graph.addEdge(7, 8);
        graph.addEdge(7, 9);
        assertEquals(15, graph.getE_Size());
        assertEquals(10, graph.getV_Size());
        assertEquals(true, graph.hasEdge(7, 8));
        assertEquals(false, graph.hasEdge(8, 7));
        assertEquals(false, graph.hasEdge(0, 5));
        System.out.println(graph.toString());
    }

}

Add JUnit to test the Edge list representation of graph


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

package org.onosproject.vtnrsc.virtualport;

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

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

import com.google.common.testing.EqualsTester;

/**
 * Unit tests for VirtualPortId class.
 */
public class VirtualPortIdTest {

    final VirtualPortId virtualPortId1 = VirtualPortId.portId("1");
    final VirtualPortId sameAsVirtualPortId1 = VirtualPortId.portId("1");
    final VirtualPortId virtualPortId2 = VirtualPortId.portId("2");

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

    /**
     * Checks the operation of equals().
     */
    @Test
    public void testEquals() {
        new EqualsTester().addEqualityGroup(virtualPortId1, sameAsVirtualPortId1)
                .addEqualityGroup(virtualPortId2).testEquals();
    }

    /**
     * Checks the construction of a VirtualPortId object.
     */
    @Test
    public void testConstruction() {
        final String vPortIdValue = "aaa";
        final VirtualPortId virtualPortId = VirtualPortId.portId(vPortIdValue);
        assertThat(virtualPortId, is(notNullValue()));
        assertThat(virtualPortId.portId(), is(vPortIdValue));

    }
}

[ONOS-3252] Add the junit test code of VirtualPortId

Change-Id: Ia26594913a7c33406379a0015464c89567790a42


package learntocode.javaapi.io_and_nio.nio;

import java.nio.file.Files;
import java.nio.file.Path;

/**
 * Show some methods
 */
public class FileParameters {
    public static void main(String[] args) {
        Path path = FilesCreatorNIO.createFiles()[0];

        checkAndPrint("Writable", Files::isWritable, path);
        checkAndPrint("Readable", Files::isReadable, path);
        checkAndPrint("Executable", Files::isExecutable, path);
        checkAndPrint("Symbolic Link", Files::isSymbolicLink, path);
        checkAndPrint("Regular file", Files::isRegularFile, path);
        checkAndPrint("Directory", Files::isDirectory, path);
    }

    private static void checkAndPrint(String checkName, BooleanByPathFuncInterface function, Path p) {
        if (function.check(p))
            System.out.println("File IS " + checkName );
        else
            System.out.println("File IS NOT " + checkName);
    }

    private interface BooleanByPathFuncInterface {
        boolean check(Path p);
    }
}

Add file parameters checker to show, what you can get with NIO


package org.verapdf.model.impl.pb.pd;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.verapdf.model.baselayer.Object;
import org.verapdf.model.impl.BaseTest;
import org.verapdf.model.pdlayer.PDAcroForm;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author Evgeniy Muravitskiy
 */
public class PBoxPDAcroFormTest extends BaseTest {

	public static final String FILE_RELATIVE_PATH = "pd/InteractiveObjects.pdf";

	@BeforeClass
	public static void setUp() throws URISyntaxException, IOException {
		expectedType = PBoxPDAcroForm.ACRO_FORM_TYPE;
		expectedID = null;

		setUp(FILE_RELATIVE_PATH);
		actual = new PBoxPDAcroForm(document.getDocumentCatalog().getAcroForm());
	}

	@Test
	public void testNeedAppearancesMethod() {
		Assert.assertFalse(((PDAcroForm) actual).getNeedAppearances());
	}

	@Test
	public void testFormFieldLink() {
		List<? extends Object> formFields = actual.getLinkedObjects(PBoxPDAcroForm.FORM_FIELDS);
		Assert.assertEquals(1, formFields.size());
		for (Object object : formFields) {
			Assert.assertEquals(PBoxPDFormField.FORM_FIELD_TYPE, object.getType());
		}
	}

	@AfterClass
	public static void tearDown() throws IOException {
		expectedType = null;
		expectedID = null;
		actual = null;

		document.close();
	}
}

Add test for acro forms

Add test for acro forms


/*
 Copyright (C) 2010 EBI, GRL

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

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

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

package org.ensembl.healthcheck.testcase.generic;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;

/**
 * Check that only genes have projected xrefs.
 */

public class ProjectedXrefGenes extends SingleDatabaseTestCase {

    /**
     * Constructor.
     */
    public ProjectedXrefGenes() {

        addToGroup("post_genebuild");
        addToGroup("release");
        setDescription("Check that only genes have projected xrefs");
        setTeamResponsible("Core");

    }

    /**
     * Run the test for each database.
     * @param dbre The database to check.
     * @return Result.
     */
    public boolean run(DatabaseRegistryEntry dbre) {

        boolean result = true;

        Connection con = dbre.getConnection();

    			String sql = "SELECT COUNT(*) FROM external_db e, xref x, object_xref ox, transcript t WHERE e.external_db_id=x.external_db_id AND x.xref_id=ox.xref_id AND ox.ensembl_object_type='Transcript' AND ox.ensembl_id=t.transcript_id AND x.info_type='PROJECTION'";

    			int rows = getRowCount(con, sql);

    			if (rows > 0) {

    				ReportManager.problem(this, con, "There are " + rows + " projected xrefs linked to transcripts however only genes and translations should have them.");
    				result = false;

    			} else {

    				ReportManager.correct(this, con, "No projected xrefs associated with transcripts");

    			}

        return result;
    }

} // ProjectedXrefGenes


/**
 * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved.
 *
 * http://izpack.org/
 * http://izpack.codehaus.org/
 *
 * Copyright 2003 Jonathan Halliday
 *
 * 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.izforge.izpack.panels.imgpacks;

import com.izforge.izpack.panels.packs.PacksPanelConsole;

/**
 * A Console implementation for ImgPacksPanel. Behaves exactly like the
 * {@link PacksPanelConsole}
 *
 * @author Polane Ramothea
 *
 */
public final class ImgPacksPanelConsole extends PacksPanelConsole {

	/**
	 *
	 */
	public ImgPacksPanelConsole() {
		super();
	}

}

Create a Console for Img Packs Panel

Create a Console for Img Packs Panel


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

import com.google.gwt.i18n.client.Constants;

public interface DatasourceExplorerConstants extends Constants {

    @DefaultStringValue("Explore")
    String exploreButtonLabel();
}

Add constants interface for the explorer


package edu.northwestern.bioinformatics.studycalendar.dao;

import edu.northwestern.bioinformatics.studycalendar.domain.ScheduledArm;

/**
 * @author Rhett Sutphin
 */
public class ScheduledArmDaoTest extends ContextDaoTestCase<ScheduledArmDao> {
    protected String getTestDataFileName() {
        return "testdata/ScheduledCalendarDaoTest.xml";
    }

    public void testGetById() throws Exception {
        ScheduledArm loaded = getDao().getById(-22);
        assertEquals("Wrong arm", -4, (int) loaded.getArm().getId());
        assertEquals("Wrong schedule", -20, (int) loaded.getScheduledCalendar().getId());
    }
}

Test for ScheduledArmDao (loading is more rigorously tested in ScheduledCalendarDaoTest)

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@607 0d517254-b314-0410-acde-c619094fa49f


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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.autoconfigure.RefreshAutoConfiguration;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.junit4.SpringRunner;

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

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {RefreshScopeNullBeanIntegrationTests.TestConfiguration.class})
public class RefreshScopeNullBeanIntegrationTests {

	@Autowired
	private MyCustomComponent myCustomComponent;

	@Autowired
	private org.springframework.cloud.context.scope.refresh.RefreshScope scope;

	@Test
	@DirtiesContext
	public void testRefreshBean() {
		assertThat(this.myCustomComponent).isNotNull();
		// ...and then refresh, so the bean is re-initialized:
		// this.scope.refreshAll();
	}

	protected static class OptionalService { }

	public static class MyCustomComponent {

		private final OptionalService optionalService;

		public MyCustomComponent(OptionalService optionalService) {
			this.optionalService = optionalService;
		}
	}

	@Configuration
	protected static class OptionalConfiguration {

		@Bean
		@RefreshScope
		public OptionalService service() {
			return null;
		}
	}

	@Configuration
	@Import({ RefreshAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, OptionalConfiguration.class })
	protected static class TestConfiguration {

		@Autowired(required = false)
		private OptionalService optionalService;

		@Bean
		public MyCustomComponent myCustomComponent() {
			return new MyCustomComponent(optionalService);
		}
	}

}

Test for NPE when calling getClass() in RefreshScope

fixes gh-297


/*
 * Copyright (C) 2016 Thinkenterprise
 *
 * 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 Michael Schaefer
 */

package com.thinkenterprise;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

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

Add Spring Boot JPA Start Sample

Add Spring Boot JPA Start Sample


package org.springframework.mock.http.client;

/*
 *
 * Riptide
 *
 * Copyright (C) 2015 - 2016 Zalando SE
 *
 * 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.
 *
 */

import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.mock.http.MockHttpInputMessage;
import org.springframework.util.Assert;

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

public class MockClientHttpResponse extends MockHttpInputMessage implements ClientHttpResponse {

    private final HttpStatus status;

    /**
     * Constructor with response body as a byte array.
     */
    public MockClientHttpResponse(byte[] body, HttpStatus statusCode) {
        super(body);
        Assert.notNull(statusCode, "statisCode is required");
        this.status = statusCode;
    }

    /**
     * Constructor with response body as InputStream.
     */
    public MockClientHttpResponse(InputStream body, HttpStatus statusCode) {
        super(body);
        Assert.notNull(statusCode, "statisCode is required");
        this.status = statusCode;
    }

    @Override
    public HttpStatus getStatusCode() throws IOException {
        return this.status;
    }

    @Override
    public int getRawStatusCode() throws IOException {
        return this.status.value();
    }

    @Override
    public String getStatusText() throws IOException {
        return this.status.getReasonPhrase();
    }

    @Override
    public void close() {
        try {
            this.getBody().close();
        } catch (IOException e) {
        }
    }

}

Align mock mvc behaviour with real http client


/*
 * Copyright (c) 2016-2019 Chronicle Software Ltd
 */

package net.openhft.chronicle.wire;

public class WatermarkedMicroTimestampLongConverter extends MicroTimestampLongConverter {
    @Override
    public long parse(CharSequence text) {
        char letter = text.charAt(0);
        if (('A' <= letter && letter <= 'Z') || ('a' <= letter && letter <= 'z')) {
            int digit = text.charAt(1);
            if ('0' <= digit && digit <= '9') {
                long watermark = (long) (((letter & 0x31) - 1) * 10 + digit) << -8;
                long parse = super.parse(text.subSequence(2, text.length()));
                return parse | watermark;
            }
        }
        throw new IllegalArgumentException("Unknown watermark");
    }

    @Override
    public void append(StringBuilder text, long value) {
        long time = value & (~0L << -8);
        long watermark = value >>> -8;
        text.append((char) ('A' + watermark / 10));
        text.append(watermark % 10);
        super.append(text, time);
    }
}

Add Chronicle FIX 4.4. and use the LATEST build otherwise a specific version doesn't get updated.


/*
 * Copyright 2015-2016 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.junit.jupiter.engine.vintage.rulesupport;

import org.junit.Rule;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.rules.ExternalResource;

@ExtendWith(ExternalResourceLegacySupport.class)
public class MultipleExternalResourceLegacySupportTests {

	private static boolean beforeOfRule1WasExecuted = false;
	private static boolean beforeOfRule2WasExecuted = false;

	private static boolean afterOfRule1WasExecuted = false;
	private static boolean afterOfRule2WasExecuted = false;

	@Rule
	public ExternalResource resource1 = new ExternalResource() {
		@Override
		protected void before() throws Throwable {
			beforeOfRule1WasExecuted = true;
		}

		@Override
		protected void after() {
			afterOfRule1WasExecuted = true;
		}
	};

	@Rule
	public ExternalResource resource2 = new ExternalResource() {
		@Override
		protected void before() throws Throwable {
			beforeOfRule2WasExecuted = true;
		}

		@Override
		protected void after() {
			afterOfRule2WasExecuted = true;
		}
	};

	@Test
	void beforeMethodsOfbothRulesWereExecuted() {
		assert beforeOfRule1WasExecuted;
		//		assert beforeOfRule2WasExecuted;
	}

	@AfterAll
	static void afterMethodsOfBothRulesWereExecuted() {
		assert afterOfRule1WasExecuted;
		//        assert afterOfRule2WasExecuted;
	}

}

Support rules of type ExternalResource

Support rules of type ExternalResource

new integration test with 2 rules
and after invocation verification

#433


package com.github.gabrielruiu.spring.cloud.config.redis;

import org.springframework.cloud.config.environment.PropertySource;

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

/**
 * @author Gabriel Mihai Ruiu (gabriel.ruiu@mail.com)
 */
public class PropertySourceBuilder {

    private String name;
    private Map<String, String> propertyMap = new HashMap<>();

    public static PropertySourceBuilder aPropertySource() {
        return new PropertySourceBuilder();
    }

    public PropertySourceBuilder withName(String name) {
        this.name = name;
        return this;
    }

    public PropertySourceBuilder withProperty(String key, String value) {
        this.propertyMap.put(key, value);
        return this;
    }

    public PropertySource build() {
        return new PropertySource(name, propertyMap);
    }
}

Add builder to help prepare expected instances of PropertySource in tests It's better than doing everything (instantiating the PropertySource along with the Map) inside the test itself, which would occupy much space


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

package org.apache.harmony.tests.java.io;

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

import junit.framework.TestCase;

public class RandomAccessFileTest extends TestCase {

	/**
	 * @tests java.io.RandomAccessFile#RandomAccessFile(java.io.File, java.lang.String)
	 */
	public void test_ConstructorLjava_io_FileLjava_lang_String() throws IOException {
		// Regression for HARMONY-50
        File f = File.createTempFile("xxx", "yyy");
        f.deleteOnExit();
        RandomAccessFile raf = new RandomAccessFile(f, "rws");
        raf.close();

        f = File.createTempFile("xxx", "yyy");
        f.deleteOnExit();
        raf = new RandomAccessFile(f, "rwd");
        raf.close();
    }
}

Test case for HARMONY-50 (rightly part of revision 389232)

svn path=/incubator/harmony/enhanced/classlib/trunk/; revision=389257


package com.nitorcreations.willow.metrics;

import com.nitorcreations.willow.messages.event.EventMessage;

import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

@Named("/event")
public class EventMetric extends FullMessageMetric<EventMessage,Collection<EventMessage>> {

  @Override
  protected Collection<EventMessage> processData(long start, long stop, int step, HttpServletRequest req) {
    return rawData.values();
  }
}

Add metric endpoint for events

Add metric endpoint for events


package net.spals.appbuilder.app.grpc;

import com.google.inject.Guice;
import com.google.inject.Module;
import io.grpc.*;
import net.spals.appbuilder.graph.model.ServiceGraph;
import org.testng.annotations.Test;

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

/**
 * Unit tests for {@link GrpcWebServerModule}
 *
 * @author tkral
 */
public class GrpcWebServerModuleTest {

    @Test
    public void testCompressorRegistry() {
        final CompressorRegistry compressorRegistry = CompressorRegistry.newEmptyInstance();
        final ServerBuilder<?> grpcExternalServerBuilder = mock(ServerBuilder.class);

        final Module compressorRegistryModule = binder ->
            binder.bind(CompressorRegistry.class).toInstance(compressorRegistry);
        Guice.createInjector(
            createWebServerModule("testCompressorRegistry", grpcExternalServerBuilder),
            compressorRegistryModule
        );

        verify(grpcExternalServerBuilder).compressorRegistry(same(compressorRegistry));
    }

    @Test
    public void testDecompressorRegistry() {
        final DecompressorRegistry decompressorRegistry = DecompressorRegistry.emptyInstance();
        final ServerBuilder<?> grpcExternalServerBuilder = mock(ServerBuilder.class);

        final Module decompressorRegistryModule = binder ->
            binder.bind(DecompressorRegistry.class).toInstance(decompressorRegistry);
        Guice.createInjector(
            createWebServerModule("testDecompressorRegistry", grpcExternalServerBuilder),
            decompressorRegistryModule
        );

        verify(grpcExternalServerBuilder).decompressorRegistry(same(decompressorRegistry));
    }

    @Test
    public void testHandlerRegistry() {
        final HandlerRegistry handlerRegistry = mock(HandlerRegistry.class);
        final ServerBuilder<?> grpcExternalServerBuilder = mock(ServerBuilder.class);

        final Module handlerRegistryModule = binder ->
            binder.bind(HandlerRegistry.class).toInstance(handlerRegistry);
        Guice.createInjector(
            createWebServerModule("testHandlerRegistry", grpcExternalServerBuilder),
            handlerRegistryModule
        );

        verify(grpcExternalServerBuilder).fallbackHandlerRegistry(same(handlerRegistry));
    }

    @Test
    public void testServerTransportFilter() {
        final ServerTransportFilter serverTransportFilter = mock(ServerTransportFilter.class);
        final ServerBuilder<?> grpcExternalServerBuilder = mock(ServerBuilder.class);

        final Module serverTransportFilterModule = binder ->
            binder.bind(ServerTransportFilter.class).toInstance(serverTransportFilter);
        Guice.createInjector(
            createWebServerModule("testServerTransportFilter", grpcExternalServerBuilder),
            serverTransportFilterModule
        );

        verify(grpcExternalServerBuilder).addTransportFilter(same(serverTransportFilter));
    }

    private GrpcWebServerModule createWebServerModule(
        final String name,
        final ServerBuilder<?> grpcExternalServerBuilder
    ) {
        return new GrpcWebServerModule.Builder()
            .setApplicationName(name)
            .setServiceGraph(new ServiceGraph())
            .setGrpcExternalServerBuilder(grpcExternalServerBuilder)
            .build();
    }
}

Add unit tests for GrpcWebServerModule

Add unit tests for GrpcWebServerModule


package io.github.droidkaigi.confsched2017.debug;

import com.tomoima.debot.strategy.DebotStrategy;

import android.app.Activity;
import android.support.annotation.NonNull;

import javax.inject.Inject;

public class NotificationStrategy extends DebotStrategy {

    @Inject
    public NotificationStrategy() {
    }

    @Override
    public void startAction(@NonNull Activity activity) {
        // Do nothing
    }
}

Add notification strategy for release build


package org.oskari.control.userlayer;

import org.oskari.map.userlayer.service.UserLayerDbService;

import fi.nls.oskari.control.ActionConstants;
import fi.nls.oskari.control.ActionDeniedException;
import fi.nls.oskari.control.ActionException;
import fi.nls.oskari.control.ActionParameters;
import fi.nls.oskari.control.ActionParamsException;
import fi.nls.oskari.domain.map.userlayer.UserLayer;

public class UserLayerHandlerHelper {

    public static UserLayer getUserLayer(UserLayerDbService service, ActionParameters params) throws ActionException {
        params.requireLoggedInUser();
        long id = params.getRequiredParamLong(ActionConstants.KEY_ID);
        UserLayer userLayer = service.getUserLayerById(id);
        if (userLayer == null) {
            throw new ActionParamsException("UserLayer doesn't exist: " + id);
        }
        if (!userLayer.isOwnedBy(params.getUser().getUuid())) {
            throw new ActionDeniedException("UserLayer belongs to another user");
        }
        return userLayer;
    }

}

Add Helper class for common functionality


package leetcode;

/**
 * https://leetcode.com/problems/additive-number/
 */
public class Problem306 {
    public boolean isAdditiveNumber(String num) {
        // TODO:
        return false;
    }

    public static void main(String[] args) {
        Problem306 prob = new Problem306();
        System.out.println(prob.isAdditiveNumber("112358")); // true
        System.out.println(prob.isAdditiveNumber("199100199")); // true
    }
}

Create a skeleton for problem 306

Create a skeleton for problem 306


package leetcode;

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

/**
 * https://leetcode.com/problems/minimum-height-trees/
 */
public class Problem310 {
    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> result = new ArrayList<>();
        // TODO:
        return result;
    }

    public static void main(String[] args) {
        Problem310 prob = new Problem310();
    }
}

Create a skeleton for problem 310

Create a skeleton for problem 310


package org.jkiss.dbeaver.ui.controls;

import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Composite;

/**
 * Advanced styled text control
 */
public class AdvancedStyledText {

    public static StyledText createControl(Composite parent, int style)
    {
        StyledText text = new StyledText(parent, style);

        return text;
    }

}

Use StyledText instead of Text in RSV editors


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

import com.github.pedrovgs.linkedlist.ListNode;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

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

  private GetTheElementInTheMiddleOfTheList getTheElementInTheMiddleOfTheList;

  @Before public void setUp() {
    getTheElementInTheMiddleOfTheList = new GetTheElementInTheMiddleOfTheList();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullListInstances() {
    getTheElementInTheMiddleOfTheList.get(null);
  }

  @Test public void shouldReturnTheElementInTheMiddleOfAListWithAnEvenNumberOfElements() {
    ListNode<Integer> list = createList(new int[] { 1, 2, 3 });

    ListNode<Integer> middleElement = getTheElementInTheMiddleOfTheList.get(list);

    assertEquals(Integer.valueOf(2), middleElement.getData());
  }

  @Test public void shouldReturnTheElementInTheMiddleOfTheListWithAnOddNumberOfElements() {
    ListNode<Integer> list = createList(new int[] { 1, 2, 3, 4 });

    ListNode<Integer> middleElement = getTheElementInTheMiddleOfTheList.get(list);

    assertEquals(Integer.valueOf(2), middleElement.getData());
  }

  private ListNode<Integer> createList(int[] integers) {
    ListNode<Integer> head = new ListNode<Integer>(integers[0]);
    if (integers.length > 1) {
      ListNode<Integer> prevNode = head;
      for (int i = 1; i < integers.length; i++) {
        ListNode<Integer> currentNode = new ListNode<Integer>(integers[i]);
        prevNode.setNext(currentNode);
        prevNode = currentNode;
      }
    }
    return head;
  }
}

Add some tests to problem 64

Add some tests to problem 64


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package nom.bdezonia.zorbage.type.storage.datasource;

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

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.int32.SignedInt32Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestReadOnlyDataSource {

	@Test
	public void test1() {

		SignedInt32Member value1 = G.INT32.construct();
		SignedInt32Member value2 = G.INT32.construct();

		IndexedDataSource<SignedInt32Member> a = ArrayStorage.allocateInts(
				new int[] {7, -99, 1, 0, 0, 121, 4000, 77, 91});
		IndexedDataSource<SignedInt32Member> ds = new ReadOnlyDataSource<>(a);

		assertEquals(a.size(), ds.size());
		for (int i = 0; i < ds.size(); i++) {
			ds.get(i, value1);
			a.get(i, value2);
			assertEquals(value2.v(), value1.v());
		}

		try {
			ds.set(0, value1);
			fail();
		} catch (Exception e) {
			assertTrue(true);
		}
	}
}

Define tests for the ReadOnlyDataSource class


package com.github.sormuras.bach.internal;

import java.lang.module.ModuleDescriptor;
import java.util.Optional;
import java.util.spi.ToolProvider;

public class ToolProviders {

  public static String describe(ToolProvider provider) {
    var name = provider.name();
    var module = provider.getClass().getModule();
    var by =
        Optional.ofNullable(module.getDescriptor())
            .map(ModuleDescriptor::toNameAndVersion)
            .orElse(module.toString());
    var info =
        switch (name) {
          case "jar" -> "Create an archive for classes and resources, and update or restore them";
          case "javac" -> "Read Java class and interface definitions and compile them into classes";
          case "javadoc" -> "Generate HTML pages of API documentation from Java source files";
          case "javap" -> "Disassemble one or more class files";
          case "jdeps" -> "Launch the Java class dependency analyzer";
          case "jlink" -> "Assemble and optimize a set of modules into a custom runtime image";
          case "jmod" -> "Create JMOD files and list the content of existing JMOD files";
          case "jpackage" -> "Package a self-contained Java application";
          case "junit" -> "Launch the JUnit Platform";
          default -> provider.toString();
        };
    return "%s (provided by module %s)\n%s".formatted(name, by, info.indent(2)).trim();
  }

  /** Hidden default constructor. */
  private ToolProviders() {}
}

Add tool provider related helper

Add tool provider related helper


/**
 * Copyright (c) 2015-present Jorge Díaz All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package jorgediazest.indexchecker.model;

import com.liferay.portal.kernel.security.permission.ActionKeys;

import jorgediazest.util.data.Data;

/**
 * @author Jorge Díaz
 */
public class CalendarBookingPermissionsHelper extends IndexCheckerPermissionsHelper {

	@Override
	protected String getPermissionsActionId(Data data) {
		return "VIEW_BOOKING_DETAILS";
	}

	@Override
	protected String getPermissionsClassName(Data data) {
		return "com.liferay.calendar.model.Calendar";
	}

	@Override
	protected long getPermissionsClassPK(Data data) {
		return data.get("calendarId", -1L);
	}
}

Fix CalendarBooking permissions bug (entries were detected as outdated)


/**
 *
 */
package zoo;

import java.io.IOException;

import shapegrammar.Node;
import turtle.TextualTurtle;
import turtle.Turtle;
import turtle.TurtleInterpreter;

/**
 * @author loic
 *
 */
public class SierpinskiTriangle {

	public static void main(final String[] args) throws IOException {
		final TurtleInterpreter<Turtle> interp = new TurtleInterpreter<>();
		interp.declareRule('A', "A−B+A+B−A", "F");
		interp.declareRule('B', "BB", "F");
		final Node<? super Turtle> axiom = interp.createAxiom("A-B-B");
		interp.evaluate(axiom, 1);
		axiom.render(new TextualTurtle());
		for(int i = 0; i < 5; i++) {
			System.out.println();
			interp.evaluate();
			axiom.render(new TextualTurtle());
		}
	}

}

Add Sierpinski example based on rule declaration.


package utils;

import java.util.HashMap;

import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;

public class RequestUtilTest {

    @Test
    public void getFirstValueFromQuery() {
        {
            HashMap<String, String[]> query = new HashMap<String, String[]>();
            String[] values = {"a", "b", "c"};
            query.put("test", values);
            String actual = RequestUtil.getFirstValueFromQuery(query, "test");
            assertThat(actual).isEqualTo("a");
        }

        {
            HashMap<String, String[]> query = new HashMap<String, String[]>();
            String[] values = {};
            query.put("test", values);
            String actual = RequestUtil.getFirstValueFromQuery(query, "test");
            assertThat(actual).isEqualTo(null);
        }

        {
            HashMap<String, String[]> query = new HashMap<String, String[]>();
            String actual = RequestUtil.getFirstValueFromQuery(query, "test");
            assertThat(actual).isEqualTo(null);
        }
    }

}

Add a test for RequestUtil.

util: Add a test for RequestUtil.