package leetcode;

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

    }

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

Create skeleton for problem 215

Create skeleton for problem 215


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

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

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

public class PreferredPooledLoSequenceIdentifierTest extends AbstractPooledSequenceIdentifierTest {

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

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

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

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

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

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

Add test case for setting the preferred pooled optimizer strategy


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

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

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

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

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

Add test with try and column with at sign


package seedu.taskitty.model;

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

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

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

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

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

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

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

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


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

package org.broadleafcommerce.common.util.sql.importsql;

import org.hibernate.tool.hbm2ddl.SingleLineSqlCommandExtractor;

import java.io.Reader;

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

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

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

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

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

        return statements;
    }
}

Allow dynamic conversion of import sql for SQL Server compatibility


package ships.model;

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

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

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

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

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

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

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

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

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

}

Add class for storing status of ship placement

Stores size, direction and activation of placement


/*
 * Copyright (c) 2012 The University of Manchester, UK.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the names of The University of Manchester nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package uk.org.taverna.server.client;

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

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

}

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

This test suite lists all test classes, including those in sub-packages.


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

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

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

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

XWIKI-3105: Use the same Range implementation for all browsers

git-svn-id: 04343649e741710b2e0f622af6defd1ac33e5ca5@15390 f329d543-caf0-0310-9063-dda96c69346f


package me.proxer.library.api;

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

import java.util.Date;

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

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

    private ConferenceAdapter adapter;

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

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

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

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

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

        return result;
    }

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

Add tests for the ConferenceAdapter

Add tests for the ConferenceAdapter


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

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

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

public class TestDocUseCases {

	private static MiniDFSCluster cluster;
	private static URI clusterUri;

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

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

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

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

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

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

}

Add more unit test from Oracle NIO documentation.


package me.izstas.rfs.client.util;

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

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

    private SwingExecutor() {
    }

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

Add Executor implementation which executes tasks in Swing event thread


package edu.hm.hafner.analysis.parser;

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

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

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

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

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

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

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

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

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

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

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

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

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

Add parser for Brakeman JSON reports

Add parser for Brakeman JSON reports


import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.sps.data.Recipe;
import com.google.sps.data.User;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

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

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

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

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

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

Implement servlet for fetching user shopping list


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

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

Add null checking by default

Add null checking by default


package com.brewtab.ircbot.util;

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

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

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

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

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

            statement.setString(1, key);

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

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

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

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

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

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

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

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

Add SQLProperites class for storing simple key value properties


package brooklyn.cli;

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

public class ClientTest {

    @BeforeClass
    public void testSetUp() {}

    @AfterClass
    public void testTearDown() {}

    @Test
    public void testCatalogEntitiesCommand() {

    }

}

Add a unit test class for the new cli client


package rabbit.filter.authenticate;

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

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

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

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

package rabbit.filter.authenticate;

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

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

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

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

Remove param that is no longer used.

Remove param that is no longer used.


package algorithms.problems;

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

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

public class DeepestNodeBinaryTree {

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

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

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

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

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

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

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

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

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

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

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

Add solution for deepest node in a BinaryTree :smile:


package org.pilgrim.leetcode.y2022;

import java.util.Arrays;

public class SumTwoInSorterArray {

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

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

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

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

        return res;
    }

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

}

Add sum two in sorted array

Add sum two in sorted array


package fr.tvbarthel.apps.simpleweatherforcast.openweathermap;

import android.os.AsyncTask;

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

import java.util.ArrayList;

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

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

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

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

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

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

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

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

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

}

Add an async task to parse the json.

Add an async task to parse the json.


package ua.qa.training.sandbox;

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

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

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

Add test for Square (from the video)

Add test for Square (from the video)


package org.bitrepository.monitoringservice;

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

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

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

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

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

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

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

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

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

}

Add begining of alarm sending in monitoring service


package cz.eeg.data;

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

import org.junit.Test;

public class MarkerTest  {

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

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

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

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

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

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

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

}

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

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


package se.movlin.hackerrank.reviewloop;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.function.IntPredicate;

public class Solution {

	public static void main(String[] args) {
		List<String> strings = readInput();

		for(String string : strings) {
			printString(string.toCharArray(), (i) -> i % 2 == 0);
			System.out.print(" ");
			printString(string.toCharArray(), (i) -> i % 2 == 1);
			System.out.println("");
		}

	}

	private static void printString(char[] string, IntPredicate f) {
		for (int i = 0; i<string.length; i++) {
			if (f.test(i)) {
				System.out.print(string[i]);
			}
		}
	}

	protected static List<String> readInput() {
		List<String> strings;
		int nrOfStrings;
		Scanner scanner = new Scanner(System.in);
		nrOfStrings = scanner.nextInt(); scanner.nextLine();
		strings = new ArrayList<String>(nrOfStrings);
		for (int i = 0; i < nrOfStrings; i++) {
			strings.add(scanner.nextLine());
		}
		scanner.close();
		return strings;
	}

}

Add solution for review loop

Add solution for review loop


/*
 * Copyright 2017 Ivaylo Stoyanov <me@ivkos.com>
 *
 * 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.ivkos.gpsd4j.messages;

import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.ToString;

@ToString
@EqualsAndHashCode(callSuper = false)
public class ErrorMessage extends GpsdMessage
{
   public static final String CLASS = "ERROR";

   @Getter
   private String message;

   @Override
   public String getGpsdClass()
   {
      return CLASS;
   }
}

Add support for ERROR messages

Add support for ERROR messages


/*
 * Licensed Materials - Property of IBM
 * © Copyright IBM Corporation 2015. All Rights Reserved.
 */

package com.ibm.mil.cafejava;

public class CafeJava {
}

Create initial class for library

Create initial class for library


/*
 * This file is part of ELKI:
 * Environment for Developing KDD-Applications Supported by Index-Structures
 *
 * Copyright (C) 2017
 * ELKI Development Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package de.lmu.ifi.dbs.elki.algorithm.clustering.hierarchical.extraction;

import org.junit.Test;

import de.lmu.ifi.dbs.elki.algorithm.AbstractAlgorithm;
import de.lmu.ifi.dbs.elki.algorithm.clustering.AbstractClusterAlgorithmTest;
import de.lmu.ifi.dbs.elki.algorithm.clustering.hierarchical.AnderbergHierarchicalClustering;
import de.lmu.ifi.dbs.elki.data.Clustering;
import de.lmu.ifi.dbs.elki.database.Database;
import de.lmu.ifi.dbs.elki.utilities.ELKIBuilder;

/**
 * Regression test for k clusters with minsize extraction.
 *
 * @author Erich Schubert
 */
