package org.intermine.sql.writebatch;

/*
 * Copyright (C) 2002-2007 FlyMine
 *
 * This code may be freely distributed and modified under the
 * terms of the GNU Lesser General Public Licence.  This should
 * be distributed with the code.  See the LICENSE file for more
 * information or http://www.gnu.org/copyleft/lesser.html.
 *
 */

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * A FlushJob that commits and re-opens a transaction on the database.
 *
 * @author Matthew Wakeling
 */
public class FlushJobBatchCommit implements FlushJob
{
    Connection con;

    /**
     * Constructor for this class
     *
     * @param con a Connection with which to perform the updates
     */
    public FlushJobBatchCommit(Connection con) {
        this.con = con;
    }

    /**
     * {@inheritDoc}
     */
    public void flush() throws SQLException {
        con.commit();
    }
}

Check in new file needed by previous check-in, and do ignores


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

import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 * The purpose of this filter is to replace xhtml anchors like {@code} with xwiki compatible links
 * like {@code}.
 *
 * @version $Id$
 * @since 1.8M1
 */
public class AnchorFilter implements HTMLFilter
{
    /**
     * {@inheritDoc}
     */
    public void filter(Document document)
    {
        NodeList links = document.getElementsByTagName("a");
        for (int i = 0; i < links.getLength(); i++) {
            if (links.item(i) instanceof Element) {
                Element link = (Element) links.item(i);
                String anchorName = link.getAttribute("name");
                boolean isAnchor = !anchorName.equals("");
                if (isAnchor) {
                    Node parent = link.getParentNode();
                    Comment beforeComment =
                        document.createComment(String.format("startmacro:id|-|name=\"%s\"|-|", anchorName));
                    Comment afterComment = document.createComment("stopmacro");
                    parent.insertBefore(beforeComment, link);
                    parent.insertBefore(afterComment, link.getNextSibling());
                }
            }
        }
    }
}

Develop the initial feature set for the Office Importer module


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

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;

@RunWith(PaxExam.class)
public class CamelAwsIamTest extends BaseKarafTest {

    public static final String COMPONENT = extractName(CamelAwsIamTest.class);

    @Test
    public void test() throws Exception {
    	testComponent(COMPONENT);
    }

}

Create single Karaf feature tests for single components, aws-iam test


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

package org.apache.jmeter.functions;

import static org.junit.Assert.assertEquals;

import java.util.Collection;
import java.util.LinkedList;

import org.apache.jmeter.engine.util.CompoundVariable;
import org.apache.jmeter.junit.JMeterTestCase;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.threads.JMeterContext;
import org.apache.jmeter.threads.JMeterContextService;
import org.apache.jmeter.threads.JMeterVariables;
import org.junit.Before;
import org.junit.Test;

public class TestEscapeOroRegexpChars extends JMeterTestCase {
    protected AbstractFunction function;

    private SampleResult result;

    private Collection<CompoundVariable> params;

    private JMeterVariables vars;

    private JMeterContext jmctx;

    @Before
    public void setUp() {
        function = new EscapeOroRegexpChars();
        result = new SampleResult();
        jmctx = JMeterContextService.getContext();
        String data = "The quick brown fox";
        result.setResponseData(data, null);
        vars = new JMeterVariables();
        jmctx.setVariables(vars);
        jmctx.setPreviousResult(result);
        params = new LinkedList<>();
    }

    @Test
    public void testParameterCount() throws Exception {
        checkInvalidParameterCounts(function, 1, 2);
    }

    @Test
    public void testNOEscape() throws Exception {
        params.add(new CompoundVariable("toto1titi"));
        function.setParameters(params);
        String ret = function.execute(result, null);
        assertEquals("toto1titi", ret);
    }

    @Test
    public void testEscapeSpace() throws Exception {
        params.add(new CompoundVariable("toto1 titi"));
        function.setParameters(params);
        String ret = function.execute(result, null);
        assertEquals("toto1\\ titi", ret);
    }

    @Test
    public void testEscape() throws Exception {
        params.add(new CompoundVariable("toto(.+?)titi"));
        function.setParameters(params);
        String ret = function.execute(result, null);
        assertEquals("toto\\(\\.\\+\\?\\)titi", ret);
    }

    @Test
    public void testEscape2() throws Exception {
        params.add(new CompoundVariable("[^\"].+?"));
        function.setParameters(params);
        String ret = function.execute(result, null);
        assertEquals("\\[\\^\\\"\\]\\.\\+\\?", ret);
    }
}

Add tests for escapeOroRegexpChars function


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

package com.google.sps.data;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth8.assertThat;
import static org.mockito.Mockito.*;

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

/**
 * A tester for the State class.
 */
@RunWith(JUnit4.class)
public final class StateTest {
  private static int STATE_NUMBER = 50;

  @Test
  public void check50States() {
    // Check that the total number of state abbreviation-name pairs is {@code STATE_NUMBER}.
    assertThat(State.abbreviationToName.size()).isEqualTo(STATE_NUMBER);
  }
}

Add sanity check for the state abbreviation-name pairs.


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

package androidx.appsearch.app.cts;

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

import androidx.appsearch.app.SearchResult;
import androidx.appsearch.app.util.AppSearchEmail;

import org.junit.Test;

public class SearchResultCtsTest {

    @Test
    public void testBuildSearchResult() {
        SearchResult.MatchRange exactMatchRange = new SearchResult.MatchRange(3, 8);
        SearchResult.MatchRange snippetMatchRange = new SearchResult.MatchRange(1, 10);
        SearchResult.MatchInfo matchInfo =
                new SearchResult.MatchInfo.Builder("body")
                        .setExactMatchRange(exactMatchRange)
                        .setSnippetRange(snippetMatchRange).build();

        AppSearchEmail email = new AppSearchEmail.Builder("namespace1", "id1")
                .setBody("Hello World.")
                .build();
        SearchResult searchResult = new SearchResult.Builder("packageName", "databaseName")
                .setGenericDocument(email)
                .addMatchInfo(matchInfo)
                .setRankingSignal(2.9)
                .build();

        assertThat(searchResult.getPackageName()).isEqualTo("packageName");
        assertThat(searchResult.getDatabaseName()).isEqualTo("databaseName");
        assertThat(searchResult.getRankingSignal()).isEqualTo(2.9);
        assertThat(searchResult.getGenericDocument()).isEqualTo(email);
        assertThat(searchResult.getMatchInfos()).hasSize(1);
        SearchResult.MatchInfo actualMatchInfo = searchResult.getMatchInfos().get(0);
        assertThat(actualMatchInfo.getPropertyPath()).isEqualTo("body");
        assertThat(actualMatchInfo.getExactMatchRange()).isEqualTo(exactMatchRange);
        assertThat(actualMatchInfo.getSnippetRange()).isEqualTo(snippetMatchRange);
        assertThat(actualMatchInfo.getExactMatch()).isEqualTo("lo Wo");
        assertThat(actualMatchInfo.getSnippet()).isEqualTo("ello Worl");
        assertThat(actualMatchInfo.getFullText()).isEqualTo("Hello World.");
    }

    @Test
    public void testMatchRange() {
        SearchResult.MatchRange matchRange = new SearchResult.MatchRange(13, 47);
        assertThat(matchRange.getStart()).isEqualTo(13);
        assertThat(matchRange.getEnd()).isEqualTo(47);
    }
}

Add cts test for SearchResult, MatchInfo and MatchRange


package authentication.keys.impl;

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

import authentication.keys.KeyCache;

import com.google.common.cache.Cache;

public class LocalKeyCache extends KeyCache {

	private final Map<String, String> keys;

	public LocalKeyCache(Cache<String, String> cache) {
		super(cache);
		this.keys = new HashMap<>();
	}

	@Override
	protected String load(String identifier) {
		return keys.get(identifier);
	}

	@Override
	protected void store(String identifier, String secretKey) {
		keys.put(identifier, secretKey);
	}

}

Add local key cache implementation.


/*
 * Copyright 2015 Open mHealth
 *
 * 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.openmhealth.schema.domain.omh;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;

import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;

/**
 * A denominator used by by a descriptive statistic when applied to a measure with an implicit duration.
 *
 * @author Emerson Farrugia
 * @version 1.0
 * @see
 * descriptive-statistic-denominator
 */
public enum DescriptiveStatisticDenominator implements SchemaEnumValue, SchemaSupport {

    DAY("d"),
    EPISODE,
    MEAL,
    SESSION;

    public static final SchemaId SCHEMA_ID = new SchemaId(OMH_NAMESPACE, "descriptive-statistic-denominator", "1.0");

    private String schemaValue;
    private static final Map<String, DescriptiveStatisticDenominator> constantsBySchemaValue = new HashMap<>();

    static {
        for (DescriptiveStatisticDenominator constant : values()) {
            constantsBySchemaValue.put(constant.getSchemaValue(), constant);
        }
    }

