package net.java.sip.communicator.service.protocol;

import java.util.*;

public class OperationSetInstantMessageTransformImpl implements
		OperationSetInstantMessageTransform {

	public final Map<Integer, Vector<TransformLayer>> transformLayers = new Hashtable<Integer, Vector<TransformLayer>>();

	private static final int defaultPriority = 1;

	public void addTransformLayer(TransformLayer transformLayer) {
		this.addTransformLayer(defaultPriority, transformLayer);
	}

	public void addTransformLayer(int priority, TransformLayer transformLayer) {
		synchronized (transformLayers) {
			if (!transformLayers.containsKey(defaultPriority))
				transformLayers.put(defaultPriority,
						new Vector<TransformLayer>());

			transformLayers.get(defaultPriority).add(transformLayer);
		}
	}

	public boolean containsLayer(TransformLayer layer) {
		synchronized (transformLayers) {
			for (Map.Entry<Integer, Vector<TransformLayer>> entry : transformLayers
					.entrySet()) {
				if (entry.getValue().contains(layer))
					return true;
			}

		}
		return false;
	}

	public void removeTransformLayer(TransformLayer transformLayer) {
		synchronized (transformLayers) {
			for (Map.Entry<Integer, Vector<TransformLayer>> entry : transformLayers
					.entrySet()) {
				entry.getValue().remove(transformLayer);
			}
		}
	}

}

Integrate the second big patch for OTR. With this patch all the required GSoC functions are available. Third commit.


package yuku.alkitabconverter.paratest;

import java.io.RandomAccessFile;
import java.nio.charset.Charset;
import java.util.List;

import yuku.alkitab.yes.YesFile;
import yuku.alkitab.yes.YesFile.InfoEdisi;
import yuku.alkitab.yes.YesFile.InfoKitab;
import yuku.alkitab.yes.YesFile.Teks;
import yuku.alkitabconverter.bdb.BdbProses;
import yuku.alkitabconverter.bdb.BdbProses.Rec;
import yuku.alkitabconverter.util.RecUtil;
import yuku.alkitabconverter.yes_common.YesCommon;

public class Proses1 {
	static String BASE_VERSION_NAME = "paratest";

	static String INPUT_TEKS_1 = "./bahan/" + BASE_VERSION_NAME + "/in/test.txt";
	public static String INPUT_TEKS_ENCODING = "utf-8";
	public static int INPUT_TEKS_ENCODING_YES = 2; // 1: ascii; 2: utf-8;
	public static String INPUT_KITAB = "./bahan/" + BASE_VERSION_NAME + "/in/book_name_lines.txt";
	static String OUTPUT_YES = "./bahan/" + BASE_VERSION_NAME + "/out/" + BASE_VERSION_NAME + ".yes";
	public static int OUTPUT_ADA_PERIKOP = 0;
	static String INFO_NAMA = BASE_VERSION_NAME;
	static String INFO_SHORT_TITLE = "Paratest";
	static String INFO_LONG_TITLE = "Paragraph test";
	static String INFO_KETERANGAN = "Paragraph test (2012-10-22)";

	final Charset utf8 = Charset.forName("utf-8");

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

	private void u() throws Exception {
		List<Rec> xrec = new BdbProses().parse(INPUT_TEKS_1, "utf-8");

		System.out.println("Total verses: " + xrec.size());

		////////// PROSES KE YES
		final InfoEdisi infoEdisi = YesCommon.infoEdisi(INFO_NAMA, INFO_SHORT_TITLE, INFO_LONG_TITLE, RecUtil.hitungKitab(xrec), OUTPUT_ADA_PERIKOP, INFO_KETERANGAN, INPUT_TEKS_ENCODING_YES);
		final InfoKitab infoKitab = YesCommon.infoKitab(xrec, INPUT_KITAB, INPUT_TEKS_ENCODING, INPUT_TEKS_ENCODING_YES);
		final Teks teks = YesCommon.teks(xrec, INPUT_TEKS_ENCODING);

		YesFile file = YesCommon.bikinYesFile(infoEdisi, infoKitab, teks);

		file.output(new RandomAccessFile(OUTPUT_YES, "rw"));
	}
}