public class ClustersWithNoiseExtractionTest extends AbstractClusterAlgorithmTest {
  @Test
  public void testClustering() {
    Database db = makeSimpleDatabase(UNITTEST + "3clusters-and-noise-2d.csv", 330);
    Clustering<?> clustering = new ELKIBuilder<>(ClustersWithNoiseExtraction.class) //
        .with(ClustersWithNoiseExtraction.Parameterizer.K_ID, 3) //
        .with(ClustersWithNoiseExtraction.Parameterizer.MINCLUSTERSIZE_ID, 5) //
        .with(AbstractAlgorithm.ALGORITHM_ID, AnderbergHierarchicalClustering.class) //
        .build().run(db);
    testFMeasure(db, clustering, 0.9242);
    testClusterSizes(clustering, new int[] { 56, 123, 151 });
  }
}

Test for the new cluster extraction method.


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

/**
 * Enumerates organization types responsible for developing and maintaining RF2 release file content.
 *
 * @see
 * 2.1.2. Release File Naming Convention
 */
public enum Rf2MaintainerType {

	/** Files are maintained and distributed by SNOMED International. */
	SNOMED_INTERNATIONAL("SNOMED International"),

	/** Files are maintained and distributed by a National Release Center (NRC). */
	NRC("National release center"),

	/** Files are maintained by a non-NRC extension provider. */
	OTHER_EXTENSION_PROVIDER("Other extension provider");

	private final String displayLabel;

	private Rf2MaintainerType(final String displayLabel) {
		this.displayLabel = displayLabel;
	}

	@Override
	public String toString() {
		return displayLabel;
	}
}

SO-2881: Add enum for maintaining organization type

This controls whether "INT", an ISO3166 country code or an empty prefix
should appear in the CountryNamespace element of each exported file.


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

/**
 * Given a singly linked list, can you write a method to return the reversed list?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseLinkedList {
}

Add statement to problem 22

Add statement to problem 22


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

package org.apache.shardingsphere.orchestration.internal.registry.fixture;

import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenter;
import org.apache.shardingsphere.orchestration.reg.api.RegistryCenterConfiguration;
import org.apache.shardingsphere.orchestration.reg.listener.DataChangedEventListener;

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

public final class ThirdTestRegistryCenter implements RegistryCenter {

    @Getter
    @Setter
    private Properties properties = new Properties();

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

    private ReentrantLock lock = new ReentrantLock();

    @Override
    public void init(final RegistryCenterConfiguration config) {
    }

    @Override
    public String get(final String key) {
        return "";
    }

    @Override
    public String getDirectly(final String key) {
        return keys.get(key);
    }

    @Override
    public boolean isExisted(final String key) {
        return keys.containsKey(key);
    }

    @Override
    public List<String> getChildrenKeys(final String key) {
        return Collections.emptyList();
    }

    @Override
    public void persist(final String key, final String value) {
        keys.put(key,value);
    }

    @Override
    public void update(final String key, final String value) {
        keys.put(key,value);
    }

    @Override
    public void persistEphemeral(final String key, final String value) {
    }

    @Override
    public void watch(final String key, final DataChangedEventListener dataChangedEventListener) {
    }

    @Override
    public void close() {
    }

    @Override
    public String getType() {
        return "ThirdTestRegistryCenter";
    }

    @Override
    public void initLock(final String key){
        lock = new ReentrantLock();
    }

    @Override
    public boolean tryLock(){
        return lock.tryLock();
    }

    @Override
    public void tryRelease(){
        lock.unlock();
    }
}

Add leaf segment key generator related functions and modify registry center implementation class.


package com.easternedgerobotics.rov.io;

import java.io.IOException;

public interface Device {
    void write(byte writeAddress, byte[] buffer) throws IOException;

    byte[] read(byte readAddress, int readLength) throws IOException;
}

Add interface for io devices such as i2c or spi


package org.jdesktop.swingx;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;

import org.jdesktop.swingx.JXHeader;
import org.jdesktop.swingx.JXMultiSplitPane;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.MultiSplitLayout;
import org.jdesktop.swingx.MultiSplitLayout.Node;

public class JXMultiSplitPaneVisualIssues extends InteractiveTestCase {

    private static void prepare(JFrame f) {
        prepare(f, MultiSplitLayout.parseModel("(ROW (COLUMN weight=0.5 left.top left.bottom)" +
                " (LEAF name=middle)" +
                " (COLUMN weight=0.5 right.top right.bottom))"));

    }

    private static void prepare(JFrame f, Node model) {
        final JXMultiSplitPane msp;
        JXPanel p = new JXPanel(new BorderLayout());
        JXHeader header = new JXHeader();
        header.setTitle("<html><B>JXMultiSplitPaneIssue</b>");
        header.setDescription("<html>This is a bit tricky ... To reproduce the issue move one of the dividers and then click reset. Expected behavior is that original layout is restored. Actual behavior (bug) is that only two cells stay displayed and no divider is visible.");
        p.add(header, BorderLayout.NORTH);
        msp = new JXMultiSplitPane();
        msp.setModel(model);
        p.add(msp);
        JButton green = new JButton("mid");
        green.setBackground(Color.GREEN);
        msp.add(green, "middle");
        msp.add(new JButton("l.t"), "left.top");
        msp.add(new JButton("l.b"), "left.bottom");
        msp.add(new JButton("r.t"), "right.top");
        msp.add(new JButton("r.b"), "right.bottom");
        f.add(p);
        JButton b = new JButton(new AbstractAction("Reset") {

            public void actionPerformed(ActionEvent e) {
                // just reset the model
                msp.setModel(MultiSplitLayout.parseModel("(ROW (COLUMN weight=0.5 left.top left.bottom)" +
                " (LEAF name=middle)" +
                " (COLUMN weight=0.5 right.top right.bottom))"));
                msp.revalidate();
                msp.repaint();
            }

        });
        f.add(b, BorderLayout.SOUTH);
        f.setPreferredSize(new Dimension(400, 400));
    }

    public void interactiveModelChange() {
        JFrame f = new JFrame();
        prepare(f);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        JXMultiSplitPaneVisualIssues test = new JXMultiSplitPaneVisualIssues();
        try {
            test.runInteractiveTests();
          } catch (Exception e) {
              System.err.println("exception when executing interactive tests:");
              e.printStackTrace();
          }
    }

}

Test exposing MultiSplitPane model reset issue.


package hello;

import com.google.common.net.MediaType;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;

import static hello.HelloWebServer.TEXT_PLAIN;

/**
 * Handles the plaintext test.
 */