    DescriptiveStatisticDenominator() {
        this.schemaValue = name().toLowerCase().replace('_', ' ');
    }

    DescriptiveStatisticDenominator(String schemaValue) {

        this.schemaValue = schemaValue;
    }

    @Override
    public SchemaId getSchemaId() {
        return SCHEMA_ID;
    }

    @Override
    @JsonValue
    public String getSchemaValue() {
        return this.schemaValue;
    }

    @Nullable
    @JsonCreator
    public static DescriptiveStatisticDenominator findBySchemaValue(String schemaValue) {
        return constantsBySchemaValue.get(schemaValue);
    }
}

Add enum for descriptive statistic denominators


package com.genymobile.pr.net;

import com.genymobile.pr.bus.BusProvider;
import com.genymobile.pr.bus.IssueRetrievedEvent;
import com.genymobile.pr.model.Issue;

import android.util.Log;
import retrofit.Callback;
import retrofit.Response;
import retrofit.Retrofit;

public class IssueCallback implements Callback<Issue> {

    private static final String TAG = IssueCallback.class.getSimpleName();

    @Override
    public void onResponse(Response<Issue> response, Retrofit retrofit) {
        if (response.isSuccess()) {
            BusProvider.getInstance().post(new IssueRetrievedEvent(response.body()));
        } else {
            Log.e(TAG, "Couldn't load issue : " + response.message());
        }
        //TODO handle error
    }

    @Override
    public void onFailure(Throwable t) {
        Log.e(TAG, "Couldn't load issue", t);
        //TODO handle error
    }
}

Add the Callback for the Retrieved Issue


import java.util.*;
import org.xbill.DNS.*;

public class lookup {

public static void
printAnswer(String name, Lookup lookup) {
	System.out.print(name + ":");
	int result = lookup.getResult();
	if (result != Lookup.SUCCESSFUL)
		System.out.print(" " + lookup.getErrorString());
	System.out.println();
	if (lookup.getResult() == Lookup.SUCCESSFUL) {
		Record [] answers = lookup.getAnswers();
		for (int i = 0; i < answers.length; i++)
			System.out.println(answers[i]);
	}
}

public static void
main(String [] args) throws Exception {
	short type = Type.A;
	int start = 0;
	if (args.length > 2 && args[0].equals("-t")) {
		type = Type.value(args[1]);
		if (type < 0)
			throw new IllegalArgumentException("invalid type");
		start = 2;
	}
	for (int i = start; i < args.length; i++) {
		Lookup l = new Lookup(args[i], type);
		l.run();
		printAnswer(args[i], l);
	}
}

}

import java.util.*;
import org.xbill.DNS.*;

public class lookup {

public static void
printAnswer(String name, Lookup lookup) {
	System.out.print(name + ":");
	int result = lookup.getResult();
	if (result != Lookup.SUCCESSFUL)
		System.out.print(" " + lookup.getErrorString());
	System.out.println();
	Name [] aliases = lookup.getAliases();
	if (aliases.length > 0) {
		System.out.print("# aliases: ");
		for (int i = 0; i < aliases.length; i++) {
			System.out.print(aliases[i]);
			if (i < aliases.length - 1)
				System.out.print(" ");
		}
		System.out.println();
	}
	if (lookup.getResult() == Lookup.SUCCESSFUL) {
		Record [] answers = lookup.getAnswers();
		for (int i = 0; i < answers.length; i++)
			System.out.println(answers[i]);
	}
}

public static void
main(String [] args) throws Exception {
	short type = Type.A;
	int start = 0;
	if (args.length > 2 && args[0].equals("-t")) {
		type = Type.value(args[1]);
		if (type < 0)
			throw new IllegalArgumentException("invalid type");
		start = 2;
	}
	for (int i = start; i < args.length; i++) {
		Lookup l = new Lookup(args[i], type);
		l.run();
		printAnswer(args[i], l);
	}
}

}

Print a list of aliases, if any exist.


/*
 * Copyright 2021 B2i Healthcare Pte Ltd, http://b2i.sg
 *
 * 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.b2international.snowowl.core.codesystem;

/**
 * @since 7.15
 */
public enum CodeSystemUpgradeState {

	AVAILABLE,

	IN_PROGRESS,

	BLOCKED,

	READY,

	DONE

}

Create code system upgrade state


package net.stickycode.deploy.sample.main;

public class HelloWorld {

  public static void main(String[] args) {
    System.out.println("Hello World!");
  }
}

package net.stickycode.deploy.sample.main;

public class HelloWorld {

  public static void main(String[] args) {
    if (args.length == 0)
      System.out.println("Hello World!");

    for (int i = 0; i < args.length; i++)
      try {
        for (int j = 0; j < Integer.parseInt(args[i]); j++) {
          System.out.println("Hello world (" + i + "," + j + ")!");
          Thread.sleep(i * 1000);
        }
      }
      catch (NumberFormatException e) {
        System.err.println("This is not a number " + args[i]);
      }
      catch (InterruptedException e) {
        throw new RuntimeException(e);
      }
  }
}

Allow for passing parameters and delaying the run for analysis


package hypernova.activities;

import java.util.Random;

import hypernova.Mass;
import hypernova.Loot;
import hypernova.Universe;
import hypernova.Activity;

public class GoodieField extends Activity {
    public static final double SPREAD = 100.0;
    public static final int COUNT = 30;
    public static final int GOLD = 10;

    public void realize(double x, double y) {
        Random rng = new Random();
        for (int i = 0; i < COUNT; i++) {
            Mass loot = new Loot(null, null, GOLD);
            loot.setPosition(x + rng.nextGaussian() * SPREAD,
                             y + rng.nextGaussian() * SPREAD, 0);
            Universe.get().add(loot);
        }
    }
}

Add the first Java-written Activity.


/*
 * 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.camel.component.vertx.http;

import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.file.AsyncFile;
import io.vertx.core.file.OpenOptions;
import io.vertx.ext.web.client.HttpRequest;
import io.vertx.ext.web.codec.BodyCodec;
import org.apache.camel.Exchange;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.junit.jupiter.api.Test;

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

public class VertxHttpStreamingResponseTest extends VertxHttpTestSupport {

    private static final String MESSAGE = "Streaming response content";

    @Test
    public void testStreamingResponseToFile() {
        VertxHttpComponent component = context.getComponent("vertx-http", VertxHttpComponent.class);
        Vertx vertx = component.getVertx();

        String path = "target/streaming.txt";
        AsyncFile file = vertx.fileSystem().openBlocking(path, new OpenOptions());

        VertxHttpBinding binding = new DefaultVertxHttpBinding() {
            @Override
            public HttpRequest<Buffer> prepareHttpRequest(VertxHttpEndpoint endpoint, Exchange exchange) throws Exception {
                HttpRequest<Buffer> request = super.prepareHttpRequest(endpoint, exchange);
                request.as(BodyCodec.pipe(file));
                return request;
            }
        };

        component.setVertxHttpBinding(binding);

        try {
            template.request(getProducerUri(), null);
            Buffer buffer = vertx.fileSystem().readFileBlocking(path);
            assertEquals(MESSAGE, buffer.toString());
        } finally {
            vertx.fileSystem().deleteBlocking(path);
        }
    }

    @Override
    protected RoutesBuilder createRouteBuilder() throws Exception {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from(getTestServerUri())
                        .setBody().constant(MESSAGE);
            }
        };
    }
}

Add a test for streaming responses to file


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

package org.springframework.security.oauth2.provider.client;

import static org.junit.Assert.assertEquals;

import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;

/**
 * @author Dave Syer
 *
 */
public class TestClientCredentialsTokenEndpointFilter {

	private ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
	private AuthenticationManager authenticationManager = Mockito
			.mock(AuthenticationManager.class);

	@Test(expected=IllegalArgumentException.class)
	public void testAuthenticationManagerNeeded() {
		new ClientCredentialsTokenEndpointFilter().afterPropertiesSet();
	}

	@Test(expected = BadCredentialsException.class)
	public void testFailedAuthentication() throws Exception {
		filter.setAuthenticationManager(authenticationManager);
		filter.afterPropertiesSet();
		filter.attemptAuthentication(new MockHttpServletRequest(),
				new MockHttpServletResponse());
	}

	@Test
	public void testAuthentication() throws Exception {
		MockHttpServletRequest request = new MockHttpServletRequest();
		request.addParameter("client_id", "foo");
		filter.setAuthenticationManager(authenticationManager);
		filter.afterPropertiesSet();
		Authentication authentication = new UsernamePasswordAuthenticationToken(
				"foo", "",
				AuthorityUtils.commaSeparatedStringToAuthorityList("CLIENT"));
		Mockito.when(
				authenticationManager.authenticate(Mockito
						.any(Authentication.class))).thenReturn(authentication);
		assertEquals(authentication, filter.attemptAuthentication(request,
				new MockHttpServletResponse()));
	}

}

Add test case for CCTF