Create a fake yes file that contains only 1 chapter for span test


/*
 * Copyright (C) 2021 DiffPlug
 *
 * 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.diffplug.gradle.eclipserunner;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class JreVersion {
	public static int thisVm() {
		String jre = System.getProperty("java.version");
		if (jre.startsWith("1.8")) {
			return 8;
		} else {
			Matcher matcher = Pattern.compile("(\\d+)").matcher(jre);
			if (!matcher.find()) {
				throw new IllegalArgumentException("Expected " + jre + " to start with an integer");
			}
			int version = Integer.parseInt(matcher.group(1));
			if (version <= 8) {
				throw new IllegalArgumentException("Expected " + jre + " to start with an integer greater than 8");
			}
			return version;
		}
	}
}

Add the ability to calculate JRE version.


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

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

/**
 * Check for DNA that is not stored on the sequence-level coordinate system.
 */

public class SequenceLevel extends SingleDatabaseTestCase {

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

		addToGroup("post_genebuild");
		addToGroup("release");
		setDescription("Check for DNA that is not stored on the sequence-level coordinate system.");

	}

	/**
	 * Run the test.
	 *
	 * @param dbre
	 *          The database to use.
	 * @return true if the test passed.
	 *
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		boolean result = true;

		Connection con = dbre.getConnection();
		String sql = "SELECT cs.name, COUNT(1) FROM coord_system cs, seq_region s, dna d WHERE d.seq_region_id = s.seq_region_id AND cs.coord_system_id =s.coord_system_id AND attrib NOT LIKE '%sequence_level%' GROUP BY cs.coord_system_id";

		try {

			Statement stmt = con.createStatement();

			ResultSet rs = stmt.executeQuery(sql);

			if (rs == null) {

				ReportManager.correct(this, con, "All DNA is attached to a sequence-level co-ordinate system.");

			} else {

				while (rs.next()) {

					String coordSystem = rs.getString(1);
					int rows = rs.getInt(2);

					ReportManager.problem(this, con, String.format("Coordinate system %s has %d seq regions containing sequence, but it does not have the sequence_level attribute", coordSystem, rows));
					result = false;

				}

			}

		} catch (SQLException e) {
			System.err.println("Error executing: " + sql);
			e.printStackTrace();
		}

		return result;

	} // run

} // SequenceLevel


package edu.virginia.psyc.pi.mvc;

import edu.virginia.psyc.pi.Application;
import edu.virginia.psyc.pi.persistence.ParticipantDAO;
import edu.virginia.psyc.pi.persistence.ParticipantRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import java.util.Arrays;

import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

/**
 * Created with IntelliJ IDEA.
 * User: dan
 * Date: 3/24/14
 * Time: 10:31 AM
 * To change this template use File | Settings | File Templates.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
public class AdminControllerTest {

    @Autowired
    private AdminController adminController;

    private MockMvc mockMvc;

    @Autowired
    WebApplicationContext wac;

    @Mock
    private ParticipantRepository participantRepository;

    @Before
    public void setup() {

        // Process mock annotations
        MockitoAnnotations.initMocks(this);

        // Setup Spring test in webapp-mode (same config as spring-boot)
        this.mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
    }

    @Test
    public void testAdminListUsers() throws Exception {

        ParticipantDAO p1 = new ParticipantDAO(1, "Dan Funk", "daniel.h.funk@gmail.com", "bla", false);
        ParticipantDAO p2 = new ParticipantDAO(1, "John Smith", "john.h.funk@gmail.com", "bla2", false);
        ParticipantDAO p3 = new ParticipantDAO(1, "Frank Jones", "frank.h.funk@gmail.com", "bla3", false);

        when(participantRepository.findAll()).thenReturn(Arrays.asList(p1,p2,p3));

        MvcResult result = mockMvc.perform(get("/admin"))
                                .andExpect((status().isOk()))
                                .andReturn();

        String content = result.getResponse().getContentAsString();

        assert(content.contains("daniel.h.funk@gmail.com"));

    }

}

Format to add a simple test

Format to add a simple test


package org.mozilla.focus.webkit.matcher;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mozilla.focus.webkit.matcher.Trie.WhiteListTrie;
import org.robolectric.RobolectricTestRunner;

import static org.junit.Assert.*;

@RunWith(RobolectricTestRunner.class)
public class TrieTest {

    @Test
    public void findNode() throws Exception {
        final Trie trie = Trie.createRootNode();

        assertNull(trie.findNode("hello"));

        final Trie putNode = trie.put("hello");
        final Trie foundNode = trie.findNode("hello");

        assertNotNull(putNode);
        assertNotNull(foundNode);
        assertEquals(putNode, foundNode);

        // Substring matching: only works in one direction
        assertNull(trie.findNode("hell"));
        assertNotNull(trie.findNode("hellohello"));

        trie.put("hellohello");

        // Ensure both old and new overlapping strings can still be found
        assertNotNull(trie.findNode("hello"));
        assertNotNull(trie.findNode("hellohello"));
        assertNull(trie.findNode("hell"));
        assertNull(trie.findNode("hella"));
    }

    @Test
    public void testWhiteListTrie() {
        final WhiteListTrie trie;

        {
            final Trie whitelist = Trie.createRootNode();

            whitelist.put("abc");

            trie = WhiteListTrie.createRootNode();
            trie.putWhiteList("def", whitelist);
        }

        assertNull(trie.findNode("abc"));

        // In practice EntityList uses it's own search in order to cover all possible matching notes
        // (e.g. in case we have separate whitelists for mozilla.org and foo.mozilla.org), however
        // we don't need to test that here yet.
        final Trie foundWhitelist = trie.findNode("def");
        assertNotNull(foundWhitelist);

        assertNotNull(foundWhitelist.findNode("abc"));
    }
}

Add some basic tests for our Trie

Add some basic tests for our Trie


/*
 * Copyright 2017 Viktor Csomor
 *
 * 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 net.viktorc.pp4j.impl;

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

/**
 * A unit test class for {@link SimpleProcessManager}.
 *
 * @author Viktor Csomor
 */