final class PlaintextHandler implements HttpHandler {
  @Override
  public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(
        Headers.CONTENT_TYPE, TEXT_PLAIN);
    exchange.getResponseSender().send("Hello, World!");
  }
}

package hello;

import com.google.common.net.MediaType;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.util.Headers;
import java.nio.ByteBuffer;

import static hello.HelloWebServer.TEXT_PLAIN;

/**
 * Handles the plaintext test.
 */
final class PlaintextHandler implements HttpHandler {
  private static final ByteBuffer buffer;
  private static final String MESSAGE = "Hello, World!";

  static {
      buffer = ByteBuffer.allocateDirect(MESSAGE.length());
      try {
          buffer.put(MESSAGE.getBytes("US-ASCII"));
      } catch (Exception e) {
          throw new RuntimeException(e);
      }
      buffer.flip();
  }

  @Override
  public void handleRequest(HttpServerExchange exchange) throws Exception {
    exchange.getResponseHeaders().put(
        Headers.CONTENT_TYPE, TEXT_PLAIN);
    exchange.getResponseSender().send(buffer.duplicate());
  }
}

Make test apples to apples with other framework tests that have started caching the response buffer


/*
 * Copyright 2014 ZXing 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.google.zxing;

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

public final class PlanarYUVLuminanceSourceTestCase extends Assert {

  private static final byte[] YUV = {
       0,  1,  1,  2,  3,  5,
       8, 13, 21, 34, 55, 89,
       0,  -1,  -1,  -2,  -3,  -5,
      -8, -13, -21, -34, -55, -89,
      127, 127, 127, 127, 127, 127,
      127, 127, 127, 127, 127, 127,
  };
  private static final int COLS = 6;
  private static final int ROWS = 4;
  private static final byte[] Y = new byte[COLS * ROWS];
  static {
    System.arraycopy(YUV, 0, Y, 0, Y.length);
  }

  @Test
  public void testNoCrop() {
    PlanarYUVLuminanceSource source =
        new PlanarYUVLuminanceSource(YUV, COLS, ROWS, 0, 0, COLS, ROWS, false);
    assertEquals(Y, 0, source.getMatrix(), 0, Y.length);
    for (int r = 0; r < ROWS; r++) {
      assertEquals(Y, r * COLS, source.getRow(r, null), 0, COLS);
    }
  }

  @Test
  public void testCrop() {
    PlanarYUVLuminanceSource source =
        new PlanarYUVLuminanceSource(YUV, COLS, ROWS, 1, 1, COLS-2, ROWS-2, false);
    for (int r = 0; r < ROWS-2; r++) {
      assertEquals(Y, (r + 1) * COLS + 1, source.getRow(r, null), 0, COLS-2);
    }
  }

  private static void assertEquals(byte[] expected, int expectedFrom,
                                   byte[] actual, int actualFrom,
                                   int length) {
    for (int i = 0; i < length; i++) {
      assertEquals(expected[expectedFrom + i], actual[actualFrom + i]);
    }
  }

}

Add simple test to try codecov.io

Add simple test to try codecov.io


package pl.ciruk.blog.jitest;

import com.google.common.base.Stopwatch;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

public class EmptyLoopTest {
    @Test(timeout = 100_000L)
    public void shouldEliminateEmptyIntLoop() throws Exception {
        for (int i = 0; i < 100; i++) {
            runAndMeasureTime(this::intLoop);
        }
    }

    @Test(timeout = 100_000L)
    public void shouldEliminateEmptyIntToLongLoop() throws Exception {
        for (int i = 0; i < 100; i++) {
            runAndMeasureTime(this::intToLongLoop);
        }
    }

    @Test(timeout = 100_000L)
    public void shouldEliminateEmptyLongLoop() throws Exception {
        for (int i = 0; i < 100; i++) {
            runAndMeasureTime(this::longLoop);
        }
    }

    private void intLoop() {
        for (int i = 0; i < 20_000_000; i++) {

        }
    }

    private void intToLongLoop() {
        for (int i = 0; i < 2_000_000_000L; i++) {
            // no-op
        }
    }

    private void longLoop() {
        for (long i = 0; i < 2_000_000_000L; i++) {
            // no-op
        }
    }

    private void runAndMeasureTime(Runnable runnable) {
        Stopwatch stopwatch = Stopwatch.createStarted();
        runnable.run();
        stopwatch.stop();
        System.out.printf("%d ms%n", stopwatch.elapsed(TimeUnit.MILLISECONDS));
    }
}

Verify JIT behaviour on empty loops

Verify JIT behaviour on empty loops


package fr.treeptik.cloudunit.dto;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by nicolas on 25/08/2014.
 */
final public class LogLine {

    private final String source;
    private final String message;

    public LogLine(String source, String message) {
        if (source == null) {
            throw new IllegalArgumentException("Source cannot be null");
        }
        if (message == null) {
            throw new IllegalArgumentException("Message cannot be null");
        }
        this.message = message;
        if (source != null && source.contains("/")) {
            this.source = source.substring(source.lastIndexOf("/") + 1);
        } else {
            this.source = source;
        }
    }

    public String getMessage() {
        return message;
    }

    public String getSource() {
        return source;
    }

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

        LogLine logLine = (LogLine) o;

        if (!source.equals(logLine.source)) return false;
        return message.equals(logLine.message);

    }

    @Override
    public int hashCode() {
        int result = source.hashCode();
        result = 31 * result + message.hashCode();
        return result;
    }
}