/* PropertySortDescriptorTests.java created on Dec 5, 2015.
 *
 * Copyright (c) <2015> Pin-Ying Tu <dbi1463@gmail.com>
 *
 * This file is part of SortDescriptor under the MIT license.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package tw.funnymph.commons.sort;

import static org.junit.Assert.*;

import org.junit.Test;

import tw.funnymph.commons.sort.Person.Gender;

/**
 * This class tests the functionalities of {@link PropertySortDescriptor}.
 *
 * @author Pin-Ying Tu
 * @version 1.0
 * @since 1.0
 */
public class PropertySortDescriptorTests {

	@Test
	public void testPropertySortDescriptor() {
		PropertySortDescriptor<Person> testee = new PropertySortDescriptor<Person>("lastName");
		Person person = new Person("Cathy", "Tu", Gender.Female, SortExample.getBirthday(30, 2, 2));
		assertTrue(testee.isAscending());
		assertEquals("Tu", testee.transform(person));
	}

	@Test
	public void testPropertySortDescriptorStringBooleanBoolean() {
		PropertySortDescriptor<Person> testee = new PropertySortDescriptor<Person>("adult", true);
		Person person = new Person("Cathy", "Tu", Gender.Female, SortExample.getBirthday(30, 2, 2));
		assertTrue(testee.isAscending());
		assertNull(testee.transform(person));

		testee = new PropertySortDescriptor<Person>("firstName");
		assertEquals("Cathy", testee.transform(person));

		testee.setGetterMethodPrefix(null);
		assertNull(testee.transform(person));

		testee.setGetterMethodPrefix("");
		assertNull(testee.transform(person));
	}
}

Add test cases for PropertySortDescriptor.


import static conexp.contrib.JavaInterface.*;

public class Test {
  public static void main(String... args) {
    Object context = random_context(10,10,0.5);
    System.out.println(context_to_string(context));
    return;
  }
}

Add example Java program that uses conexp-clj


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Collapse;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.Views;
import net.imglib2.view.composite.CompositeIntervalView;
import net.imglib2.view.composite.GenericComposite;

import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.Collapse.class, name = ViewOps.Collapse.NAME)
public class DefaultCollapse2CompositeIntervalView<T>
		extends
		AbstractView<RandomAccessibleInterval<T>, CompositeIntervalView<T, ? extends GenericComposite<T>>>
		implements
		Collapse<RandomAccessibleInterval<T>, CompositeIntervalView<T, ? extends GenericComposite<T>>> {

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

}

Add default implementation of Collapse to CompositeView.


/*
 * Copyright (c) 2014 Ushahidi.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program in the file LICENSE-AGPL. If not, see
 * https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.ui.fragment;

/**
 * Shows list of deployment.
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
public class ListDeploymentFragment {

}

Add deployment list fragment class


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

import junit.framework.Assert;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.xwiki.it.ui.elements.WikiEditPage;
import org.xwiki.it.ui.framework.AbstractAdminAuthenticatedTest;
import org.xwiki.it.ui.framework.TestUtils;

/**
 * Test wiki editing.
 *
 * @version $Id$
 * @since 2.4M1
 */
public class EditWikiTest extends AbstractAdminAuthenticatedTest
{
    /** Page used for testing: Main.WikiEditTest */
    private WikiEditPage editPage;

    @Before
    @Override
    public void setUp()
    {
        super.setUp();
        this.editPage = new WikiEditPage(getDriver());
        TestUtils.deletePage("Test", "EditWikiTest", getDriver());
    }

    @After
    public void cleanUp()
    {
        TestUtils.deletePage("Test", "EditWikiTest", getDriver());
    }

    /** Test that save and continue saves as a minor version. */
    @Test
    public void testSaveAndContinueIsMinorEdit()
    {
        this.editPage.switchToEdit("Test", "EditWikiTest");
        Assert.assertTrue(this.editPage.isNewDocument());
        this.editPage.setContent("abc1");
        this.editPage.clickSaveAndView();
        Assert.assertEquals("1.1", this.editPage.getMetaDataValue("version"));

        this.editPage.switchToEdit("Test", "EditWikiTest");
        Assert.assertFalse(this.editPage.isNewDocument());
        this.editPage.setContent("abc2");
        this.editPage.setMinorEdit(false);
        this.editPage.clickSaveAndContinue();
        this.editPage.clickCancel();
        Assert.assertEquals("1.2", this.editPage.getMetaDataValue("version"));
    }
}

Save & Continue should save as minor edit Added test.


package com.github.stefanbirkner.fishbowl;

import org.junit.Test;
import org.junit.experimental.runners.Enclosed;
import org.junit.runner.RunWith;

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

import static com.github.stefanbirkner.fishbowl.Fishbowl.defaultIfException;
import static com.github.stefanbirkner.fishbowl.Fishbowl.exceptionThrownBy;
import static com.github.stefanbirkner.fishbowl.Fishbowl.wrapCheckedException;
import static java.lang.Long.parseLong;
import static org.junit.Assert.assertEquals;

/**
 * Test that the website's example code is working.
 */
@RunWith(Enclosed.class)
public class WebsiteExampleTest {
    private static class WrappingExceptions {
        public void doSomething(InputStream is) {
            //originally both lines can throw an IOException
            int nextByte = wrapCheckedException(() -> is.read());
            wrapCheckedException(() -> is.close());
        }

        @Test
        public void verifyThatTheMethodCanBeExecuted() {
            InputStream is = new ByteArrayInputStream("dummy".getBytes());
            doSomething(is);
        }
    }

    private static class DefaultValues {
        @Test
        public void doSomething() {
            long value = defaultIfException(() -> parseLong("NaN"),
                NumberFormatException.class, 0L);
            //value is 0
            assertEquals(0, value);
        }
    }

    private static class ExceptionTesting {
        @Test
        public void anExceptionIsThrown() {
            String noString = null;
            Throwable exception = exceptionThrownBy(() -> noString.trim());
            assertEquals(NullPointerException.class, exception.getClass());
        }
    }
}

Add test for the website's code example.


package de.retest.recheck.ui.diff;

import java.io.Serializable;

import javax.xml.bind.annotation.XmlAttribute;

import lombok.Data;
import lombok.RequiredArgsConstructor;

/**
 * Structurally stores the information about a test breakage caused by the
 * GUI element identification
 * problem. This information can be re-used by review or recheck.cli when the user applies a change.
 */
@Data
@RequiredArgsConstructor
public class ElementIdentificationWarning implements Serializable {

	private static final long serialVersionUID = 1L;

	@XmlAttribute
	private final String elementIdentifier;

	@XmlAttribute
	private final String testClassName;

	@XmlAttribute
	private final String retestId;

	@SuppressWarnings( "unused" )
	private ElementIdentificationWarning() {
		elementIdentifier = null;
		testClassName = null;
		retestId = null;
	}
}

Add class for GUI element identification warning


package leetcode;

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

/**
 * https://leetcode.com/problems/single-number-ii/
 */
public class Problem137 {
    public int singleNumber(int[] A) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < A.length; i++) {
            if (!map.containsKey(A[i])) {
                map.put(A[i], 1);
            } else {
                map.put(A[i], map.get(A[i]) + 1);
            }
        }
        for (Map.Entry<Integer, Integer> e : map.entrySet()) {
            if (e.getValue() != 3) {
                return e.getKey();
            }
        }
        throw new RuntimeException();
    }
}

Solve problem 137 (using O(n) space)


package model;

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

import static org.junit.Assert.*;

/**
 * Created by vincet on 31/03/16.
 */
public class TetrominoTest {
    private Tetromino objectTest;
    @Before
    public void setUp() throws Exception {
        objectTest = new Tetromino(TetrominoType.L,new Position(0,0));
    }

    @Test
    public void getPosition() throws Exception {
        Position pos = objectTest.getPosition();
        assertTrue("Position incorrecte", pos.getX()==0 && pos.getY()==0);
    }

    @Test
    public void setPosition() throws Exception {
        objectTest.setPosition(new Position(12,31));
        Position pos = objectTest.getPosition();
        assertTrue("Position mise correctement", pos.getX()==12 && pos.getY()==31);

    }

    @Test
    public void getRotation() throws Exception {
        int rot = objectTest.getRotation();
        assertTrue("Rotation Valide", rot==0 || rot==1 || rot==2 || rot==3);
    }

    @Test
    public void setRotation() throws Exception {
        objectTest.setRotation(1);
        int rot = objectTest.getRotation();
        assertTrue("Rotation mise a jour", rot==1);

    }

    @Test
    public void rotate() throws Exception {
        objectTest.rotate(true);

        assertTrue(0==1);
    }

}

Add tests for the Tetromino class


package keymix;

import java.util.HashMap;
import javafx.scene.input.KeyCode;
import java.io.File;

/**
 * HashMap to map keycodes to the corresponding sound they should produce.
 */
public class SoundMap {

    /* Maps keycodes to string containing the file name of the sound byte. */
    HashMap<KeyCode, String> sounds = new HashMap<KeyCode, String>();