public class SimpleProcessManagerTest extends TestCase {

  @Test
  public void testStartsUpInstantlyTrueIfNoPredicateDefined() {
    SimpleProcessManager manager = new SimpleProcessManager(new ProcessBuilder(""));
    Assert.assertTrue(manager.startsUpInstantly());
  }

  @Test
  public void testStartsUpInstantlyFalseIfPredicateDefined() {
    SimpleProcessManager manager = new SimpleProcessManager(new ProcessBuilder(""), null, (o, e) -> true);
    Assert.assertFalse(manager.startsUpInstantly());
  }

  @Test
  public void testIsStartedUpReturnsTrueIfPredicateDoes() {
    SimpleProcessManager manager = new SimpleProcessManager(new ProcessBuilder(""), null, (o, e) -> !e && "ready".equals(o));
    Assert.assertFalse(manager.isStartedUp("bla", false));
    Assert.assertFalse(manager.isStartedUp("ready", true));
    Assert.assertTrue(manager.isStartedUp("ready", false));
  }

  @Test
  public void testInitSubmissionEmptyIfNoProviderDefined() {
    SimpleProcessManager manager = new SimpleProcessManager(new ProcessBuilder(""));
    Assert.assertFalse(manager.getInitSubmission().isPresent());
  }

  @Test
  public void testInitSubmissionNotEmptyIfProviderDefined() {
    SimpleProcessManager manager = new SimpleProcessManager(new ProcessBuilder(""), null, null,
        () -> new SimpleSubmission<>(new SimpleCommand("")), null);
    Assert.assertTrue(manager.getInitSubmission().isPresent());
  }