Remove infinite testCase + introduce new log pattern inherited from Docker 1.9


package com.expidev.gcmapp.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.expidev.gcmapp.sql.TableNames;
import com.expidev.gcmapp.utils.DatabaseOpenHelper;

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

/**
 * Created by William.Randall on 1/21/2015.
 */
public class MinistriesDao
{
    private final String TAG = getClass().getSimpleName();

    private final SQLiteOpenHelper databaseHelper;

    private static final Object instanceLock = new Object();
    private static MinistriesDao instance;

    private MinistriesDao(final Context context)
    {
        this.databaseHelper = new DatabaseOpenHelper(context);
    }

    public static MinistriesDao getInstance(Context context)
    {
        if(instance == null)
        {
            synchronized(instanceLock)
            {
                instance = new MinistriesDao(context.getApplicationContext());
            }
        }

        return instance;
    }

    public Cursor retrieveAssociatedMinistriesCursor()
    {
        final SQLiteDatabase database = databaseHelper.getReadableDatabase();
        try
        {
            return database.query(TableNames.ASSOCIATED_MINISTRIES.getTableName(), null, null, null, null, null, null);
        }
        catch(Exception e)
        {
            Log.e(TAG, "Failed to retrieve associated ministries: " + e.getMessage());
        }

        return null;
    }

    public List<String> retrieveAssociatedMinistries()
    {
        Cursor cursor = null;

        try
        {
            cursor = retrieveAssociatedMinistriesCursor();

            if(cursor != null && cursor.getCount() > 0)
            {
                List<String> associatedMinistries = new ArrayList<String>(cursor.getCount());

                cursor.moveToFirst();
                for(int i = 0; i < cursor.getCount(); i++)
                {
                    associatedMinistries.add(cursor.getString(cursor.getColumnIndex("name")));
                }

                return associatedMinistries;
            }
        }
        finally
        {
            if(cursor != null)
            {
                cursor.close();
            }
        }

        return null;
    }
}

Create dao for associated ministries

Create dao for associated ministries


package ch.rasc.eds.starter.config;

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.MimeMappings;
import org.springframework.context.annotation.Configuration;

@Configuration
public class WebFontMimeMapper implements EmbeddedServletContainerCustomizer {

	@Override
	public void customize(ConfigurableEmbeddedServletContainer container) {
		MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT);
		mappings.add("svg", "image/svg+xml");
		mappings.add("eot", "application/vnd.ms-fontobject");
		mappings.add("woff", "application/font-woff");
		mappings.add("woff2", "application/font-woff2");
		mappings.add("ttf", "application/font-sfnt");
		mappings.add("otf", "application/font-sfnt");
		container.setMimeMappings(mappings);
	}
}

Add a mime mapper for webfonts

Add a mime mapper for webfonts


package gr.iti.mklab.simmo.core.annotations;

import gr.iti.mklab.simmo.core.Annotation;

public class SummaryScore implements Annotation {

	 /** The prior of the item */
    private double popularityScore = 0;

	 /** The prior of the item */
    private double priorScore = 0;

	 /** The divRank score of the item */
    private double pageRankScore = 0;

	 /** The divRank score of the item */
    private double divRankScore = 0;

    public SummaryScore() {

    }

    public SummaryScore(double popularityScore, double priorScore, double pageRankScore, double divRankScore) {
    	this.popularityScore = popularityScore;
    	this.priorScore = priorScore;
    	this.pageRankScore = pageRankScore;
    	this.divRankScore = divRankScore;
    }

	public double getPriorScore() {
		return priorScore;
	}

	public void setPriorScore(double priorScore) {
		this.priorScore = priorScore;
	}

	public double getPageRankScore() {
		return pageRankScore;
	}

	public void setPageRankScore(double pageRankScore) {
		this.pageRankScore = pageRankScore;
	}

	public double getDivRankScore() {
		return divRankScore;
	}

	public void setDivRankScore(double divRankScore) {
		this.divRankScore = divRankScore;
	}

	public double getPopularityScore() {
		return popularityScore;
	}

	public void setPopularityScore(double popularityScore) {
		this.popularityScore = popularityScore;
	}

}

Add annotation for summarization scores

Add annotation for summarization scores


package net.sf.jabref.model.entry;

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

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static org.junit.Assert.*;

public class IEEETranEntryTypesTest {

    @Test
    public void ctlTypeContainsYesNoFields() {
        List<String> ctlFields = IEEETranEntryTypes.IEEETRANBSTCTL.getAllFields();
        List<String> ynFields = Arrays.asList(IEEETranEntryTypes.IEEETRANBSTCTL_YES_NO_FIELDS);

        Assert.assertTrue(ctlFields.containsAll(ynFields));
    }

    @Test
    public void ctlTypeContainsNumericFields() {
        List<String> ctlFields = IEEETranEntryTypes.IEEETRANBSTCTL.getAllFields();
        List<String> numericFields = Arrays.asList(IEEETranEntryTypes.IEEETRANBSTCTL_NUMERIC_FIELDS);

        Assert.assertTrue(ctlFields.containsAll(numericFields));
    }

}

Add test for IEEETranBstCtl type fields

Add test for IEEETranBstCtl type fields


import java.io.*;
import java.util.*;

public class harshitmalik03_Word_Break{

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

Add Word Break Problem in Java.

Add Word Break Problem in Java.


package net.imagej.ops.viewOp;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ExtendZero;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.type.numeric.NumericType;
import net.imglib2.view.ExtendedRandomAccessibleInterval;
import net.imglib2.view.Views;

import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.ExtendZero.class, name = ViewOps.ExtendZero.NAME)
public class DefaultExtendZero<T extends NumericType<T>, F extends RandomAccessibleInterval<T>>
		extends AbstractView<F, ExtendedRandomAccessibleInterval<T, F>>
		implements ExtendZero<F, ExtendedRandomAccessibleInterval<T, F>> {

	@Override
	public ExtendedRandomAccessibleInterval<T, F> compute(F input) {
		return Views.extendZero(input);
	}

}

Add default implementation of ExtendZero interface.