    /* KeyCodes for all valid keys. */
    KeyCode[] codes = new KeyCode[]{KeyCode.A, KeyCode.B, KeyCode.C, KeyCode.D, KeyCode.E, KeyCode.F, KeyCode.G,
            KeyCode.H, KeyCode.I, KeyCode.J, KeyCode.K, KeyCode.L, KeyCode.M, KeyCode.N, KeyCode.O, KeyCode.P,
            KeyCode.Q, KeyCode.R, KeyCode.S, KeyCode.T, KeyCode.U, KeyCode.V, KeyCode.W, KeyCode.X, KeyCode.Y, KeyCode.Z,
            KeyCode.DIGIT0, KeyCode.DIGIT1, KeyCode.DIGIT2, KeyCode.DIGIT3, KeyCode.DIGIT4, KeyCode.DIGIT5,
            KeyCode.DIGIT6, KeyCode.DIGIT7, KeyCode.DIGIT8, KeyCode.DIGIT9,
            KeyCode.SPACE, KeyCode.SHIFT, KeyCode.CONTROL, KeyCode.BACK_SPACE};

    /* Filepaths for all sound bytes to be available. */
    String[] filepaths = new String[]{
        // Insert filepaths as Strings
    };

    /* Given a filepath as a String, return the name of the file. */
    public static String name(String filepath) {
        File f = new File(filepath);
        return f.getName();
    }

    public static HashMap<KeyCode, String> map(KeyCode[] c, String[] fp, HashMap<KeyCode, String> m) {
        for(int i = 0; i < c.length; i += 1) {
            m.put(c[i], name(fp[i]));
        }
        return m;
    }
}

Create sound HashMap for KeyCode to file name


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

package com.github.robozonky.app.portfolio;

import java.util.Collections;

import com.github.robozonky.api.notifications.LoanRepaidEvent;
import com.github.robozonky.api.remote.entities.Investment;
import com.github.robozonky.api.remote.entities.Loan;
import com.github.robozonky.api.remote.enums.PaymentStatus;
import com.github.robozonky.app.AbstractZonkyLeveragingTest;
import com.github.robozonky.app.authentication.Authenticated;
import com.github.robozonky.common.remote.Zonky;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;

class RepaymentsTest extends AbstractZonkyLeveragingTest {

    @Test
    void registerNewRepayments() {
        final Loan l = spy(new Loan(1, 1000));
        when(l.getRemainingInvestment()).thenReturn(0.0);
        final Investment i = spy(new Investment(l, 200));
        // first, portfolio contains one active investment; no repaid
        final Portfolio p = new Portfolio(Collections.singletonList(i));
        final Zonky z = harmlessZonky(10_000);
        when(z.getLoan(eq(l.getId()))).thenReturn(l);
        final Authenticated a = mockAuthentication(z);
        final Repayments r = new Repayments(true);
        r.accept(p, a);
        assertThat(getNewEvents()).isEmpty();
        // now, portfolio has the same investment marked as paid; event will be triggered
        when(i.getPaymentStatus()).thenReturn(PaymentStatus.PAID);
        r.accept(p, a);
        assertThat(getNewEvents())
                .first()
                .isInstanceOf(LoanRepaidEvent.class);
        // make sure the loan was retrieved from Zonky
        verify(z).getLoan(eq(l.getId()));
    }
}

Increase mutation coverage in robozonky-app to make AppVeyor happy


/*
 * 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.tinkerpop.gremlin.util;

import org.apache.tinkerpop.gremlin.TestHelper;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class GremlinTest {
    @Test
    public void shouldBeUtilityClass() throws Exception {
        TestHelper.assertIsUtilityClass(Gremlin.class);
    }

    @Test
    public void shouldGetVersion() {
        // the manifests lib should be solid at doing this job - can get by with a
        // light testing here - this will be good for at least version 3
        assertEquals('3', Gremlin.version().charAt(0));
    }
}

Add test for Gremlin utility.


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

/**
 * Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column are
 * set to 0.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class RewriteRowAndColumsWithZeros {
}

Add statement to problem 55


package org.oddjob.beancmpr.comparers;

import org.oddjob.beancmpr.Comparison;

/**
 * A {@link Comparison} that is the result of comparing many things.
 *
 * @author rob
 *
 */
public class DelegatingMultiItemComparison<T>
implements MultiItemComparison<T> {

	private final T x;

	private final T y;

	private final MultiItemComparisonCounts multiItemStats;

	private final int result;

	private final String summaryText;

	public DelegatingMultiItemComparison(
			T x,
			T y,
			MultiItemComparisonCounts multiItemStats) {

		this.x = x;
		this.y = y;

		this.multiItemStats = multiItemStats;

		this.result = multiItemStats.getBreaksCount();

		if (this.result == 0) {
			this.summaryText = "Equal, " + multiItemStats.getMatchedCount() +
					" matched";
		}
		else {
			this.summaryText = "" + multiItemStats.getBreaksCount() +
					" differences";
		}
	}

	@Override
	public T getX() {
		return x;
	}

	@Override
	public T getY() {
		return y;
	}

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

	@Override
	public String getSummaryText() {
		return summaryText;
	}

	@Override
	public int getXMissingCount() {
		return multiItemStats.getXMissingCount();
	}

	@Override
	public int getYMissingCount() {
		return multiItemStats.getYMissingCount();
	}

	@Override
	public int getMatchedCount() {
		return multiItemStats.getMatchedCount();
	}

	@Override
	public int getDifferentCount() {
		return multiItemStats.getDifferentCount();
	}

	@Override
	public int getBreaksCount() {
		return multiItemStats.getBreaksCount();
	}

	@Override
	public int getComparedCount() {
		return multiItemStats.getComparedCount();
	}
}

Add missing class from previous commit.


package org.cbsa.api.controller.search;

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

import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.io.RandomAccessBuffer;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripper;
import org.cbsa.api.model.PageCard;
import org.cbsa.api.model.ResultCard;

public class PageByPageSearch {

    public List<ResultCard> findpages(String path,
            List<String> searchKeywordList) throws IOException {

        int i; // page no.
        boolean hasKeywords = false;

        PDDocument finalDocument = new PDDocument();
        List<PDPage> pageList = new ArrayList<PDPage>();

        File file = new File(path);
        PDFParser parser = new PDFParser(new RandomAccessBuffer(
                new FileInputStream(file)));
        parser.parse();

        COSDocument cosDoc = parser.getDocument();
        PDFTextStripper reader = new PDFTextStripper();
        PDDocument doc = new PDDocument(cosDoc);

        List<ResultCard> list = new ArrayList<ResultCard>();

        for (i = 0; i <= doc.getNumberOfPages(); i++) {
            reader.setStartPage(i);
            reader.setEndPage(i);
            hasKeywords = true;

            for (String keyword : searchKeywordList) {

                if (!reader.getText(doc).contains(keyword)) {
                    hasKeywords = false;
                    break;
                }
            }

            if (hasKeywords) {

                ResultCard result = new PageCard();
                result.setFileContent(reader.getText(doc));
                result.setFilePath(path);
                result.setPageNumber(i);
                list.add(result);
                pageList.add(doc.getPage(i));
            }

        }

        for (PDPage page : pageList) {
            finalDocument.addPage(page);
        }

        finalDocument.save("/opt/dataset/results/final.pdf");
        finalDocument.close();
        System.out.println("Saved");

        return list;

    }
}

Split and Merge combined to PageByPage Content Search


/*
 * Copyright 2020 Martin Winandy
 *
 * 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.tinylog.core.providers;

import java.util.List;

/**
 * Wrapper for multiple {@link LoggingProvider LoggingProviders}.
 */
public class BundleLoggingProvider implements LoggingProvider {

	private final List<LoggingProvider> providers;

	/**
	 * @param providers Logging providers to combine
	 */
	public BundleLoggingProvider(List<LoggingProvider> providers) {
		this.providers = providers;
	}

}

Add bundle logging provider for combing multiple providers


package imagej.core.commands.debug;

import imagej.command.Command;
import imagej.data.table.DefaultResultsTable;
import imagej.data.table.ResultsTable;
import imagej.module.ItemIO;
import imagej.plugin.Parameter;
import imagej.plugin.Plugin;

/** A test of {@link ResultsTable}. */
@Plugin(menuPath = "Plugins>Sandbox>Results Table Test", headless = true)
public class ResultsTableTest implements Command {

	@Parameter(label = "Paul Molitor", type = ItemIO.OUTPUT)
	private ResultsTable table;