  @Test
  public void testTerminationSubmissionEmptyIfNoProviderDefined() {
    SimpleProcessManager manager = new SimpleProcessManager(new ProcessBuilder(""));
    Assert.assertFalse(manager.getTerminationSubmission().isPresent());
  }

  @Test
  public void tesTerminationSubmissionNotEmptyIfProviderDefined() {
    SimpleProcessManager manager = new SimpleProcessManager(new ProcessBuilder(""), null, null, null,
        () -> new SimpleSubmission<>(new SimpleCommand("")));
    Assert.assertTrue(manager.getTerminationSubmission().isPresent());
  }

}

Add unit tests for SimpleProcessManager

Add unit tests for SimpleProcessManager


// 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;

/**
 * Custom exception class for GoogleShoppingQuerier class.
 */
public class ShoppingQuerierConnectionException extends Exception {
  public ShoppingQuerierConnectionException(String errorMessage, Throwable cause) {
    super(errorMessage, cause);
  }
}

Add custom exception for querier class

Add custom exception for querier class


package com.ibm.mil.cafejava;

import com.worklight.wlclient.api.WLResponse;

import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

import rx.Observable;
import rx.observers.TestSubscriber;

import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class JacksonConverterTest {
    private Observable<WLResponse> observable;

    @Before public void before() {
        Person person = new Person();
        person.setName("John");
        person.setAge(25);
        person.setDev(true);

        JSONObject jsonObject = mock(JSONObject.class);
        when(jsonObject.toString()).thenReturn(person.toString());

        WLResponse wlResponse = mock(WLResponse.class);
        when(wlResponse.getResponseJSON()).thenReturn(jsonObject);

        observable = Observable.just(wlResponse);
    }

    @Test public void testSimpleObject() {
        TestSubscriber<Person> subscriber = new TestSubscriber<>();
        observable.lift(new JacksonObjectConverter<>(Person.class)).subscribe(subscriber);

        subscriber.assertNoErrors();
        subscriber.assertTerminalEvent();

        List<Person> persons = subscriber.getOnNextEvents();
        assertEquals(1, persons.size());

        Person person = persons.get(0);
        assertEquals("John", person.getName());
        assertEquals(25, person.getAge());
        assertTrue(person.isDev());
    }
}

Write simple JacksonConverter test for object mapping


package no.ssb.vtl.model;

import org.junit.Test;

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

public class VTLObjectTest {

    @Test
    public void testIntegerCompare() throws Exception {

        VTLObject one = VTLObject.of(new Integer(1));
        VTLObject two = VTLObject.of(new Integer(2));
        VTLObject otherOne = VTLObject.of(new Integer(1));

        assertThat(one.compareTo(two)).isLessThan(0);
        assertThat(two.compareTo(one)).isGreaterThan(0);
        assertThat(one.compareTo(otherOne)).isEqualTo(0);
        assertThat(otherOne.compareTo(one)).isEqualTo(0);

    }

    @Test
    public void testDoubleCompare() throws Exception {

        VTLObject one = VTLObject.of(new Double(1));
        VTLObject two = VTLObject.of(new Double(2));
        VTLObject otherOne = VTLObject.of(new Double(1));

        assertThat(one.compareTo(two)).isLessThan(0);
        assertThat(two.compareTo(one)).isGreaterThan(0);
        assertThat(one.compareTo(otherOne)).isEqualTo(0);
        assertThat(otherOne.compareTo(one)).isEqualTo(0);

    }

    @Test
    public void testNumberCompare() throws Exception {

        VTLObject one = VTLObject.of(new Double(1));
        VTLObject two = VTLObject.of(new Integer(2));
        VTLObject otherOne = VTLObject.of(new Long(1));

        assertThat(one.compareTo(two)).isLessThan(0);
        assertThat(two.compareTo(one)).isGreaterThan(0);
        assertThat(one.compareTo(otherOne)).isEqualTo(0);
        assertThat(otherOne.compareTo(one)).isEqualTo(0);

    }
}

Add comparison tests with different number subclasses


package org.realityforge.arez.api2;

import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;