public static void RadixSort(ArrayList<Integer> list) {

        final int NUM_BASE = 10;

        int maximum = 0;

        ArrayList<ArrayList<Integer>> buckets;
        buckets = new ArrayList<ArrayList<Integer>>(NUM_BASE);

        // New buckets are added to the bucket list; one for each digit
        // in the numeral system of the data being sorted.

        for (int ii = 0; ii < NUM_BASE; ii++) {

            buckets.add(new ArrayList<Integer>());
        }

        // Identifying the list item with the most place values.

        for (int ii = 0; ii < list.size(); ii++) {

            if (list.get(ii) > maximum) {

                maximum = list.get(ii);
            }
        }

        // List items are sorted by place value. The place value is
        // multiplied by the numeric base with each pass of the loop.

        for (int power = 1; maximum / power != 0; power *= NUM_BASE) {

            for (int ii = 0; ii < list.size(); ii++) {

                // List items are added to the bucket which corresponds
                // to the place value which they are being sorted by.

                buckets.get(list.get(ii) / power % NUM_BASE)
                        .add(list.get(ii));
            }

            int index = 0;

            for (int ii = 0; ii < buckets.size(); ii++) {

                for (int jj = 0; jj < buckets.get(ii).size(); jj++) {

                    // The buckets, sorted by the current place value
                    // under consideration, have their values written
                    // back to original list, overwriting its previous
                    // contents.

                    list.set(index, buckets.get(ii).get(jj));
                    index++;
                }
            }

            // At the end of each pass of the loop, the contents of the
            // buckets are dumped out.

            for (int ii = 0; ii < buckets.size(); ii++) {

                buckets.get(ii).clear();
            }
        }
    }

Add A Readable Radix Sort

Add A Readable Radix Sort

Implemented In Java