	@Override
	public void run() {
		// Paul Molitor
		final double[][] data = {
			{1978, 21, .273},
			{1979, 22, .322},
			{1980, 23, .304},
			{1981, 24, .267},
			{1982, 25, .302},
			{1983, 26, .270},
			{1984, 27, .217},
			{1985, 28, .297},
			{1986, 29, .281},
			{1987, 30, .353},
			{1988, 31, .312},
			{1989, 32, .315},
			{1990, 33, .285},
			{1991, 34, .325},
			{1992, 35, .320},
			{1993, 36, .332},
			{1994, 37, .341},
			{1995, 38, .270},
			{1996, 39, .341},
			{1997, 40, .305},
			{1998, 41, .281},
		};
		table = new DefaultResultsTable(data[0].length, data.length);
		table.setColumnHeader("Year", 0);
		table.setColumnHeader("Age", 1);
		table.setColumnHeader("BA", 2);
		for (int row=0; row<data.length; row++) {
			for (int col=0; col<data[row].length; col++) {
				table.setValue(data[row][col], col, row);
			}
		}
	}

}

Add a test plugin for results tables


/*
 * Copyright 2014 Open mHealth
 *
 * 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.openmhealth.dsu.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * A Spring Security configuration that provides an empty authentication manager, since authentication will happen on
 * the authorization server.
 *
 * @author Emerson Farrugia
 */
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication();
    }

    @Bean(name = "authenticationManager")
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}

Add an empty authentication manager to the resource server to satisfy method security annotations.


package npe;
class TrackFields {
    Object x;
    TrackFields(Object x) {
            this.x = x;
            }

    int f() {
            if (x == null) return x.hashCode();
            return 42;
            }
    int g() {
            if (x != null) return 42;
            return x.hashCode();
            }
    int doNotReport() {
        if (x == null)
        	x = new Object();
        return x.hashCode();
        }
}

Test case for tracking fields in NP analysis


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

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

import javax.ws.rs.core.Application;

import com.redhat.rhevm.api.powershell.resource.PowerShellApiResource;
import com.redhat.rhevm.api.powershell.resource.PowerShellHostsResource;
import com.redhat.rhevm.api.powershell.resource.PowerShellVmsResource;

public class PowerShellApplication extends Application {

    private Set<Object> singletons = new HashSet<Object>();
    private Set<Class<?>> classes = new HashSet<Class<?>>();

    public PowerShellApplication() {
        singletons.add(new PowerShellHostsResource());
        singletons.add(new PowerShellVmsResource());
        classes.add(PowerShellApiResource.class);
    }

    @Override
    public Set<Class<?>> getClasses() {
        return classes;
    }

    @Override
    public Set<Object> getSingletons() {
        return singletons;
    }
}

Add a Application subclass for the PowerShell implementation


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

import java.net.URL;
import java.net.URLClassLoader;

import io.github.lukehutch.fastclasspathscanner.scanner.ClasspathFinder;

/** ClassLoaderHandler that is able to extract the URLs from a URLClassLoader. */
public class URLClassLoaderHandler implements ClassLoaderHandler {
    @Override
    public boolean handle(final ClassLoader classloader, final ClasspathFinder classpathFinder) {
        if (classloader instanceof URLClassLoader) {
            final URL[] urls = ((URLClassLoader) classloader).getURLs();
            if (urls != null) {
                for (final URL url : urls) {
                    if (url != null) {
                        classpathFinder.addClasspathElement(url.toString());
                    }
                }
            }
            return true;
        }
        return false;
    }
}

Move URLClassLoader into a separate class


package org.ovirt.engine.core.utils.archivers.tar;

import java.io.OutputStream;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;

public class InMemoryTar implements AutoCloseable{
    private TarArchiveOutputStream tarArchiveOutputStream;

    public InMemoryTar(OutputStream outputStream) {
        tarArchiveOutputStream = new TarArchiveOutputStream(outputStream);
    }

    public void addTarEntry(byte[] data, String name) throws Exception {
        TarArchiveEntry entry = new TarArchiveEntry(name);
        entry.setSize(data.length);
        tarArchiveOutputStream.putArchiveEntry(entry);
        tarArchiveOutputStream.write(data);
        tarArchiveOutputStream.closeArchiveEntry();
    }

    @Override
    public void close() throws Exception {
        tarArchiveOutputStream.close();
    }
}

Add support for creating in memory tar


package leetcode.count_and_say;

import java.util.ArrayList;

public class Solution {
    public String countAndSay(int n) {
    	if(n == 0) return "";
    	ArrayList<Integer> cas = new ArrayList<Integer>();
    	ArrayList<Integer> next = new ArrayList<Integer>();
    	cas.add(1);
    	while(--n > 0){
    		int cnt = 0;
    		for(int i = 0; i < cas.size(); i += cnt){
    			int c = cas.get(i);
    			cnt = 1;
    			if(i + 1 < cas.size()){
    				if(cas.get(i + 1) == c){
    					cnt++;
    					if(i + 2 < cas.size()){
    						if(cas.get(i + 2) == c){
    							cnt++;
    						}
    					}
    				}
    			}
    			next.add(cnt);
    			next.add(c);
    		}
    		cas.clear();
    		cas = next;
    		next = new ArrayList<Integer>();
    	}
    	StringBuilder sb = new StringBuilder();
    	for(int c : cas){
    		sb.append(c);
    	}
    	return sb.toString();
    }

    public static void main(String[] args){
    	for(int i = 0; i < 30; i++){
    		System.err.println(new Solution().countAndSay(i));
    	}
    }
}

Add java solution for 38. Count and Say


package edu.usc.glidein.util;

import java.net.InetAddress;

import org.apache.log4j.Logger;

public class ServiceUtil {
	private static Logger logger = Logger.getLogger(ServiceUtil.class);

	public static String getServiceHost() {
		// Set the default condor host
		try {
			InetAddress addr = InetAddress.getLocalHost();
			return addr.getHostName();
		}  catch (Exception e) {
			logger.warn("Unable to get service host",e);
			return null;
		}
	}
}

Add util class to return the local host name


package arez.integration;

import arez.annotations.ArezComponent;
import arez.annotations.ComponentNameRef;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class ComponentNameRefInvokedInCtorTest
  extends AbstractIntegrationTest
{
  @ArezComponent( allowEmpty = true )
  static abstract class TestComponent
  {
    TestComponent()
    {
      getName();
    }

    @ComponentNameRef
    abstract String getName();
  }

  @Test
  public void scenario()
    throws Throwable
  {
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, ComponentNameRefInvokedInCtorTest_Arez_TestComponent::new );
    assertEquals( exception.getMessage(), "Method invoked on uninitialized component of type 'TestComponent'" );
  }
}

Add another test to ensure invariants fail appropriately


package security;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/login").setViewName("login");
    }

}

Configure home and login pages.


package com.github.apsk.hax;

import javax.xml.stream.XMLStreamException;

public class ParseException extends XMLStreamException {
    public ParseException(String msg) {
        super(msg);
    }
}

Add class for parser exception handling.


/**
 * 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.hadoop.hive.metastore.hbase;

import java.util.List;

import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hive.conf.HiveConf;

public class HBaseStoreTestUtil {
  public static void initHBaseMetastore(HBaseAdmin admin, HiveConf conf) throws Exception {
    for (String tableName : HBaseReadWrite.tableNames) {
      List<byte[]> families = HBaseReadWrite.columnFamilies.get(tableName);
      HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
      for (byte[] family : families) {
        HColumnDescriptor columnDesc = new HColumnDescriptor(family);
        desc.addFamily(columnDesc);
      }
      admin.createTable(desc);
    }
    admin.close();
    if (conf != null) {
      HBaseReadWrite.getInstance(conf);
    }
  }
}

Exclude hbase-metastore in itests for hadoop-1


/*
 * Copyright 2016-2018 Talsma ICT
 *
 * 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 nl.talsmasoftware.context.clearable;

import nl.talsmasoftware.context.ContextManagers;
import org.junit.Test;

/**
 * Tests for clearing context managers.
 *
 * @author Sjoerd Talsma
 */
public class ClearableContextManagerTest {

    @Test(expected = UnsupportedOperationException.class)
    public void testUnsupportedBehaviour() {
        ContextManagers.clearManagedContexts();
    }

}

Make a start with unit test for ClearableContextManager


package edu.kit.iti.formal.pse.worthwhile.prover;

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

import edu.kit.iti.formal.pse.worthwhile.common.tests.TestASTProvider;
import edu.kit.iti.formal.pse.worthwhile.model.ast.Program;

/**
 * Test for {@link DivisionByZeroAssertionInserter} which ensures that Divisions by zero cause the proof to fail.
 *
 * @author Leon Handreke
 */
public class DivisionByZeroAssertionInserterTest {

	/**
	 * Test if division by a zero literal causes the proof to fail.
	 */
	@Test
	public final void testDivisionByZeroLiteral() {
		Program p = TestASTProvider.getRootASTNode("Integer a := 1/0\n_assert(true)\n");
		SpecificationChecker checker = new SpecificationChecker();
		Validity validity = checker.checkProgram(p);
		Assert.assertEquals(Validity.INVALID, validity);
	}