public class AbstractArezTest
{
  @BeforeTest
  protected void beforeTest()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setEnableNames( true );
    provider.setVerboseErrorMessages( true );
    provider.setCheckInvariants( true );
  }

  @AfterTest
  protected void afterTest()
    throws Exception
  {
    final ArezConfig.DynamicProvider provider = (ArezConfig.DynamicProvider) ArezConfig.getProvider();
    provider.setEnableNames( false );
    provider.setVerboseErrorMessages( false );
    provider.setCheckInvariants( false );
  }
}

Add base test that adds all the assertions and invariant checks


package monica.framework.tools;

import java.io.File;

public class Utils {
	public static File getPropertiesPath(String propertiesName) {
		String[] pathArray = System.getProperty("java.class.path").split(";");
		for (String s : pathArray) {
			File newFile = new File(s + File.separator + propertiesName);
			if (newFile.exists()) {
				return newFile;
			}
		}
		return null;
	}

}

Add tools for fetching file path

Add tools for fetching file path


package org.pinae.timon.session;

import java.io.IOException;

import org.pinae.timon.session.defaults.DefaultSqlSessionFactory;

/**
 * 会话帮助类
 *
 * @author Huiyugeng
 *
 */
public class SqlSessionHelper {

	private static final ThreadLocal<SqlSessionFactory> THREAD_SESSION_FACTORY = new ThreadLocal<SqlSessionFactory>();
	private static final ThreadLocal<SqlSession> THREAD_SESSION = new ThreadLocal<SqlSession>();

	/**
	 * 获取当前线程的会话工厂类
	 *
	 * @return 会话工厂类
	 * @throws IOException IO异常处理
	 */
	public static SqlSessionFactory getSessionFactory() throws IOException {
		SqlSessionFactory sessionFactory = THREAD_SESSION_FACTORY.get();
		try {
			if (sessionFactory == null) {
				sessionFactory = new DefaultSqlSessionFactory();
				THREAD_SESSION_FACTORY.set(sessionFactory);
			}
		} catch (Exception e) {
	        throw new IOException(e);
	    }
	    return sessionFactory;
	}

	/**
	 * 获取当前线程的Sql会话
	 *
	 * @return Sql会话类
	 * @throws IOException IO异常处理
	 */
	public static SqlSession getSession() throws IOException {
		SqlSession session = (SqlSession) THREAD_SESSION.get();
	    try {
	        if (session == null) {
	        	session = getSessionFactory().getSession();
	        	THREAD_SESSION.set(session);
	        }
	    } catch (Exception e) {
	        throw new IOException(e);
	    }
	    return session;
	}
}

Add static getSqlSessionFactory and getSqlSession


package io.orchestrate.client;

import static org.junit.Assert.assertFalse;

import java.io.IOException;

import org.glassfish.grizzly.http.HttpHeader;
import org.junit.Test;

public class RelationFetchOperationTest {
    private static final JacksonMapper mapper = new JacksonMapper();
    private static final HttpHeader httpHeader = null;

    @Test
    public void jsonIsNull() throws IOException {
        final RelationFetchOperation operation = new RelationFetchOperation("collection", "key", "kinds");
        final Iterable<KvObject<String>> response = operation.fromResponse(404, httpHeader, null, mapper);
        assertFalse(response.iterator().hasNext());
    }

    @Test
    public void jsonIsBlank() throws IOException {
        final RelationFetchOperation operation = new RelationFetchOperation("collection", "key", "kinds");
        final Iterable<KvObject<String>> response = operation.fromResponse(404, httpHeader, "", mapper);
        assertFalse(response.iterator().hasNext());
    }

    @Test
    public void jsonIsEmpty() throws IOException {
        final RelationFetchOperation operation = new RelationFetchOperation("collection", "key", "kinds");
        final Iterable<KvObject<String>> response = operation.fromResponse(404, httpHeader, "{}", mapper);
        assertFalse(response.iterator().hasNext());
    }
}

Add basic, and failing, unit tests for RelationFetchOperation.fromResponse()


/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