/*
 * Copyright (c) 2010, 2011 The University of Manchester, UK.
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice,
 *   this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 * * Neither the names of The University of Manchester nor the names of its
 *   contributors may be used to endorse or promote products derived from this
 *   software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package uk.org.taverna.server.client;

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

import java.net.URI;
import java.net.URISyntaxException;

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

public class TestServer {

	private static String address;
	private URI uri1;
	private URI uri2;
	private Server server;

	@BeforeClass
	public static void getAddress() {
		address = System.getProperty("T2SERVER");

		if (address == null) {
			throw new RuntimeException(
					"Invalid configuration. Make sure T2SERVER is set.");
		}
	}

	@Before
	public void setup() {
		try {
			uri1 = new URI(address);
			uri2 = new URI(address);
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testConnect() {
		server = Server.connect(uri1);
		Server other = Server.connect(uri2);
		Server third = null;
		try {
			third = Server.connect(address);
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		assertNotNull(server);
		assertSame(server, other);
		assertSame(server, third);
	}
}

Add a minimal test suite for the Server class.

This only tests the connect methods as these are the only methods that do things
that might be incorrect independently of the server. Testing other methods would
be effectively be merely testing the remote server.

The connect methods need to be tested to ensure that two connections to the same
remote server return the same Server object.


// Copyright 2021 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.servlets;

import com.google.gson.Gson;
import com.google.sps.data.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/investments")
public class InvestmentServlet extends HttpServlet {
  List<Investment> usersInvestments = new ArrayList<>();
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    addHardCodedData();
    response.setContentType("text/html;");

    response.getWriter().println(new Gson().toJson(usersInvestments));
  }

  public void addHardCodedData() {
    usersInvestments.add(
        new Investment("Bob", "Chicken Wings", 50, new Date(2020, 12, 26).getTime()));
    usersInvestments.add(new Investment("Jack", "Trump", 25, new Date(2020, 11, 26).getTime()));
    usersInvestments.add(new Investment("Mary", "COVID", 30, new Date(2020, 10, 26).getTime()));
  }
}

Add investment Servlets to sent all users investments to the frontend


package com.github.pedrovgs.app.problem2;

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

import static org.junit.Assert.assertEquals;

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

  private VectorScalarProduct vectorScalarProduct;

  @Before public void setUp() {
    vectorScalarProduct = new VectorScalarProduct();
  }

  @Test(expected = IllegalArgumentException.class)
  public void differentSizeVectorsShouldThrowException() {
    Vector v1 = new Vector(1, 2, 3, 4);
    Vector v2 = new Vector(1, 2);

    vectorScalarProduct.calculateScalarProduct(v1, v2);
  }

  @Test public void shouldReturnZeroIfOneVectorIsFullOfZeros() {
    Vector v1 = new Vector(1, 2, 3, 4);
    Vector v2 = new Vector(0, 0, 0, 0);

    int result = vectorScalarProduct.calculateScalarProduct(v1, v2);

    assertEquals(0, result);
  }

  @Test public void shouldReturnSumOfOneVectorIfOtherIsFullOfOnes() {
    Vector v1 = new Vector(2, 2, 2, 2);
    Vector v2 = new Vector(1, 1, 1, 1);

    int result = vectorScalarProduct.calculateScalarProduct(v1, v2);

    assertEquals(8, result);
  }

  @Test public void shouldTakeIntoAccountNegativeElements() {
    Vector v1 = new Vector(2, 2, 2, 2);
    Vector v2 = new Vector(-1, 1, -1, -1);

    int result = vectorScalarProduct.calculateScalarProduct(v1, v2);

    assertEquals(-2, result);
  }
}

Add tests for problem 2.

Add tests for problem 2.


package net.kencochrane.raven.jul;

import net.kencochrane.raven.SentryStub;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.logging.Logger;

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

public class SentryHandlerIT {
    private static final Logger logger = Logger.getLogger(SentryHandlerIT.class.getCanonicalName());
    private SentryStub sentryStub;

    @Before
    public void setUp() {
        sentryStub = new SentryStub();
    }

    @After
    public void tearDown() {
        sentryStub.removeEvents();
    }

    @Test
    public void testInfoLog() {
        assertThat(sentryStub.getEventCount(), is(0));
        logger.info("This is a test");
        assertThat(sentryStub.getEventCount(), is(1));
    }
}

Add integration tests for JUL

Add integration tests for JUL


package com.boundary.metrics.vmware;

import io.dropwizard.configuration.ConfigurationFactory;
import io.dropwizard.jackson.Jackson;

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

import javax.validation.Validation;
import javax.validation.Validator;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.google.common.io.Resources;

public class VMWareTestUtils {

	public static VMwarePerfAdapterConfiguration getConfiguration(String resource) throws Exception {

		VMwarePerfAdapterConfiguration configuration = null;
		File validFile = new File(Resources.getResource(resource).toURI());
		System.out.println(resource);

		Validator validator = Validation.buildDefaultValidatorFactory()
				.getValidator();
		ConfigurationFactory<VMwarePerfAdapterConfiguration> factory = new ConfigurationFactory<VMwarePerfAdapterConfiguration>(
				VMwarePerfAdapterConfiguration.class, validator,
				Jackson.newObjectMapper(), "dw");

		try {
			configuration = factory.build(validFile);
		} catch (JsonParseException e) {

			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return configuration;
	}
}

Add utility class loads VMWare adapter configuration file


package com.akiba.cserver;

public interface CServerConstants {

	public final static short OK = 1;
	public final static short END = 2;
	public final static short ERR = 100;
	public final static short MISSING_OR_CORRUPT_ROW_DEF = 99;
	public final static short NON_UNIQUE = 101;
	public final static short FOREIGN_KEY_MISSING= 102;

	public final static int MAX_VERSIONS_PER_TABLE = 65536;
	public final static int MAX_GROUP_DEPTH = 256;
}

package com.akiba.cserver;

public interface CServerConstants {

	public final static short OK = 1;
	public final static short END = 2;
	public final static short ERR = 100;
	public final static short MISSING_OR_CORRUPT_ROW_DEF = 99;
	public final static short NON_UNIQUE = 121;	// copied from mysql include/my_base.h (line 377)
	public final static short FOREIGN_KEY_MISSING= 151; // copied from mysql include/my_base.h (line 405)

	public final static int MAX_VERSIONS_PER_TABLE = 65536;
	public final static int MAX_GROUP_DEPTH = 256;
}

Update the error values generated (and returned over the wire) to match those expected by MySQL.


package com.sensei.search.query;

import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.Filter;
import org.apache.lucene.search.Query;

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

import com.sensei.search.query.filters.FilterConstructor;

public class RangeQueryConstructor extends QueryConstructor
{
  public static final String QUERY_TYPE = "range";

  // "range" : {
  //     "age" : {
  //         "from" : 10,
  //         "to" : 20,
  //         "boost" : 2.0,
  //         "_noOptimize" : false
  //     }
  // },

  @Override
  public Query constructQuery(JSONObject jsonQuery) throws JSONException
  {
    FilterConstructor filterConstructor = FilterConstructor.getFilterConstructor(QUERY_TYPE);
    Filter filter = null;
    try
    {
      filter = filterConstructor.constructFilter(jsonQuery);
    }
    catch(Exception e)
    {
      throw new JSONException(e);
    }
    ConstantScoreQuery query = new ConstantScoreQuery(filter);
    query.setBoost((float)jsonQuery.getJSONObject((String)jsonQuery.keys().next()).optDouble("boost", 1.0));
    return query;
  }
}

Add missing file for range query constructor.


package info.freelibrary.jiiify.util;

import java.awt.Dimension;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import info.freelibrary.jiiify.iiif.IIIFException;
import info.freelibrary.jiiify.iiif.ImageRequest;
import info.freelibrary.util.PairtreeRoot;

import au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.CSVWriter;

public class ReportUtils {

    private static final File CSV_FILE = new File("input.csv");

    private static final File CSV_OUT = new File("output.csv");

    private static final Logger LOGGER = LoggerFactory.getLogger(ReportUtils.class);

    private static int myFoundCount;

    private static int myNotFoundCount;

    public static final void main(final String[] args) throws IOException {
        final CSVReader csvReader = new CSVReader(new FileReader(CSV_FILE));
        final PairtreeRoot ptRoot = new PairtreeRoot(new File(args[0]));
        final CSVWriter csvWriter = new CSVWriter(new FileWriter(CSV_OUT));

        csvReader.readAll().forEach(image -> {
            try {
                final File imageFile = new File(image[1]);
                final Dimension dim = ImageUtils.getImageDimension(imageFile);

                myFoundCount = 0;
                myNotFoundCount = 0;

                ImageUtils.getTilePaths("/iiif", image[0], 1024, dim.width, dim.height).forEach(path -> {
                    try {
                        final ImageRequest request = new ImageRequest(path);

                        if (request.hasCachedFile(ptRoot)) {
                            myFoundCount++;
                        } else {
                            myNotFoundCount++;
                        }
                    } catch (final IIIFException | IOException details) {
                        try {
                            csvWriter.close();
                            csvReader.close();
                        } catch (final IOException ignorable) {
                            LOGGER.error(ignorable.getMessage(), ignorable);
                        }

                        throw new RuntimeException(details);
                    }
                });

                csvWriter.writeNext(new String[] { imageFile.getAbsolutePath(), Integer.toString(myFoundCount),
                    Integer.toString(myNotFoundCount) });
            } catch (final IOException details) {
                try {
                    csvWriter.close();
                    csvReader.close();
                } catch (final IOException ignorable) {
                    LOGGER.error(ignorable.getMessage(), ignorable);
                }

                throw new RuntimeException(details);
            }
        });

        csvReader.close();
        csvWriter.close();
    }
}

Add csv pairtree file system checker script


/*
 * Copyright (c) 2017 Falko Schumann
 * Released under the terms of the MIT License.
 */

package de.muspellheim.jdbc;

import com.mysql.jdbc.jdbc2.optional.*;
import javafx.application.*;
import javafx.beans.property.*;
import javafx.beans.value.*;
import javafx.collections.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.stage.*;
import javafx.util.*;

import java.sql.*;