	/**
	 * Test if division by a variable set to zero causes the proof to fail.
	 */
	@Test
	public final void testDivisionByZeroVariable() {
		Program p = TestASTProvider.getRootASTNode("Integer a := 0\nInteger b := 42 / a\n_assert(true)\n");
		SpecificationChecker checker = new SpecificationChecker();
		Validity validity = checker.checkProgram(p);
		Assert.assertEquals(Validity.INVALID, validity);
	}

	/**
	 * Test if division by a variable that was previously set to zero causes the proof to succeed like it should.
	 */
	@Test
	public final void testDivisionByMultipleZeroVariables() {
		Program p = TestASTProvider
		                .getRootASTNode("Integer a := 2\nInteger b := 42 / a\na := 0\nb := 42 / 1\n_assert(true)\n");
		SpecificationChecker checker = new SpecificationChecker();
		Validity validity = checker.checkProgram(p);
		Assert.assertEquals(Validity.VALID, validity);
	}

	/**
	 * Test if Divisions by zero inside the condition of a Conditional cause the proof to fail.
	 */
	@Test
	public final void testDivisionByZeroInConditional() {
		Program p = TestASTProvider.getRootASTNode("Integer a := 0\nif(10 / a = 2) {\n    a := 0\n"
		                + "    Integer b := 42 / 1\n}\n_assert(true)\n");
		SpecificationChecker checker = new SpecificationChecker();
		Validity validity = checker.checkProgram(p);
		Assert.assertEquals(Validity.INVALID, validity);
	}
}

Add test for division by zero


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author:
 *    Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 */
package org.jenetics.internal.util;

import static java.lang.String.format;
import static java.util.Objects.requireNonNull;

import java.io.PrintStream;

/**
 * @author Franz Wilhelmstötter
 * @since 3.0
 * @version 3.0 — $Date: 2014-08-29 $
 */
public class CU {
	private final PrintStream _stream;

	public CU(final PrintStream stream) {
		_stream = requireNonNull(stream);
	}

	public void printTitle(final String title, final Object... args) {
		printHLine();
		println("# %-76s#", format(title, args));
		printHLine();
	}

	private void printEnvironment() {
		printHLine();
		println(
			"# %-76s#",
			format("%s %s (%s) ", p("os.name"), p("os.version"), p("os.arch"))
		);
		println(
			"# %-76s#",
			format("java version \"%s\"", p("java.version"))
		);
		println(
			"# %-76s#",
			format("%s (build %s)", p("java.runtime.name"), p("java.runtime.version"))
		);
		println(
			"# %-76s#",
			format("%s (build %s)", p("java.vm.name"), p("java.vm.version"))
		);
		printHLine();
	}

	private void printHLine() {
		_stream.print('#');
		print('=', 78);
		_stream.println('#');
	}

	private void print(final char c, final int times) {
		for (int i = 0; i < times; ++i) {
			_stream.print(c);
		}
	}

	private void print(final String pattern, final Object... args) {
		_stream.print(format(pattern, args));
	}

	private void println(final String pattern, final Object... args) {
		_stream.println(format(pattern, args));
	}

	private static String p(final String name) {
		return System.getProperty(name);
	}

}

Add some console utility class.


package org.apache.tinkerpop.gremlin.util.iterator;

import org.junit.Test;

import java.util.Iterator;

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

/**
 * @author Stephen Mallette (http://stephen.genoprime.com)
 */
public class IteratorUtilsTest {
    @Test
    public void shouldIterateSingleObject() {
        final Iterator<String> itty = IteratorUtils.of("test");
        assertEquals("test", itty.next());
        assertFalse(itty.hasNext());
    }

    @Test
    public void shouldIteratePairOfObjects() {
        final Iterator<String> itty = IteratorUtils.of("test1", "test2");
        assertEquals("test1", itty.next());
        assertEquals("test2", itty.next());
        assertFalse(itty.hasNext());
    }
}

Add unit test for IteratorUtils.


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

package io.michaelrocks.lightsaber.processor.warermark;

import org.objectweb.asm.Attribute;
import org.objectweb.asm.ByteVector;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Label;

public class LightsaberAttribute extends Attribute {
    public LightsaberAttribute() {
        this("Lightsaber");
    }

    private LightsaberAttribute(final String type) {
        super(type);
    }

    @Override
    protected LightsaberAttribute read(final ClassReader classReader, final int offset, final int length,
            final char[] buffer, final int codeOffset, final Label[] labels) {
        return new LightsaberAttribute();
    }

    @Override
    protected ByteVector write(final ClassWriter classWriter, final byte[] code, final int length, final int maxStack,
            final int maxLocals) {
        return new ByteVector();
    }
}

Add an attribute for watermarking Lightsaber-processed classes


package org.mutabilitydetector.benchmarks.mutabletofield;

public final class HasFieldOfGenericType<T> {

    public final T field;

    public HasFieldOfGenericType(T field) {
        this.field = field;
    }
}

Add pending test for allowing generic type field.


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

/**
 * Visitor classes for extracting values from a Configuration or Node corresponding to a plugin annotation.
 */
package org.apache.logging.log4j.core.config.plugins.visitors;

Add visitors package for PluginVisitors.


/*
 * Copyright 2015 Greg Kopff
 * 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 THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

package com.fatboyindustrial.omnium.thread;

import com.google.common.base.Preconditions;
import org.slf4j.Logger;

/**
 * An {@link Thread.UncaughtExceptionHandler} that logs the exception.
 */
public class LoggingUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler
{
  /** The log to write to. */
  private final Logger log;

  /**
   * Constructor.
   * @param log The log to write to.
   */
  public LoggingUncaughtExceptionHandler(final Logger log)
  {
    this.log = Preconditions.checkNotNull(log, "log cannot be null");
  }

  /**
   * Method invoked when the given thread terminates due to the given uncaught exception. <p>
   *
   * Any exception thrown by this method will be ignored by the Java Virtual Machine.
   *
   * @param t The thread.
   * @param e The exception.
   */
  @Override
  @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
  public void uncaughtException(final Thread t, final Throwable e)
  {
    Preconditions.checkNotNull(t, "t cannot be null");
    Preconditions.checkNotNull(e, "e cannot be null");

    this.log.warn("Uncaught exception in thread: {}", t.getName(), e);
  }
}

Add an uncaught exception handler that logs a message to a SLF4J logger.


package com.thinkaurelius.titan.blueprints;

import com.thinkaurelius.titan.BerkeleyStorageSetup;
import com.thinkaurelius.titan.StorageSetup;
import com.thinkaurelius.titan.diskstorage.berkeleyje.BerkeleyJETx;
import com.thinkaurelius.titan.diskstorage.configuration.ModifiableConfiguration;
import com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration;

import java.time.Duration;
import java.util.Set;

/**
 * @author Matthias Broecheler (me@matthiasb.com)
 */
public class BerkeleyGraphProvider extends AbstractTitanGraphProvider {

    @Override
    public ModifiableConfiguration getTitanConfiguration(String graphName, Class<?> test, String testMethodName) {
        return BerkeleyStorageSetup.getBerkeleyJEConfiguration(StorageSetup.getHomeDir(graphName)).set(GraphDatabaseConfiguration.IDAUTHORITY_WAIT, Duration.ofMillis(20));
    }

    @Override
    public Set<Class> getImplementations() {
        final Set<Class> implementations = super.getImplementations();
        implementations.add(BerkeleyJETx.class);
        return implementations;
    }

}

package com.thinkaurelius.titan.blueprints;

import com.thinkaurelius.titan.BerkeleyStorageSetup;
import com.thinkaurelius.titan.StorageSetup;
import com.thinkaurelius.titan.diskstorage.berkeleyje.BerkeleyJETx;
import com.thinkaurelius.titan.diskstorage.configuration.ModifiableConfiguration;
import com.thinkaurelius.titan.graphdb.configuration.GraphDatabaseConfiguration;

import java.time.Duration;
import java.util.Set;

/**
 * @author Matthias Broecheler (me@matthiasb.com)
 */
public class BerkeleyGraphProvider extends AbstractTitanGraphProvider {

    @Override
    public ModifiableConfiguration getTitanConfiguration(String graphName, Class<?> test, String testMethodName) {
        return BerkeleyStorageSetup.getBerkeleyJEConfiguration(StorageSetup.getHomeDir(graphName)).set(GraphDatabaseConfiguration.IDAUTHORITY_WAIT, Duration.ofMillis(150L));
    }

    @Override
    public Set<Class> getImplementations() {
        final Set<Class> implementations = super.getImplementations();
        implementations.add(BerkeleyJETx.class);
        return implementations;
    }

}

Increase BDB test ID timeout: 20 to 150 ms


package com.aleggeup.confagrid.router;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class RouteController {

    @RequestMapping({
        "/create",
        "/existing",
        "/intro",
        "/more"
    })
    public String router() {
        return "forward:/index.html";
    }
}

Create router to redirect frontend html5 paths