public class Solution {

    public int maxDepth(TreeNode root) {

        if (root == null) {
            return 0;
        }

        return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;

    }

}

Create : 104 Maximum Depth of Binary Tree


/*
 * Copyright (C) 2015 The Minium 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 minium.cucumber;

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

import cucumber.runtime.io.Resource;

public class StringResource implements Resource {

    private String path;
    private InputStream inputStream;

    public StringResource(String path, InputStream inputStream) {
        super();
        this.path = path;
        this.inputStream = inputStream;
    }

    @Override
    public String getPath() {
        return path;
    }

    @Override
    public String getAbsolutePath() {
        return new File(this.path).getAbsolutePath();
    }

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

    @Override
    public String getClassName(String extension) {
        String path = getPath();
        return path.substring(0, path.length() - extension.length()).replace(File.separatorChar, '.');
    }
}

Add the missing class to fix the minium developer build.


package com.whereuat.whereu.db;

import android.os.AsyncTask;

import com.whereuat.whereu.db.command.DbCommand;

/**
 * Created by kangp3 on 4/5/16.
 */
public class DbTask extends AsyncTask<DbCommand, Void, Object> {
    public interface AsyncResponse {
        void processFinish(Object result);
    }

    public AsyncResponse delegate = null;

    public DbTask(AsyncResponse delegate) {
        this.delegate = delegate;
    }

    @Override
    protected Object doInBackground(DbCommand... commands) {
        DbCommand command = commands[0];
        return command.execute();
    }

    @Override
    protected void onPostExecute(Object result) {
        if (delegate != null) {
            delegate.processFinish(result);
        }
    }
}

Add custom AsyncTask for DB operations

Add custom AsyncTask for DB operations


package org.jenkinsci.plugins.p4.client;

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

import java.util.logging.Logger;

import org.jenkinsci.plugins.p4.DefaultEnvironment;
import org.junit.Test;

public class ViewMapHelperTest extends DefaultEnvironment {
    private static Logger logger = Logger.getLogger(ViewMapHelperTest.class.getName());

    @Test
    public void testSplitDepotPath_singlepath_ok(){
        String[] res = ViewMapHelper.splitDepotPath("//depot/Projects/my-super-project");
        String[] exp = new String[]{"depot", "Projects", "my-super-project" };

        assertArrayEquals("Depot path is equal", exp, res);
    }

    @Test
    public void testgetClientView_multipath_ok(){
        String multi_path =
            "\n//depot/Projects/Foo/Bar/Baz/Tick/Tock/...\n//depot/Projects/Foo/Bar/Baz/Tick/Tack/...\n";
        String res = ViewMapHelper.getClientView(multi_path, "p4client", false);
        // String[] exp = new String[]{"depot", "Projects", "my-super-project" };

        assertEquals("Depot path is equal", "Something", res);
    }
}

Add test class with failing test for viewmaphelper


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

package com.billyyccc.database;

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

Add a db service layer test stub

Add a db service layer test stub


package checksum;

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

public class ChecksumGenerator
{
  private MessageDigest digester;

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

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

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

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

    return digester.digest();
  }

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

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

    return checksumString;
  }

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

      File file = new File(fileName);

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

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

Implement a simple checksum generator

Implement a simple checksum generator


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

public class RegExConverter {

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

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

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

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

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

		String formattedRegEx = formatRegEx(regex);

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

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

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

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

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

		}

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

		return postfix;
	}
}

Add converter from infix to postfix notation.


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

Add a package annotation to distancemetrics.


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2009 - 2013 Board of Regents of the University of
 * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
 * Institute of Molecular Cell Biology and Genetics.
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 * The views and conclusions contained in the software and documentation are
 * those of the authors and should not be interpreted as representing official
 * policies, either expressed or implied, of any organization.
 * #L%
 */

package imagej.text.io;

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

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

import org.scijava.plugin.Plugin;

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

	// -- IOPlugin methods --

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

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

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

}

Add an I/O plugin for text formats

Add an I/O plugin for text formats