public class FXApplication extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        TableView tableView = new TableView();

        MysqlDataSource dataSource = new MysqlConnectionPoolDataSource();
        dataSource.setPort(8889);
        dataSource.setUser("root");
        dataSource.setPassword("root");
        dataSource.setDatabaseName("oshop");

        ObservableList<ObservableList> data = FXCollections.observableArrayList();
        try (Connection connection = dataSource.getConnection()) {
            String sql = "SELECT artikel_id AS 'Artikel-ID', bezeichnung AS 'Bezeichnung', CONCAT(FORMAT(einzelpreis, 2, 'de_DE'), ' ', waehrung) AS 'Einzelpreis' FROM artikel WHERE deleted = 0";
            ResultSet resultSet = connection.createStatement().executeQuery(sql);

            for (int i = 0; i < resultSet.getMetaData().getColumnCount(); i++) {
                final int j = i;
                TableColumn col = new TableColumn(resultSet.getMetaData().getColumnLabel(i + 1));
                col.setCellValueFactory((Callback<TableColumn.CellDataFeatures<ObservableList, String>, ObservableValue<String>>) param -> new SimpleStringProperty(param.getValue().get(j).toString()));
                tableView.getColumns().addAll(col);
            }

            while (resultSet.next()) {
                ObservableList<String> row = FXCollections.observableArrayList();
                for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                    row.add(resultSet.getString(i));
                }
                data.add(row);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
        tableView.setItems(data);

        Scene scene = new Scene(tableView);

        stage.setTitle("Demo with table kunde");
        stage.setScene(scene);
        stage.show();
    }

}

Create dynamic table with result set

Create dynamic table with result set


package com.continuuity.passport.passportClient;

import com.continuuity.common.utils.PortDetector;
import com.continuuity.passport.http.client.AccountProvider;
import com.continuuity.passport.http.client.PassportClient;
import com.continuuity.passport.server.MockServer;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.junit.Assert.assertTrue;

/**
 *
 */
public class TestPassportClient {

  private static MockServer server ;
  private static int port;

  @BeforeClass
  public static void startServer() throws Exception {
    port = PortDetector.findFreePort();
    server = new MockServer(port);
    System.out.println("Starting server");
    server.start();
    Thread.sleep(1000);
    assertTrue(server.isStarted());
    Map<String,String> accountHash=  new HashMap<String, String>();
    accountHash.put("email_id", "john@smith.com");
    accountHash.put("first_name", "john");
    accountHash.put("last_name", "smith");
    accountHash.put("company", "continuuity");

    addAccount(accountHash);
    System.out.println("Added account");
 }
  @Test
  public void testValidAccount(){
    PassportClient client = new PassportClient();
    System.out.println("Trying to get account");
    AccountProvider accountProvider = client.getAccount("http","localhost",port,"apiKey1");
    System.out.println("Got an account");

    assert (accountProvider !=null);
    System.out.println(accountProvider.getAccountId());
    assert ("1".equals(accountProvider.getAccountId()));
    System.out.println("Tested");
  }

  @Test(expected = RuntimeException.class)
  public void testInvalidAccount() {
    PassportClient client = new PassportClient();
    AccountProvider accountProvider = client.getAccount("http","localhost",port,"apiKey100");

  }

  @AfterClass
  public static void stopServer() throws Exception {
     server.stop();
     Thread.sleep(1000);
  }

  private static void addAccount(Map<String,String> account) throws IOException {
    Gson gson =new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();

    HttpPost post = new HttpPost(String.format("http://localhost:%d/passport/v1/account",port));
    StringEntity entity =  new StringEntity(gson.toJson(account));
    entity.setContentType("application/json");
    post.setEntity(entity);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(post);

    assert(response.getStatusLine().getStatusCode() == 200);
  }

}

Add Test cases for passport client

Add Test cases for passport client


package org.jdesktop.beans.editors;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * A demo program to showcase {@link PaintPicker}.
 *
 * @author Karl Schaefer
 */
@SuppressWarnings("all")
public class PaintPickerDemo extends JFrame {
    /**
     * {@inheritDoc}
     */
    @Override
    protected void frameInit() {
        super.frameInit();

        setTitle("PaintPicker Demo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new PaintPicker());

        pack();
    }

    /**
     * Demo entry point.
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new PaintPickerDemo().setVisible(true);
            }
        });
    }
}

Add demo for paint picker.

Add demo for paint picker.

git-svn-id: 9c6ef37dfd7eaa5a3748af7ba0f8d9e7b67c2a4c@3853 1312f61e-266d-0410-97fa-c3b71232c9ac


package com.easternedgerobotics.rov.io;

import com.easternedgerobotics.rov.value.MotionPowerValue;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.pmw.tinylog.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.Preferences;

public final class MotionPowerProfile {
    /**
     * The directory which contains the power profiles.
     */
    private final Preferences profileHome;

    /**
     * A copy of power profiles to exist in RAM.
     */
    private final Map<Integer, MotionPowerValue> profiles = new HashMap<>();

    /**
     * Create a power profile loader/ setter which works in the specified directory.
     *
     * @param profile the preferences directory.
     */
    public MotionPowerProfile(final String profile) {
        this.profileHome = Preferences.userRoot().node(profile);
    }

    /**
     * Get the latest MotionPowerValue associated with the index.
     * Fetches from disk if not loaded.
     *
     * @param index the power profile index.
     * @return MotionPowerValue
     */
    public MotionPowerValue get(final int index) {
        return profiles.computeIfAbsent(index, i -> {
            final String profileName = String.format("profile-%d", i);
            final String profileStr = profileHome.get(profileName, "DEFAULT");
            if (profileStr.equals("DEFAULT")) {
                Logger.warn("The profile {} does not exist.", profileName);
                return new MotionPowerValue();
            }
            try {
                return new ObjectMapper().readValue(profileStr, MotionPowerValue.class);
            } catch (final IOException e) {
                Logger.warn("The profile {} could not be parsed from '{}': {}", profileName, profileStr, e);
                return new MotionPowerValue();
            }
        });
    }

    /**
     * Update the MotionPowerValue profile for a given index and write this value to disk.
     *
     * @param index the power profile index.
     * @param profile MotionPowerValue to be saved to disk.
     */
    public void set(final int index, final MotionPowerValue profile) {
        profiles.put(index, profile);
        final String profileName = String.format("profile-%d", index);
        try {
            profileHome.put(profileName, new ObjectMapper().writeValueAsString(profile));
        } catch (final IOException e) {
            Logger.warn("The profile {} could not be saved to {}: {}", profile, profileName, e);
        }
    }
}

Load and save motion power values to disk


package pabix.chickens.una;

import android.app.Application;
import android.content.Context;

import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;

/**
 * Created by JunHyeok on 2016. 10. 6..
 */

public class UnaApplication extends Application {