/**
 * 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.bigtop.bazaar.datagenerator.potentials;

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

import org.apache.bigtop.bazaar.datagenerator.base.Vec2D;
import org.junit.Test;

public class TestSphericalBoundaryConditions
{
	static final double EPS = 1e-5;

	@Test
	public void testInside()
	{
		final double radius = 3.0;
		final double strength = 2.0;
		final Vec2D center = new Vec2D(0.0, 0.0);

		final double expectedPE = 0.0;

		Potential potential = new SphericalBoundaryConditions(center, radius, strength);
		potential.update(new Vec2D[]{center});
		final double observedPE = potential.getEnergy();

		assertEquals("Observed PE: " + observedPE + ", expected PE: " + expectedPE,
				expectedPE, observedPE, EPS);
	}

	@Test
	public void testBoundary()
	{
		final double radius = 3.0;
		final double strength = 2.0;
		final Vec2D center = new Vec2D(0.0, 0.0);
		final Vec2D particleLocation = new Vec2D(3.0, 0.0);

		final double expectedPE = 0.0;

		Potential potential = new SphericalBoundaryConditions(center, radius, strength);
		potential.update(new Vec2D[]{particleLocation});
		final double observedPE = potential.getEnergy();

		assertEquals("Observed PE: " + observedPE + ", expected PE: " + expectedPE,
				expectedPE, observedPE, EPS);
	}

	@Test
	public void testOutside()
	{
		final double radius = 3.0;
		final double strength = 2.0;
		final Vec2D center = new Vec2D(0.0, 0.0);
		final Vec2D particleLocation = new Vec2D(4.0, 0.0);

		Potential potential = new SphericalBoundaryConditions(center, radius, strength);
		potential.update(new Vec2D[]{particleLocation});
		final double observedPE = potential.getEnergy();

		assertTrue("Observed PE: " + observedPE, observedPE > 0.0);
	}
}

Add test for boundary conditions


package br.com.caelum.vraptor.musicjungle.converter;

import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import br.com.caelum.vraptor.Convert;
import br.com.caelum.vraptor.Converter;
import br.com.caelum.vraptor.interceptor.multipart.UploadedFile;

/**
 * VRaptor's file upload converter.
 *
 */
@Convert(UploadedFile.class)
public class UploadedFileConverter implements Converter<UploadedFile> {

	private final HttpServletRequest request;

	public UploadedFileConverter(HttpServletRequest request) {
		this.request = request;
	}

	public UploadedFile convert(String value, Class<? extends UploadedFile> type, ResourceBundle bundle) {
		Object upload = request.getAttribute(value);
		return upload == null ? null : type.cast(upload);
	}
}

Add converter to upload files


package com.vladmihalcea.book.hpjp.hibernate.query.function;

import com.vladmihalcea.book.hpjp.util.AbstractPostgreSQLIntegrationTest;
import org.hibernate.boot.MetadataBuilder;
import org.hibernate.boot.spi.MetadataBuilderContributor;
import org.hibernate.dialect.function.SQLFunctionTemplate;
import org.hibernate.type.StandardBasicTypes;
import org.junit.Test;

import javax.persistence.*;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Properties;

import static org.junit.Assert.assertEquals;

/**
 * @author Vlad Mihalcea
 */
public class DateTruncTimeZoneFunctionTest extends AbstractPostgreSQLIntegrationTest {

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

    @Override
    protected void additionalProperties(Properties properties) {
        properties.put(
                "hibernate.metadata_builder_contributor",
                SqlFunctionsMetadataBuilderContributor.class
        );
    }

    public static class SqlFunctionsMetadataBuilderContributor
            implements MetadataBuilderContributor {

        @Override
        public void contribute(MetadataBuilder metadataBuilder) {
            metadataBuilder.applySqlFunction(
                    "date_trunc",
                    new SQLFunctionTemplate(
                            StandardBasicTypes.TIMESTAMP,
                            "date_trunc('day', (?1 AT TIME ZONE ?2))"
                    )
            );
        }
    }

    @Override
    public void afterInit() {
        doInJPA(entityManager -> {

            Post post = new Post();
            post.setId(1L);
            post.setTitle("High-Performance Java Persistence");
            post.setCreatedOn(Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 11, 22, 33)));

            entityManager.persist(post);
        });
    }

    @Test
    public void test() {
        doInJPA(entityManager -> {
            Tuple tuple = entityManager
            .createQuery(
                "select p.title as title, date_trunc(p.createdOn, :timezone) as creation_date " +
                "from Post p " +
                "where p.id = :postId", Tuple.class)
            .setParameter("postId", 1L)
            .setParameter("timezone", "UTC")
            .getSingleResult();

            assertEquals("High-Performance Java Persistence", tuple.get("title"));
            assertEquals(Timestamp.valueOf(LocalDateTime.of(2018, 11, 23, 0, 0, 0)), tuple.get("creation_date"));
        });
    }

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

        @Id
        private Long id;

        private String title;

        @Column(name = "created_on")
        private Timestamp createdOn;

        public Long getId() {
            return id;
        }

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

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public Timestamp getCreatedOn() {
            return createdOn;
        }

        public void setCreatedOn(Timestamp createdOn) {
            this.createdOn = createdOn;
        }
    }

}

Add date_trunc with time zone parameter


package com.yahoo.vespa.hosted.controller.api.integration.stubs;

import com.yahoo.vespa.hosted.controller.api.integration.BuildService;

public class MockBuildService implements BuildService {

    @Override
    public boolean trigger(BuildJob buildJob) {
        return true;
    }

}

Add dummy for container tests


/*
 * Copyright 2008 Novamente LLC
 * Copyright 2009 Linas Vepstas
 *
 * 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 relex.entity;

import java.io.Serializable;
import java.util.List;

public abstract class EntityTagger
{
	// An array of EntityInfos, ordered by their order in the sentence
	private List<EntityInfo> orderedEntityInfos;

	public abstract List<EntityInfo> tagEntities(String sentence);

	// --------------------------------------------------------

	/**
	 * Add the entity info to the list, inserting it in sorted order.
	 */
	public void addEntity(EntityInfo ei)
	{
		if (null == orderedEntityInfos)
			orderedEntityInfos = new ArrayList<EntityInfo>();

		int open = 0;
		int start = ei.getFirstCharIndex();
		int end = ei.getLastCharIndex();
		for (EntityInfo e: orderedEntityInfos)
		{
			int beg = e.getFirstCharIndex();
			if ((open <= start) && (end <= beg))
			{
				int idx = orderedEntityInfos.indexOf(e);
				orderedEntityInfos.add(idx, ei);
				return;
			}
			open = e.getLastCharIndex();

			// If our entity overlaps with existing entities, ignore it.
			if (start < open) return;
		}
		orderedEntityInfos.add(ei);
	}

	// --------------------------------------------------------

	/**
	 * Return all EntityInfo's ordered by their starting character
	 * position.
	 */
	public List<EntityInfo> getEntities()
	{
		return orderedEntityInfos;
	}

	public boolean equals(Object other)
	{
		if (! (other instanceof EntityTagger)) return false;
		EntityTagger et = (EntityTagger)other;
		return this.orderedEntityInfos.equals(et.orderedEntityInfos);
	}
}

Add the missing interface class


package fr.tvbarthel.apps.simplethermometer;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.DialogFragment;
import android.widget.ArrayAdapter;

public class TemperatureUnitPickerDialogFragment extends DialogFragment {

	private static final String BUNDLE_TEMPERATURE_UNIT_NAMES = "BundleTemperatureUnitNames";
	private static final String BUNDLE_TEMPERATURE_UNIT_SYMBOLS = "BundleTemperatureUnitSymbols";

	private TemperatureUnitPickerDialogFragment() {
		super();
	}

	public static TemperatureUnitPickerDialogFragment newInstance(String[] temperatureUnitNames, String[] temperatureUnitSymbols) {
		TemperatureUnitPickerDialogFragment fragment = new TemperatureUnitPickerDialogFragment();
		Bundle arguments = new Bundle();
		arguments.putStringArray(BUNDLE_TEMPERATURE_UNIT_NAMES, temperatureUnitNames);
		arguments.putStringArray(BUNDLE_TEMPERATURE_UNIT_SYMBOLS, temperatureUnitSymbols);
		fragment.setArguments(arguments);
		return fragment;
	}

	@Override
	public Dialog onCreateDialog(Bundle savedInstanceState) {

		Bundle arguments = getArguments();
		final String[] temperatureUnitNames = arguments.getStringArray(BUNDLE_TEMPERATURE_UNIT_NAMES);
		final String[] temperatureUnitSymbols = arguments.getStringArray(BUNDLE_TEMPERATURE_UNIT_SYMBOLS);

		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle(R.string.temperature_unit_picker_dialog_fragment_title);
		final ArrayAdapter<String> arrayAdapterColorNames = new ArrayAdapter<String>(getActivity(),
				android.R.layout.simple_expandable_list_item_1,
				temperatureUnitNames);
		builder.setAdapter(arrayAdapterColorNames, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				SharedPreferences defaultPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
				SharedPreferences.Editor editor = defaultPreferences.edit();
				editor.putString(MainActivity.PREF_KEY_TEMPERATURE_UNIT_STRING, temperatureUnitSymbols[which]);
				editor.commit();
			}
		});
		builder.setCancelable(true);
		builder.setNegativeButton(R.string.alert_dialog_cancel_button, null);

		return builder.create();
	}
}