It standardizes incoming text to HTML, so that it can ultimately be
displayed in an HTML-based rich text viewer.

The implementation is nice and simple thanks to the TextService.


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

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

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

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

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

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

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

Add helper class for implementing 'equals' method.


package aeronicamc.mods.mxtune.gui.widget;

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

import javax.annotation.Nullable;

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

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

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

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

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

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

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

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

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

    public int getPadding()
    {
        return padding;
    }

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

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


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

package com.pyamsoft.padlock.dagger.lock;

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

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

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

  LockInteractor interactor;

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

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

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

Add test for lock interactor

Add test for lock interactor


package leetcode.valid_parentheses;

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

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

Add java solution for 20. Valid Parentheses

20. Valid Parentheses: https://leetcode.com/problems/valid-parentheses/


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

import java.awt.BorderLayout;

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

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

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

	private static final long serialVersionUID = -5363687740449453246L;

	private BornStarter bornStarter = null;

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

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

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

}

Add class to initialize from Protege

Add class to initialize from Protege


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

package tachyon.worker.block.allocator;

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

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

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

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

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

Add a class of a naive implementation of Allocator interface


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

package com.google.android.gnd.ui.settings;

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

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

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

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

Add class to manage preference keys

Add class to manage preference keys


package no.ssb.vtl.model;

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

import com.google.common.collect.ImmutableMap;

import java.util.Map;

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

    private final Map<String, VTLExpression> context;

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

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

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

    @FunctionalInterface
    interface Body {
        VTLObject execute();
    }

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

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

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

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

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

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

Add a function class to the model

Add a function class to the model


package com.hankcs.hanlp.algorithm;

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

public class EditDistanceTest {

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

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

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

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

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

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

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

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

These tests were written using Diffblue Cover.


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

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

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

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


package pipe.models.visitor;

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

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

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

public class PetriNetComponentRemovalVisitorTest {
    PetriNet mockNet;
    PetriNetComponentRemovalVisitor visitor;

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

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

    }

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

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

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

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

    }

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

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

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

Add better unit tests for PetriNetComponentRemovalVisitor


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

import org.junit.Test;

import java.util.UUID;

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

public class TestVendorArrays {

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

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

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

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

Add a test for arrays' support in HSQLDB

Verify that we can save and retrieve arrays from a HSQLDB database
using the HSQLDB driver.


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

package io.github.bonigarcia.wdm.test;

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

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

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

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

    private WebDriver driver;

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

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

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

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

        // Open page
        driver.get(sutUrl);

        // Wait 5 seconds
        sleep(5000);
    }

}

Add remote test for WebRTC with Firefox

Add remote test for WebRTC with Firefox


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

package com.s13g.winston.common;

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

  private TypeConversion() {
  }

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

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

Add basic type conversion for REST requests.


package com.fasterxml.jackson.failing;

import com.fasterxml.jackson.annotation.*;

import com.fasterxml.jackson.databind.*;

import java.util.*;

public class TestIssue877TypingWithId extends BaseMapTest
{
    interface BaseInterface { }

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

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

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

    static class LisWrappert<T extends BaseInterface> {

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

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

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

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

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

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

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

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

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

        LisWrappert<BaseInterfaceImpl> result;

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

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

Add a test to reproduce

Add a test to reproduce [JACKSON-877]


package ru.ifmo.nds;

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

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

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

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

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

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

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


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

package com.btmura.android.reddit.content;

import java.io.IOException;

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

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

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

    public static final String TAG = "UserInfoLoader";

    private final String user;
    private AccountResult result;

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

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

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

Add loader that grabs a user's info

Add loader that grabs a user's info


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

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

Add package-level doc. for filters

Add package-level doc. for filters

git-svn-id: 25ca64b629f24bdef6d1cceac138f74b13f55e41@659162 13f79535-47bb-0310-9956-ffa450edef68


package gherkin.formatter;

import java.util.List;

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

package gherkin.formatter;

import java.util.List;

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

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


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

public class MyStack {