    public static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        FacebookSdk.sdkInitialize(getApplicationContext());
        AppEventsLogger.activateApp(this);
        context = this;
    }

    public static Context getContext() {
        return context;
    }
}

Add Application class for manage Context


package sizebay.catalog.client.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;

@Data
@Accessors(chain = true)
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserProfileProduct implements Serializable {

      long id ;
      long profileIdentificationId;
      String brand;
      String category;
      String model;
      String gender;
      int ageGroup;
      String size;
      String sizeStr;

      public static UserProfileProduct empty() {

          UserProfileProduct product = new UserProfileProduct();

          product.setBrand("");
          product.setCategory("");
          product.setModel("");
          product.setGender("");
          product.setAgeGroup(0);
          product.setSize("");
          product.setSizeStr("");

          return product;

      }

}

Create the Profile Product class

Create the Profile Product class


/*
 * 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;
import com.github.pedrovgs.sortingalgorithms.SortingAlgorithmTest;

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

  @Override public SortingAlgorithm getSortingAlgorithm() {
    return new InsertionSort();
  }
}

Add some tests to problem 76

Add some tests to problem 76


package problems;

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

public class SubstringWithConcatenationOfAllWords {
    public List<Integer> findSubstring(String S, String[] L) {
        final List<Integer> out = new ArrayList<Integer>();
        if (S == null || L == null || S.length() == 0 || L.length == 0)
            return out;

        final int len = L[0].length();
        final int N = L.length * len;
        final HashMap<String, Integer> map = new HashMap<String, Integer>();
        HashMap<String, Integer> mapcopy = null;
        for (final String st : L) {
            if (!map.containsKey(st))
                map.put(st, 1);
            else
                map.put(st, map.get(st) + 1);
        }

        for (int i = 0; i < S.length() - N + 1; i++) {
            final String a = S.substring(i, i + len);
            if (!map.containsKey(a))
                continue;
            else {
                mapcopy = new HashMap<String, Integer>(map);
                remove(mapcopy, a);
            }

            for (int j = 1; j < L.length; j++) {
                String t = S.substring(i + j * len, i + (j + 1) * len);
                if (!remove(mapcopy, t))
                    break;
            }
            if (mapcopy.size() == 0)
                out.add(i);
        }
        return out;
    }

    boolean remove(HashMap<String, Integer> map, String s) {
        if (map.containsKey(s)) {
            final int count = map.get(s);
            if (count > 1)
                map.put(s, count - 1);
            else
                map.remove(s);
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        SubstringWithConcatenationOfAllWords sw = new SubstringWithConcatenationOfAllWords();
        String S = "lingmindraboofooowingdingbarrwingmonkeypoundcake";
        String[] L = { "fooo", "barr", "wing", "ding", "wing" };
        System.out.println(sw.findSubstring(S, L));
    }
}

Add Substring with Concatenation of All Words


package uk.ac.ebi.gxa.loader.service;

import org.junit.Test;

/**
 */
public class TestNcdfConversion {
    @Test
    public void testExportExperiment() {
        // Get an experiment from DB/NetCDF
        // run update on it - not it'll rewrite the file
        // make sure all the DB fields are shown in the NetCDF and IDF files properly
        // release the experiment
        // import the experiment
        // make sure all the fields are still the same
    }
}

Test scenario to start with

Test scenario to start with


package com.github.kratorius.cuckoohash;

import junit.framework.TestCase;

import java.util.ArrayList;
import java.util.Random;

/**
 * Tests for the put() method of the Cuckoo hash map.
 */
public class PutTest extends TestCase {
  @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
  public void testNullKey() {
    CuckooHashMap<Character, Boolean> m = new CuckooHashMap<>();

    try {
      m.put(null, true);
      fail("Accepted null key for put()");
    } catch (NullPointerException e) {
      // Expected.
    }
  }

  public void testUpdate() {
    CuckooHashMap<Character, Integer> m = new CuckooHashMap<>();

    m.put('A', 3);
    assertEquals(3, (int) m.get('A'));

    m.put('A', 42);
    assertEquals(42, (int) m.get('A'));
  }

  public void testManyKeys() {
    // Enough to generate a fair amount of rehashes but not too many so that it fits in memory
    // in the default heap size, and also so that it doesn't take too long to execute.
    final int size = 1024 * 128;

    ArrayList<String> keys = new ArrayList<>(size);
    for (int i = 0; i < size; i++) {
      keys.add(String.valueOf("key-" + i));
    }

    CuckooHashMap<String, Integer> m = new CuckooHashMap<>();
    for (int i = 0; i < size; i++) {
      m.put(keys.get(i), i);
      assertEquals(i, (int) m.get(keys.get(i)));
    }

    for (int i = 0; i < size; i++) {
      assertEquals(i, (int) m.get(keys.get(i)));
    }
  }
}

Add more thorough tests for put()

Add more thorough tests for put()


package tests.dynamicObjectModule;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

public class DynamicObjectModuleTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
	}

	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testDynamicObjectModule() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testAddItem() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testAddVirtualCharacter() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testFindItem() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testFindVirtualCharacter() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testGetAllDynamicObjects() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testGetVirtualCharacterPosition() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testKeyGETPressed() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testUpdateItem() {
		fail("Not yet implemented"); // TODO
	}

	@Test
	public void testUpdateVirtualCharacter() {
		fail("Not yet implemented"); // TODO
	}

}

Create test case for DynamicObjectModule.


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

/**
 * Given an integer passed as parameter, can you write a method to return the reverse binary
 * number? The reverse binary number is defined like the number where every 1 in the original
 * number has a 0 in the reversed number and the same with 0 in the original number.
 *
 * For example:
 *
 * Input: 63 = 111111
 * Output: 0
 *
 * Input = 5 = 101
 * Output = 2 = 010
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class ReverseBinaryNumber {

}

Add statement to problem 71

Add statement to problem 71