Support Fahrenheit and Kelvin Unit(ter)


/*
 * Copyright 2022 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.
 */
@NonNullApi
package org.gradle.integtests.fixtures.validation;

import org.gradle.api.NonNullApi;

Fix nullability problems in org.gradle.integtests.fixtures.validation


import cloudsimulator.clustersimulator.SimulateFailures;
import cloudsimulator.clustersimulator.dto.SimulatedCluster;
import cloudsimulator.clustersimulator.dto.TCGroup;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.LinkedList;

public class TestSimulatedFailure {

    @Test
    public void testVmForFailure() {
        SimulateFailures simulateFailures = new SimulateFailures();
        double sla = 80.00;
        long vmCount = 1;
        SimulatedCluster simulatedCluster =
                new SimulatedCluster(
                        new LinkedList<TCGroup>(Arrays.asList(
                                new TCGroup("TC3", sla, vmCount))
                        )
                );

        long secondsToFailure = 0;
        while (simulatedCluster.getCluster().size() > 0) {
            simulateFailures.simulateFailures(simulatedCluster);
            secondsToFailure++;
        }

        System.out.println("Seconds until failure: " + secondsToFailure);
    }
}

Add unit test for VM failure simulator.


package com.bendb.thrifty.integration;

import com.bendb.thrifty.protocol.CompactProtocol;
import com.bendb.thrifty.protocol.Protocol;
import com.bendb.thrifty.testing.ServerProtocol;
import com.bendb.thrifty.testing.ServerTransport;
import com.bendb.thrifty.transport.FramedTransport;
import com.bendb.thrifty.transport.Transport;

public class NonblockingCompactProtocolConformance extends ConformanceBase {
    @Override
    protected ServerTransport getServerTransport() {
        return ServerTransport.NON_BLOCKING;
    }

    @Override
    protected ServerProtocol getServerProtocol() {
        return ServerProtocol.COMPACT;
    }

    @Override
    protected Transport decorate(Transport transport) {
        return new FramedTransport(transport);
    }

    @Override
    protected Protocol createProtocol(Transport transport) {
        return new CompactProtocol(transport);
    }
}

Add non-blocking CompactProtocol conformance test


/*
 * 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.asterix.external.input.record.reader;

import org.apache.asterix.external.input.record.reader.rss.RSSRecordReader;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;
import java.net.MalformedURLException;

public class RSSRecordReaderTest {
    @Test
    public void fetchFromDummyWebsite() throws MalformedURLException {
        String dummyRssFeedURL = "http://foobar";
        RSSRecordReader rssRecordReader = new RSSRecordReader(dummyRssFeedURL);
        Exception expectedException = null;
        try {
            rssRecordReader.next();
        } catch (IOException e) {
            expectedException = e;
        }
        Assert.assertNotNull(expectedException);
        Assert.assertTrue(expectedException.getMessage().contains("UnknownHostException"));
    }
}

Add test case for RSS feed


package leetcode.gray_code;

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> grayCode(int n) {
        ArrayList<Integer> ans = new ArrayList<Integer>();
        int prev = 0;
        ans.add(prev);
        for(int cnt = 0; cnt < (1 << n) - 1; cnt++){
        	int z = 0;
        	while(((1 << z) & cnt) != 0){
        		z++;
        	}
        	int next = prev ^ (1 << z);
        	ans.add(next);
        	prev = next;
        }
        return ans;
    }

    public static void main(String[] args){
    	ArrayList<Integer> ans = new Solution().grayCode(1);
    	for(int i : ans){
    		System.err.print(i + ", ");
    	}
    	System.err.println("");
    }
}

Add java solution for 89. Gray Code


package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.O;

import android.service.autofill.FillEventHistory;
import android.view.autofill.AutofillManager;

import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;

/**
 * Robolectric implementation of {@link android.os.AutofillManager}.
 */
@Implements(value = AutofillManager.class, minSdk = O)
public class ShadowAutofillManager {

  @Implementation
  protected FillEventHistory getFillEventHistory() {
    return null;
  }
}

Add basic shadow tro prevent NPE when dereferencing.


package gameEngine.meshGenerator;

import gameEngine.Material;
import gameEngine.Mesh;

public class BlockGenerator {
	public static Mesh generate(float xLength, float yLength, float zLength, Material m){
		float x = xLength/2f;
		float y = yLength/2f;
		float z = zLength/2f;
		float[] vertices = new float[]{
				//Front face
				x,  y, z,
				-x,  y, z,
				-x, -y, z,
				x, -y, z,
				//Top face
				x, y, z,
				-x, y, z,
				x, y, -z,
				-x, y, -z,
				//Back face
				x,  y, -z,
				-x,  y, -z,
				-x, -y, -z,
				x, -y, -z,
				//Bottom face
				x, -y, z,
				-x, -y,z,
				x, -y, -z,
				-x, -y, -z,
				//Left face
				-x,  y, z,
				-x,  y, -z,
				-x, -y, z,
				-x, -y, -z,
				//Right face
				x,  y, z,
				x,  y, -z,
				x, -y, z,
				x, -y, -z
		};

	float[] normales = {
					//Front face
					0,0,1f,
					0,0,1f,
					0,0,1f,
					0,0,1f,
					//Top face
					0,1f,0,
					0,1f,0,
					0,1f,0,
					0,1f,0,
					//Back face
					0,0,-1f,
					0,0,-1f,
					0,0,-1f,
					0,0,-1f,
					//Bottom face
					0,-1f,0,
					0,-1f,0,
					0,-1f,0,
					0,-1f,0,
					//Left face
					-1,0,0,
					-1,0,0,
					-1,0,0,
					-1,0,0,
					//Right face
					1,0,0,
					1,0,0,
					1,0,0,
					1,0,0
			};

			int[] indices = new int[]{
					//Front face
					0,1,2,0,2,3,
					//Top face
					4,6,5,6,7,5,
					//Back face
					8,11,10,8,10,9,
					//Bottom Face
					14,12,13,14,13,15,
					//Left face
					16,19,18,16,17,19,
					//Right face
					20,22,21,22,23,21
			};

			return new Mesh(vertices, m,normales, indices);
	}
}

Add of a block generator.


package absyn;

import env.Env;
import parse.Loc;
import types.Type;

public abstract class Dec extends AST {

   public Dec(Loc loc) {
      super(loc);
   }

   // Do semantic analysis of the declaraction
   public abstract void semantic(Env env);

}

Add abstract class for declartions


/*
 * Copyright (c) 2014, Colorado State University All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer. 2. Redistributions in
 * binary form must reproduce the above copyright notice, this list of
 * conditions and the following disclaimer in the documentation and/or other
 * materials provided with the distribution.
 *
 * This software is provided by the copyright holders and contributors "as is"
 * and any express or implied warranties, including, but not limited to, the
 * implied warranties of merchantability and fitness for a particular purpose
 * are disclaimed. In no event shall the copyright holder or contributors be
 * liable for any direct, indirect, incidental, special, exemplary, or
 * consequential damages (including, but not limited to, procurement of
 * substitute goods or services; loss of use, data, or profits; or business
 * interruption) however caused and on any theory of liability, whether in
 * contract, strict liability, or tort (including negligence or otherwise)
 * arising in any way out of the use of this software, even if advised of the
 * possibility of such damage.
 */

/**
 *
 *
 * @author ctolooee
 */
package mendel.data;

public class Metadata {
}

Add data package for representing datasets


/*
 * Copyright 2015 Square, 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.squareup.moshi.recipes;

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;
import com.squareup.moshi.Types;
import java.lang.reflect.Type;
import java.util.List;

public final class ReadJsonList {
  public void run() throws Exception {
    String json = "[\n"
        + "  {\n"
        + "    \"rank\": \"4\",\n"
        + "    \"suit\": \"CLUBS\"\n"
        + "  },\n"
        + "  {\n"
        + "    \"rank\": \"A\",\n"
        + "    \"suit\": \"HEARTS\"\n"
        + "  },\n"
        + "  {\n"
        + "    \"rank\": \"J\",\n"
        + "    \"suit\": \"SPADES\"\n"
        + "  }\n"
        + "]";

    Moshi moshi = new Moshi.Builder().build();

    Type listOfCardsType = Types.newParameterizedType(List.class, Card.class);
    JsonAdapter<List<Card>> jsonAdapter = moshi.adapter(listOfCardsType);

    List<Card> cards = jsonAdapter.fromJson(json);
    System.out.println(cards);
  }

  public static void main(String[] args) throws Exception {
    new ReadJsonList().run();
  }
}

Add read json array recipe