    private Queue<Integer> queue;

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

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

        queue.add(x);

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

    }

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

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

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

}

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

Create : 225 Implement Stack using Queues


package net.lifove.research.utils;

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

import org.junit.Test;

import weka.core.Instances;

public class CrossPredictionTest {

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

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

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

Add cross prediciton test case

Add cross prediciton test case


package de.slikey.effectlib.effect;

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

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

public class ArcLocationEffect extends LocationEffect {

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

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

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

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

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

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

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

			step++;
		}
	}

}

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


package com.jmb.springfactory.model.bo;

public class BusinessObjectBase {

  private String id;

  public String getId() {
    return id;
  }

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

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


package router.client;

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

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

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

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

    final RegExp re = RouteDefinition.pathToRegex( path );

    assertEquals( re, mock );

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

Introduce a very basic test

Introduce a very basic test


package to.etc.domui.hibernate.idgen;

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

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

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

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

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

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

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

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

}

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


package org.intermine.webservice.server.output;

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

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

public class TableCellFormatter
{

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

    private final LinkRedirectManager redirector;
    private final InterMineAPI im;

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

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

Refactor json cell formatting into own class

Former-commit-id: ff2289c99591625a7a7a3b36d52287a889d4457d


package net.imagej.ops.views;

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

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

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

}

Add default implementation of CollapseNumeric to CompositeIntervalView.


package org.springframework.test.integration;

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

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

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

public class StaticAssetRequestMappingTest {

	private static ConfigurableApplicationContext context;

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

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

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

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

}

Fix mime type for css (and test)

Fix mime type for css (and test)


package org.robockets.stronghold.robot.autonomous;

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

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

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

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

Add autonomous command for drawbridge.

Add autonomous command for drawbridge.


package com.codeborne.selenide.conditions;

import com.codeborne.selenide.Driver;

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

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

class ExactTextCaseSensitiveTest {

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

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

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

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

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

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

}

Add tests for ExactTextCaseSensitive condition


package com.enginemobi.core.generic.util;

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

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

@Component
public class EntityManagerUtils {

	@Autowired
	private EntityManagerFactory entityManagerFactory;

	@PersistenceContext
	private EntityManager entityManager;

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

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

	public EntityManager getEntityManager() {
		return entityManager;
	}
}

Add entity manager utils for unit testing


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

import java.io.IOException;

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

 */
public class SystemConsoleInoutTest {

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

}

Add test cases for SystemConsoleInout

Add test cases for SystemConsoleInout


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

/**
 * Package to test JOrphanUtils methods
 */

package org.apache.jorphan.exec;

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

import junit.framework.TestCase;

public class TestKeyToolUtils extends TestCase {

    public TestKeyToolUtils() {
        super();
    }

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

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

Test assumptions regarding keytool check

git-svn-id: 5ccfe34f605a6c2f9041ff2965ab60012c62539a@1544901 13f79535-47bb-0310-9956-ffa450edef68


package com.m4gik.util;

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

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

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

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

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

    private final Object input;

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

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

}

Create TDD test for utils.

Create TDD test for utils.


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

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/

package io.sigpipe.sing.stat;

public class OnlineKDEException extends Exception {

    public OnlineKDEException() {
        super();
    }

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

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

}

Add generic Online KDE exception

Add generic Online KDE exception


package search;

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

class TestSearch{

	// Tests binary search

	public static void testBinarySearch(){

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

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

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

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

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

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

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

		}

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

	}

	public static void main(String args[]){

		// Call testBinarySearch
		testBinarySearch();

	}

}

Add test class for binary search

Add test class for binary search


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

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;

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

}

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

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;

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

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

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

Add solution to problem 76

Add solution to problem 76


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

import junit.framework.TestCase;

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

public class AddServiceTaskTest extends TestCase {

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

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

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

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

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

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

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

Add forgotten unit test for adding a new service task

git-svn-id: f26ccc5efe72c2bd8e1c40f599fe313f2692e4de@9231 a612230a-c5fa-0310-af8b-88eea846685b