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

import org.junit.Test;

public class ReportTestITCase extends AbstractTest {

    @Test
    public void readReportlet() {
        selenium.click("css=img[alt=\"Reports\"]");
        selenium.waitForCondition("selenium.isElementPresent(\"//div[@id='tabs']\");", "30000");

        selenium.click("//table/tbody/tr/td[6]/span/span[7]/a");
        selenium.waitForCondition("selenium.isElementPresent("
                + "\"//form/div[2]/div/div/span/div/div[5]/div[2]/span/div[2]/div/a\");", "30000");

        selenium.click("css=img[alt=\"plus icon\"]");
        selenium.waitForCondition("selenium.isElementPresent("
                + "\"//form/div[2]/div/div/div[2]/div[2]/span/select\");", "30000");

        selenium.select("//form/div[2]/div/div/div[2]/div[2]/span/select",
                "label=org.syncope.client.report.UserReportletConf");
        selenium.waitForCondition("selenium.isElementPresent(\"//form/div[2]/div[2]/div/span/div/div/span\")", "30000");

        selenium.click("css=a.w_close");
        selenium.click("css=a.w_close");
    }

    @Test
    public void execute() {
        selenium.click("css=img[alt=\"Reports\"]");

        selenium.waitForCondition("selenium.isElementPresent(\"//div[@id='tabs']\");", "30000");

        selenium.click("//table/tbody/tr/td[6]/span/span[3]/a");

        selenium.waitForCondition("selenium.isTextPresent(\"Operation executed successfully\");", "30000");
    }
}

Test cases added to selenium profile

[SYNCOPE-6] Test cases added to selenium profile

git-svn-id: 51e9c0635e05060c2a7639df764e0b3ebb09013f@1298457 13f79535-47bb-0310-9956-ffa450edef68


package me.haosdent.cgroup.subsystem;

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

public class TestNetPrio {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testGetPrioId() {}

  @Test
  public void testGetIfPrioMap() {}

  @Test
  public void testAddIfPrioMap() {}
}

Add net_prio subsystem test class.

Add net_prio subsystem test class.


package cgeo.geocaching.connector.gc;

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

import cgeo.geocaching.enumerations.StatusCode;

import junit.framework.TestCase;
import org.apache.commons.lang3.StringUtils;

import android.test.suitebuilder.annotation.Suppress;

public class GCLoginTest extends TestCase {

    final GCLogin instance = GCLogin.getInstance();

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        assertThat(instance.login()).isEqualTo(StatusCode.NO_ERROR);
    }

    public static void testHomeLocation() {
        assertThat(StringUtils.isNotBlank(GCLogin.retrieveHomeLocation().toBlocking().value())).isTrue();
    }

    @Suppress // It currently fails on CI
    public void testAvatar() {
        assertThat(instance.downloadAvatar()).isNotNull();
    }

}

package cgeo.geocaching.connector.gc;

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

import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.location.Geopoint;

import junit.framework.TestCase;
import org.apache.commons.lang3.StringUtils;

import android.test.suitebuilder.annotation.Suppress;

public class GCLoginTest extends TestCase {

    private final GCLogin instance = GCLogin.getInstance();

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        assertThat(instance.login()).isEqualTo(StatusCode.NO_ERROR);
    }

    private static String blockingHomeLocation() {
        return GCLogin.retrieveHomeLocation().toBlocking().value();
    }

    public static void testRetrieveHomeLocation() {
        assertThat(StringUtils.isNotBlank(blockingHomeLocation())).isTrue();
    }

    public static void testValidHomeLocation() {
        assertThat(new Geopoint(blockingHomeLocation())).isInstanceOf(Geopoint.class);
    }

    @Suppress // It currently fails on CI
    public void testAvatar() {
        assertThat(instance.downloadAvatar()).isNotNull();
    }

}

Add a test to confirm that the home location contains valid coordinates

Related to #6042.


package reactor.kafka.support;

import org.apache.kafka.common.serialization.Serializer;
import org.apache.kafka.common.serialization.StringSerializer;
import reactor.pipe.key.Key;

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

public class KeySerializer implements Serializer<Key> {

  private final StringSerializer stringSerializer;

  public KeySerializer() {
    this.stringSerializer = new StringSerializer();
  }

  @Override
  public void configure(Map<String, ?> map, boolean b) {
    stringSerializer.configure(map, b);
  }

  @Override
  public byte[] serialize(String topic, Key key) {
    return stringSerializer.serialize(topic,
                                      String.join(",",
                                                  Arrays.stream(key.getObjects())
                                                        .map(Object::toString)
                                                        .collect(Collectors.toList())));
  }

  @Override
  public void close() {
  }
}

Add a serializer for key

Add a serializer for key


package jetbrains.jetpad.base;

public class Interval {
  private int myLowerBound;
  private int myUpperBound;

  public Interval(int lowerBound, int upperBound) {
    if (lowerBound > upperBound) throw new IllegalArgumentException("Lower bound is greater than upper: lower bound=" + lowerBound + ", upper bound=" + upperBound);
    myLowerBound = lowerBound;
    myUpperBound = upperBound;
  }

  public int getLowerBound() {
    return myLowerBound;
  }

  public int getUpperBound() {
    return myUpperBound;
  }

  @Override
  public String toString() {
    return "[" + myLowerBound + ", " + myUpperBound + "]";
  }
}

Use custom int pair instead of guava range in persistence


package com.google.bitcoin.examples;

import com.google.bitcoin.core.*;
import com.google.bitcoin.kits.WalletAppKit;
import com.google.bitcoin.params.RegTestParams;
import com.google.bitcoin.utils.BriefLogFormatter;
import com.google.bitcoin.utils.Threading;

import java.io.File;
import java.math.BigInteger;

/**
 * This is a little test app that waits for a coin on a local regtest node, then  generates two transactions that double
 * spend the same output and sends them. It's useful for testing double spend codepaths but is otherwise not something
 * you would normally want to do.
 */
public class DoubleSpend {
    public static void main(String[] args) throws Exception {
        BriefLogFormatter.init();
        final RegTestParams params = RegTestParams.get();
        WalletAppKit kit = new WalletAppKit(params, new File("."), "doublespend");
        kit.connectToLocalHost();
        kit.setAutoSave(false);
        kit.startAsync();
        kit.awaitRunning();

        System.out.println(kit.wallet());

        kit.wallet().getBalanceFuture(Utils.COIN, Wallet.BalanceType.AVAILABLE).get();
        Transaction tx1 = kit.wallet().createSend(new Address(params, "muYPFNCv7KQEG2ZLM7Z3y96kJnNyXJ53wm"), Utils.CENT);
        Transaction tx2 = kit.wallet().createSend(new Address(params, "muYPFNCv7KQEG2ZLM7Z3y96kJnNyXJ53wm"), Utils.CENT.add(BigInteger.TEN));
        final Peer peer = kit.peerGroup().getConnectedPeers().get(0);
        peer.addEventListener(new AbstractPeerEventListener() {
            @Override
            public Message onPreMessageReceived(Peer peer, Message m) {
                System.err.println("Got a message!" + m.getClass().getSimpleName() + ": " + m);
                return m;
            }
        }, Threading.SAME_THREAD);
        peer.sendMessage(tx1);
        peer.sendMessage(tx2);

        Thread.sleep(5000);
        kit.stopAsync();
        kit.awaitTerminated();
    }
}

Add a double spending test program

Add a double spending test program


package de.codecentric.centerdevice.sample;

import de.codecentric.centerdevice.MenuToolkit;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.control.SeparatorMenuItem;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

/**
 * Skeleton for Standard Macintosh Application
 * See: "OS X Human Interface Guidelines"
 */
public class StandardMacApp extends Application {
    static final String appName = "Standard";
    static final String mainWindowTitle = "Main";

    @Override
    public void start(Stage primaryStage) throws Exception {

        StackPane root = new StackPane();
        primaryStage.setScene(new Scene(root, 300, 200));
        primaryStage.requestFocus();
        primaryStage.setTitle(mainWindowTitle);
        primaryStage.show();

        MenuToolkit tk = MenuToolkit.toolkit();

        MenuBar bar = new MenuBar();

        // Application Menu
        // TBD services, show/hide, etc.
        Menu appMenu = new Menu(appName);   // Name for appMenu can't be set at Runtime
        MenuItem aboutItem = new MenuItem("About");
        MenuItem prefsItem = new MenuItem("Preferences...");
        MenuItem quitItem = tk.createQuitMenuItem(appName);
        appMenu.getItems().addAll(aboutItem,
                                    new SeparatorMenuItem(),
                                    prefsItem,
                                    new SeparatorMenuItem(),
                                    quitItem);

        // File Menu (items TBD)
        Menu fileMenu = new Menu("File");
        MenuItem newItem = new MenuItem("New...");
        fileMenu.getItems().addAll(newItem, new MenuItem("TBD"));

        // Edit (items TBD)
        Menu editMenu = new Menu("Edit");
        editMenu.getItems().addAll(new MenuItem("TBD"));

        // Format (items TBD)
        Menu formatMenu = new Menu("Format");
        formatMenu.getItems().addAll(new MenuItem("TBD"));

        // View Menu (items TBD)
        Menu viewMenu = new Menu("View");
        viewMenu.getItems().addAll(new MenuItem("TBD"));

        // Window Menu
        // TBD standard window menu items
        Menu windowMenu = new Menu("Window");
        MenuItem mainWinItem = new MenuItem(mainWindowTitle);
        windowMenu.getItems().addAll(new MenuItem("TBD"),
                                new SeparatorMenuItem(),
                                mainWinItem);

        // Help Menu (items TBD)
        Menu helpMenu = new Menu("Help");
        helpMenu.getItems().addAll(new MenuItem("TBD"));

        bar.getMenus().addAll(appMenu,
                                fileMenu,
                                editMenu,
                                formatMenu,
                                viewMenu,
                                windowMenu,
                                helpMenu);

        tk.setMenuBar(primaryStage, bar);
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Add a sample with Standard Mac menus

Add a sample with Standard Mac menus

Starting point only, most items are TBD.


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

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;

import javax.inject.Named;
import javax.inject.Singleton;

import org.junit.jupiter.api.Test;
import org.xwiki.component.annotation.Component;
import org.xwiki.resource.CreateResourceReferenceException;
import org.xwiki.resource.ResourceType;
import org.xwiki.resource.UnsupportedResourceReferenceException;
import org.xwiki.test.junit5.mockito.ComponentTest;
import org.xwiki.test.junit5.mockito.InjectMockComponents;
import org.xwiki.url.ExtendedURL;

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

/**
 * @version $Id$
 */
@ComponentTest
public class AbstractParentResourceReferenceResolverTest
{
    @Component
    @Named("test")
    @Singleton
    public static class TestParentResourceReferenceResolver extends AbstractParentResourceReferenceResolver
    {

    }

    @InjectMockComponents
    private TestParentResourceReferenceResolver resolver;

    @Test
    public void resolve()
        throws MalformedURLException, CreateResourceReferenceException, UnsupportedResourceReferenceException
    {
        ExtendedURL extendedURL = new ExtendedURL(
            new URL("http://host/xwiki/test/child/1/2/3?key1=value11&key1=value12&key2=value2"), "xwiki/test");
        ResourceType type = new ResourceType("test");

        ParentResourceReference reference = this.resolver.resolve(extendedURL, type, null);

        assertSame(type, reference.getType());
        assertEquals("child", reference.getChild());
        assertEquals("child/1/2/3", reference.getRootPath());
        assertEquals(Arrays.asList("1", "2", "3"), reference.getPathSegments());
        assertEquals(2, reference.getParameters().size());
        assertEquals(Arrays.asList("value11", "value12"), reference.getParameters().get("key1"));
        assertEquals(Arrays.asList("value2"), reference.getParameters().get("key2"));
    }
}

Add test (really this time)

[misc] Add test (really this time)


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

/**
 *
 * This is a list container for jstl.
 *
 * @author Gautier Koscielny (EMBL-EBI) <koscieln@ebi.ac.uk>
 *  @since February 2012
 */

import java.util.List;

import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name="listContainer")
public class ListContainer<X> {

	private int count;
	private List<X> results;

	public ListContainer() {}

	public ListContainer(List<X> results) {
		this.results = results;
		this.count = results.size();
	}

	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}

	@XmlElement(name="results")
	public List<X> getResults() {
		return results;
	}
	public void setResults(List<X> results) {
		this.results = results;
	}
}

Move PhenotypeArchive to trunk Refactored to use generics. Use generics. lightweight object representation for HTML / JSON / XML export. List container. It is used for HTML rendering with jstl.


package com.cinnamon.gfx;

/**
 *

 *     Listener to be called whenever the {@link ImageFactory}'s drawing data
 *     may need to be updated.
 *

 *
 *
 */
public interface OnDrawVisibilityChangeListener
{
    /**
     *
Called when there's been a change that affects the
     * {@link ImageFactory}'s drawing data.

     */
    void onChange();
}

Revert "Changed name to past tense"

Revert "Changed name to past tense"

This reverts commit e6182cbd12ee45449b77bde0ee414787da3362b8.


package seedu.task.logic.commands;

import java.util.HashMap;
import java.util.Optional;

public class CommandInput {
    private String command;
    private String mainInput;
    private HashMap<String, String> keywordArguments;

    public CommandInput(String command, String mainInput, HashMap<String, String> keywordArguments) {
        this.command = command;
        this.mainInput = mainInput;
        this.keywordArguments = new HashMap<String, String>(keywordArguments);
    }

    public String getCommand() {
        return command;
    }

    public String getMainInput() {
        return mainInput;
    }

    public Optional<String> getKeywordArgument(String keyword) {
        if (keywordArguments.containsKey(keyword)) {
            return Optional.of(keywordArguments.get(keyword));
        } else {
            return Optional.empty();
        }
    }
}

Create class to encapsulate Command inputs


package org.adaptlab.chpir.android.survey.Models;

import java.util.Date;

import com.activeandroid.Model;
import com.activeandroid.annotation.Column;

public class EventLog extends Model {
    private final static String TAG = "EVENT";

    public static enum EventType {
        SENT_SURVEY
    }

    @Column(name = "EventType")
    private EventType mEventType;
    @Column(name = "SurveyIdentifier")
    private String mSurveyIdentifier;
    @Column(name = "Instrument")
    private Instrument mInstrument;
    @Column(name = "Timestamp")
    private Date mTimestamp;

    public EventLog(EventType eventType) {
        super();
        mEventType = eventType;
        mTimestamp = new Date();
    }

    public void setInstrument(Instrument instrument) {
        mInstrument = instrument;
    }

    public void setSurveyIdentifier(String identifier) {
        mSurveyIdentifier = identifier;
    }

    public Instrument getInstrument() {
        return mInstrument;
    }

    public String getSurveyIdentifier() {
        return mSurveyIdentifier;
    }

    public Date getTimestamp() {
        return mTimestamp;
    }

    public String getLogMessage() {
        if (mEventType == EventType.SENT_SURVEY) {
            // TODO: Internationalize
            return "Sent " + mInstrument.getTitle() + " for " + mSurveyIdentifier;
        }

        return "";
    }
}

Add basic event log model

Add basic event log model


package org.arp.javautil.datastore;

final class BdbStoreTest {
    public static void main(String[] args) throws Exception {
        DataStore<String, String> store = DataStoreFactory.newCacheStore();
//        Store<String, String> store = StoreFactory.getPermanentStore("foo");
//        Store<String, String> bar = StoreFactory.getPermanentStore("bar");

        if (store.containsKey("foo")) {
            System.out.println("Found 'foo': " + store.get("foo"));
        } else {
            System.out.println("Couldn't find 'foo'...adding 'foo'");
            store.put("foo", "FOO");
        }

//        if (bar.containsKey("bar")) {
//            System.out.println("Found 'bar': " + bar.get("bar"));
//        } else {
//            bar.put("bar", "BAR");
//        }

        store.shutdown();
    }
}

Test class for BerkeleyDB implementation of persistent/cache data stores. See PROTEMPA-64 in JIRA.


package org.osmdroid.google.wrapper.v2;

import com.google.android.gms.maps.model.LatLng;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IProjection;
import org.osmdroid.util.GeoPoint;

import android.graphics.Point;

public class Projection implements IProjection {

	private final com.google.android.gms.maps.Projection mProjection;

	private final Point mPoint = new Point();

	public Projection(final com.google.android.gms.maps.Projection aProjection) {
		mProjection = aProjection;
	}

	@Override
	public Point toPixels(final IGeoPoint in, final Point out) {
		final LatLng latLng = new LatLng(in.getLatitudeE6() / 1E6, in.getLongitudeE6() / 1E6);
		return mProjection.toScreenLocation(latLng);
	}

	@Override
	public IGeoPoint fromPixels(final int x, final int y) {
		mPoint.x = x;
		mPoint.y = y;
		final LatLng latLng = mProjection.fromScreenLocation(mPoint);
		return new GeoPoint(latLng.latitude, latLng.longitude);
	}

	@Override
	public float metersToEquatorPixels(final float meters) {
		return 0; // TODO implement this
	}
}

package org.osmdroid.google.wrapper.v2;

import com.google.android.gms.maps.model.LatLng;
import org.osmdroid.api.IGeoPoint;
import org.osmdroid.api.IProjection;
import org.osmdroid.util.GeoPoint;

import android.graphics.Point;

public class Projection implements IProjection {

	private final com.google.android.gms.maps.Projection mProjection;

	private final Point mPoint = new Point();

	public Projection(final com.google.android.gms.maps.Projection aProjection) {
		mProjection = aProjection;
	}

	@Override
	public Point toPixels(final IGeoPoint in, final Point out) {
		final LatLng latLng = new LatLng(in.getLatitudeE6() / 1E6, in.getLongitudeE6() / 1E6);
		final Point point = mProjection.toScreenLocation(latLng);
		if (out != null) {
			out.x = point.x;
			out.y = point.y;
		}
		return point;
	}

	@Override
	public IGeoPoint fromPixels(final int x, final int y) {
		mPoint.x = x;
		mPoint.y = y;
		final LatLng latLng = mProjection.fromScreenLocation(mPoint);
		return new GeoPoint(latLng.latitude, latLng.longitude);
	}

	@Override
	public float metersToEquatorPixels(final float meters) {
		return 0; // TODO implement this
	}
}

Copy result to out parameter

Copy result to out parameter


package bugIdeas;

import java.util.Hashtable;
import java.util.Properties;

public class Ideas_2009_10_05 {

	public void propertiesCantContainNull(Properties p) {
		p.put("a", null);
		p.put(null, "a");
		p.get(null);
		p.getProperty(null);
		p.getProperty(null, "foo");
		p.setProperty(null, "a");
		p.setProperty("a", null);

	}

	public void hashtablesCantContainNull(Hashtable h) {
		h.put("a", null);
		h.put(null, "a");
		h.get(null);
		h.contains(null);
		h.containsKey(null);
		h.containsValue(null);
		h.remove(null);

	}
}

Check that we are doing the right thing for hashtable and properties nullness

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@11578 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


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

package com.pushtechnology.diffusion.transform.messaging.send;

import java.util.concurrent.CompletableFuture;

import com.pushtechnology.diffusion.client.callbacks.Stream;
import com.pushtechnology.diffusion.client.session.SessionId;
import com.pushtechnology.diffusion.transform.transformer.TransformationException;

/**
 * A sender of values as request. May transform them before sending. May
 * transform the response received.
 *
 * @param <T> the type of response understood by Diffusion
 * @param <U> the type of request
 * @param <V> the type of response
 * @author Push Technology Limited
 */
public interface RequestToSessionSender<T, U, V> {

    /**
     * Send a request.
     *
     * @param sessionId the recipient of the request
     * @param path the path to send the request to
     * @param request the request
     *
     * @return the response
     */
    CompletableFuture<V> sendRequest(SessionId sessionId, String path, U request) throws TransformationException;

    /**
     * Send a request to many sessions.
     *
     * @param sessionFilter the recipient of the request
     * @param path the path to send the request to
     * @param request the request
     * @param callback the callback that receives the responses
     *
     * @return the number of requests sent
     * @throws TransformationException if the request cannot be transformed
     */
    CompletableFuture<Integer> sendRequest(
        String sessionFilter,
        String path,
        U request,
        TransformedFilterCallback<T, V> callback) throws TransformationException;

    /**
     * The callback for transformed responses.
     *
     * @param <R> the type of response understood by Diffusion
     * @param <S> the type of response
     */
    interface TransformedFilterCallback<R, S> extends Stream {
        /**
         * Called when a response has been received.
         *
         * @param sessionId sessionId of the session that sent the response
         * @param response transformed response object
         */
        void onResponse(SessionId sessionId, S response);

        /**
         * Called when a response from a session results in an error.
         *
         * @param sessionId sessionId of the session in error
         * @param t the throwable reason of the response error
         */
        void onResponseError(SessionId sessionId, Throwable t);

        /**
         * Called when a response has been received but cannot be transformed.
         *
         * @param sessionId sessionId of the session that sent the response
         * @param response untransformed response object
         * @param e the transformation exception
         */
        void onTransformationException(SessionId sessionId, R response, TransformationException e);
    }
}

Add an interface for sending requests to sessions.


package com.bloatit.common;

import org.apache.log4j.Logger;

// TRACE
// DEBUG
// INFO
// WARN  -> not correct behavior but non so serious
// ERROR -> should be reported to the admin
// FATAL -> should be reported to the admin

public class Log {
    public static Logger framework() {
        return Logger.getLogger("com.bloatit.framework");
    }

    public static Logger data() {
        return Logger.getLogger("com.bloatit.model.data");
    }
}

Add a class to get logger

Add a class to get logger


package tests;

import junit.framework.TestCase;
import api.SimpleAPI;

public class TestSimpleAPI extends TestCase {
	/**
	 * Test method for {@link api.SimpleAPI#add(int, int)}.
	 */
	public void testAdd() {
		int a = SimpleAPI.add(2, 3);
		assertTrue("Add API not working. Expected 5 but received: " + a, a == 5);
	}

	/**
	 * Test method for {@link api.SimpleAPI#subtract(int, int)}.
	 */
	public void testSubtract() {
		int a = SimpleAPI.subtract(2, 3);
		assertTrue("Subtract API not working. Expected -1 but received: " + a, a == -1);

		a = SimpleAPI.subtract(3, -4);
		assertTrue("Subtract API not working. Expected 7 but received: " + a, a == 7);

		a = SimpleAPI.subtract(5, 4);
		assertTrue("Subtract API not working. Expected 1 but received: " + a, a == 1);
	}

	/**
	 * Test method for {@link api.SimpleAPI#divide(int, int)}.
	 */
	public void testDivide() {
		int a = SimpleAPI.divide(44, 11);
		assertTrue("Subtract API not working. Expected 4 but received: " + a, a == 4);
	}

	/**
	 * Test method for {@link api.SimpleAPI#multiply(int, int)}.
	 */
	public void testMultiply() {
		int a = SimpleAPI.multiply(2, 3);
		assertTrue("Multiply API not working. Expected 6 but received: " + a, a == 6);
	}
}

Add tests for simple api

Add tests for simple api


package com.hida.service;

import com.hida.model.BadParameterException;
import com.hida.model.DefaultSetting;
import com.hida.model.Pid;
import org.mockito.Mock;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.testng.Assert;
import static org.testng.Assert.*;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

/**
 *
 * @author lruffin
 */
public class MinterServiceImplTest {

    @Mock
    MinterService MinterServiceDao;

    @InjectMocks
    MinterServiceImpl MinterServiceImpl;

    @BeforeClass
    public void setUpClass() throws Exception {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testMint() throws BadParameterException {
        Assert.fail("unimplemented");
    }

    @Test
    public void testGetCurrentSetting() {
        Assert.fail("unimplemented");
    }

    @Test
    public void updateCurrentSetting() {
        Assert.fail("unimplemented");
    }

}

Create stub to test MinterServiceImpl

Create stub to test MinterServiceImpl

This class was created to test the API provided by MinterService. All
of the test cases are failing on purpose and will be updated at a later
time.


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

/**
 * In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all
 * positive integers less than or equal to n. For example:
 *
 * 5! = 5  \times  4  \times  3  \times  2  \times  1 = 120.
 *
 * The value of 0! is 1, according to the convention for an empty product.
 *
 * Can you write a method to calculate the factorial of a given positive integer?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class Factorial {

}

Add statement for problem 9

Add statement for problem 9


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

/**
 * Given an image represented by an NxN matrix, where each pixel in the image is an integer, write
 * a method to rotate the image by 90 degrees. Can you do this in place?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class RotateMatrix {

}

Add statement to problem 54

Add statement to problem 54


package com.continuuity.passport.utils;

import org.junit.Test;

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

/**
 *
 */
public class TestURI {

  @Test
  public void testUri() throws URISyntaxException, MalformedURLException {
    URI uri  = new URI ("http://foo.bar.com");
    URI appendedUri = getAppendedURI(uri,"/path/to/baz");

    assert(appendedUri.toURL().toString().equals("http://foo.bar.com/path/to/baz"));

  }

  @Test
  public void testUriWithQueryParam() throws URISyntaxException, MalformedURLException {
    URI uri  = new URI ("http://foo.bar.com?query=param");
    URI appendedUri =  getAppendedURI(uri, "query=param");
    assert(appendedUri.toURL().toString().equals("http://foo.bar.com/path/to/baz?query=param"));
  }

  public URI getAppendedURI(URI uri, String relativePath) throws MalformedURLException, URISyntaxException {
    if (uri.getQuery() !=null && uri.getQuery().isEmpty()){
      return new URI(String.format("%s/%s",uri.toURL(),relativePath));
    }
    else {
      return new URI(String.format("%s/%s?%s",uri.toURL(),relativePath,uri.getQuery()));
    }
  }
}

Add test case for URI

Add test case for URI


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

package imagej.data.io;

import imagej.data.Dataset;
import imagej.data.DatasetService;
import imagej.io.AbstractIOPlugin;
import imagej.io.IOPlugin;

import java.io.IOException;

import org.scijava.plugin.Plugin;

/**
 * I/O plugin for {@link Dataset}s.
 *
 * @author Curtis Rueden
 */
@Plugin(type = IOPlugin.class)
public class DatasetIOPlugin extends AbstractIOPlugin<Dataset> {

	// -- IOPlugin methods --

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

	@Override
	public boolean supportsOpen(final String source) {
		return datasetService().canOpen(source);
	}

	@Override
	public boolean supportsSave(final String destination) {
		return datasetService().canSave(destination);
	}

	@Override
	public Dataset open(final String source) throws IOException {
		return datasetService().open(source);
	}

	@Override
	public void save(final Dataset dataset, final String destination)
		throws IOException
	{
		datasetService().save(dataset, destination);
	}

	// -- Helper methods --

	private DatasetService datasetService() {
		return getContext().getService(DatasetService.class);
	}

}

Add an I/O plugin for Datasets

Add an I/O plugin for Datasets

It is short and sweet thanks to the new DatasetService I/O methods.


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

// https://www.hackerrank.com/challenges/counting-valleys/problem
public class CountingValleys {

    private static final char D = 'D';
    private static final char U = 'U';

    private static String readPath() throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            reader.readLine(); // Ignore this line.
            return reader.readLine();
        }
    }

    private static int countValleys(String path) {
        int seaLevel = 0;
        int valleys = 0;
        for (char c : path.toCharArray()) {
            if (seaLevel == 0 && c == D) {
                valleys += 1;
            }
            seaLevel += (c == U) ? 1: -1;
        }
        return valleys;
    }

    public static void main(String[] args) throws IOException {
        String path = readPath();
        int valleys = countValleys(path);
        System.out.println(valleys);
    }
}

Add solution for Counting valleys problem.


/*
 * Copyright (C) 2004 EBI, GRL
 *
 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 */

package org.ensembl.healthcheck.testcase.variation;

import java.sql.Connection;

import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;

/**
 * Check that the variation table does not contain anomalities
 */
public class Variation extends SingleDatabaseTestCase {

	/**
	 * Creates a new instance of Variation
	 */
	public Variation() {

		addToGroup("variation-release");

		setDescription("Checks that the variation table does not have blank evidence statuses");
		setTeamResponsible(Team.VARIATION);

	}

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

	/**
	 * Check that the variation table does not have blank evidence statuses
	 *
	 * @param dbre
	 *          The database to check.
	 * @return true if the test passed.
	 */
	public boolean run(DatabaseRegistryEntry dbre) {

		Connection con = dbre.getConnection();
		boolean result = true;

		try {
			// Check for empty but non-null evidence statuses
			if (!checkCountIsZero(con,"variation","evidence = '' ")) {
				ReportManager.problem(this, con, "Variations with blank evidence statuses");
				result = false;
			}

		} catch (Exception e) {
			ReportManager.problem(this, con, "HealthCheck caused an exception: " + e.getMessage());
			result = false;
		}

		return result;

	} // run

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

	/**
	 * This only applies to variation databases.
	 */
	public void types() {

		removeAppliesToType(DatabaseType.OTHERFEATURES);
		removeAppliesToType(DatabaseType.CDNA);
		removeAppliesToType(DatabaseType.CORE);
		removeAppliesToType(DatabaseType.VEGA);

	}

} // Variation

Check for blank (non-null) evidence statuses


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

/**
 * Given a binary tree passed as argument, can you write a method to return true if the binary tree
 * is a Binary Search Tree?
 *
 * A Binary Search Tree (BST), sometimes also called an ordered or sorted binary tree, is a
 * node-based binary tree data structure where each node has a comparable key (and an associated
 * value) and satisfies the restriction that the key in any node is larger than the keys in all
 * nodes in that node's left sub-tree and smaller than the keys in all nodes in that node's right
 * sub-tree. Each node has no more than two child nodes. Each child must either be a leaf node or
 * the root of another binary search tree. The left sub-tree contains only nodes with keys less
 * than
 * the parent node; the right sub-tree contains only nodes with keys greater than the parent node.
 * BSTs are also dynamic data structures, and the size of a BST is only limited by the amount of
 * free memory in the operating system. The main advantage of binary search trees is that it
 * remains
 * ordered, which provides quicker search times than many other data structures.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class IsBST {
}

Add statement to problem 18

Add statement to problem 18


package com.pollistics.models.validators;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.pollistics.models.*;

public class UserValidator implements Validator {
	@Override
	public boolean supports(Class<?> clazz) {
		return clazz.isInstance(User.class);
	}

	@Override
	public void validate(Object target, Errors errors) {
		User user = (User) target;
		if(!user.getUsername().matches("^(?=.{3,20}$)(?![_.])(?!.*[_.]{2})[a-zA-Z0-9._]+(?<![_.])$")) {
			errors.rejectValue("username", "invalid.username", "Username has to be 3 to 20 characters and contain only letters, number and dots or underscores.");
		}
		if(!user.getPassword().matches("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{8,}$")) {
			errors.rejectValue("password", "invalid.password", "Password has to be at least 8 characters long and needs to contain at least one uppercase letter, one lowercase leter and one number");
		}
	}
}

Add validator for user object

Add validator for user object


package api.torrents.torrents;

import api.son.MySon;
import api.soup.MySoup;

/**
 * A standalone torrent request. contains information about the group the torrent
 * is in and the torrent itself
 */
public class Torrent {
	private String status;
	private Response response;

	public static Torrent fromId(int id){
		String url = "ajax.php?action=torrent&id=" + id + "&auth=" + MySoup.getAuthKey();
		return (Torrent)MySon.toObject(url, Torrent.class);
	}

	public boolean getStatus(){
		return status.equalsIgnoreCase("success");
	}

	public Group getGroup(){
		return response.group;
	}

	public Torrents getTorrent(){
		return response.torrent;
	}

	@Override
	public String toString(){
		return "Torrent [group=" + response.group + ", torrent=" + response.torrent + "]";
	}

	/**
	 * The API response returned for a single torrent
	 */
	private static class Response {
		/**
		 * Information about the group the torrent is in
		 */
		public Group group;
		/**
		 * The torrent itself
		 */
		public Torrents torrent;
	}
}

Add support for loading a single torrent by id


package com.pm.server.player;

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

import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.pm.server.PmServerApplicationTests;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(PmServerApplicationTests.class)
public class GhostRepositoryTest {

	@Autowired
	private GhostRepository ghostRepository;

	private static final Logger log =
			LogManager.getLogger(GhostRepositoryTest.class.getName());

	@Before
	public void setUp() {

		List<Ghost> ghostList = ghostRepository.getAllGhosts();

		for(Ghost ghost : ghostList) {
			try {
				ghostRepository.deleteGhostById(ghost.getId());
			}
			catch(Exception e) {
				log.error(e.getMessage());
				fail();
			}
		}

		assertTrue(ghostRepository.getAllGhosts().isEmpty());

	}

}

Add skeleton for GhostRepository tests

Add skeleton for GhostRepository tests


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

package com.google.sps;

/**
 * Custom exception class for photo detection classes.
 */
public class PhotoDetectionException extends Exception {
  public PhotoDetectionException(String errorMessage) {
    super(errorMessage);
  }

  public PhotoDetectionException(String errorMessage, Throwable cause) {
    super(errorMessage, cause);
  }
}

Add custom exception class for photo detection


package fgis.server.support.geojson;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.util.Arrays;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import javax.json.JsonStructure;
import javax.json.stream.JsonGenerator;
import org.geolatte.geom.Geometry;
import org.geolatte.geom.codec.Wkt;
import org.geolatte.geom.codec.Wkt.Dialect;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class GeoJsonWriterTest
{
  @Test
  public void emitPointGeometry()
  {
    final Geometry geometry = fromWkT( "POINT (1 1)" );
    final GjElement e = new GjGeometry( geometry, null, null, null );

    final JsonStructure result = writeAndRead( e );

    final String expectedJson = "{\"type\":\"Point\",\"coordinates\":[1.0,1.0]}";
    final JsonObject expected = (JsonObject) parse( expectedJson );
    assertEquals( result, expected );
  }

  private JsonStructure writeAndRead( final GjElement e )
  {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final JsonGenerator g = Json.createGenerator( baos );

    new GeoJsonWriter().emit( g, e );

    g.flush();

    return parse( baos.toByteArray() );
  }

  private JsonStructure parse( final byte[] bytes )
  {
    return parse( new String( bytes, Charset.forName( "US-ASCII" ) ) );
  }

  private JsonStructure parse( final String json )
  {
    return new JsonReader( new StringReader( json ) ).read();
  }

  @SuppressWarnings( "unchecked" )
  public final <T extends Geometry> T fromWkT( final String wkt )
  {
    return (T) Wkt.newDecoder( Dialect.POSTGIS_EWKT_1 ).decode( wkt );
  }
}

Add basic test for emitting a point

Add basic test for emitting a point


package com.thoughtomaton.SamsJava21Days.day01;

class MarsApplication {
    public static void main(String[] args) {
        System.out.println("hello robot");
    }
}

Add day01 main file and set up for execution with IntelliJ


package com.github.aureliano.verbum_domini.web.ui;

import java.io.IOException;

import javax.faces.component.FacesComponent;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;

import com.github.aureliano.verbum_domini.helper.UrlHelper;

@FacesComponent(
		value = "com.github.aureliano.verbum_domini.web.ui.HtmlScript",
		tagName = "script", createTag = true
	)
public class HtmlScript extends UIComponentBase {

	public HtmlScript() {
		super();
	}

	@Override
	public String getFamily() {
		return "custom.ui.verbum_domini";
	}

	@Override
	public void encodeBegin(FacesContext facesContext) throws IOException {
		StringBuilder tag = new StringBuilder();

		tag.append("<script");

		String source = (String) super.getAttributes().get("source");
		if (source != null) {
			String url = UrlHelper.buildWebAppUrl("js/" + source + ".js");
			tag.append(" src=\"" + url + "\"");
		}

		tag.append("></script>");

		facesContext.getResponseWriter().write(tag.toString());
	}
}

Create custom script tag component.

Create custom script tag component.


//
//  TestJSONDecoding.java
//  xal
//
//  Created by Tom Pelaia on 2/17/2011.
//  Copyright 2011 Oak Ridge National Lab. All rights reserved.
//

package xal.tools.text;

import org.junit.*;

/** test the ScientificNumberFormat class */
public class TestScientificNumberFormat {
	@Test
	public void testPositiveSimpleFormats() {
		assertFormat( "    3.1416", 5, 10, 3.14159265 );
	}

	@Test
	public void testNegativeSimpleFormats() {
		assertFormat( "   -3.1416", 5, 10, -3.14159265 );
	}

	@Test
	public void testPositiveExponentialFormats() {
		assertFormat( "   1.000E1", 4, 10, 10.0 );
		assertFormat( "    3.00E2", 3, 10, 300.0 );
		assertFormat( "  5.24E250", 3, 10, 5.2395E+250 );
		assertFormat( "  1.000E-1", 4, 10, 0.1 );
		assertFormat( "  9.900E-1", 4, 10, 0.99 );
	}

	@Test
	public void testNegativeExponentialFormats() {
		assertFormat( "  -1.000E1", 4, 10, -10.0 );
		assertFormat( " -1.000E-1", 4, 10, -0.1 );
		assertFormat( " -9.900E-1", 4, 10, -0.99 );
		assertFormat( "   -3.00E2", 3, 10, -300.0 );
		assertFormat( "  -5.2395E250", 5, 13, -5.2395E+250 );
		assertFormat( " -5.2395E-250", 5, 13, -5.2395E-250 );
	}

	@Test
	public void testRoundingFormats() {
		assertFormat( "    1.49", 3, 8, 1.494999 );
		assertFormat( "    1.50", 3, 8, 1.495 );
	}

	/** Assert whether the formatted output matches the specified reference */
	static private void assertFormat( final String reference, final int significantDigits, final int width, final double value ) {
		final ScientificNumberFormat format = new ScientificNumberFormat( significantDigits, width );
		final String output = format.format( value );
		Assert.assertEquals( "Failed format equality for number: " + value + " with output: " + output + " of length: " + output.length(), reference, output );
	}
}

Add unit tests for ScientificNumberFormat


package leetcode.binary_search_tree_iterator;

import common.TreeNode;

public class BSTIterator {
    Integer biggest = null;
    Integer curVal = null;
    TreeNode root;

    public BSTIterator(TreeNode root) {
        this.root = root;
        TreeNode cur = root;
        if(cur != null){
            while(cur.right != null){
                cur = cur.right;
            }
            biggest = cur.val;
        }
    }

    /** @return whether we have a next smallest number */
    public boolean hasNext() {
        if(biggest == null) return false;
        return curVal == null || biggest > curVal;
    }

    /** @return the next smallest number */
    public int next() {
        TreeNode cur = root;
        int smallest = biggest;
        if(curVal == null || cur.val > curVal)
            smallest = cur.val;
        while(cur != null){
            if(curVal == null || cur.val > curVal){
                cur = cur.left;
            }else{
                cur = cur.right;
            }
            if(cur != null && cur.val < smallest && (curVal == null || cur.val > curVal)){
                smallest = cur.val;
            }
        }
        return curVal = smallest;
    }
}

Add java solution for 173. Binary Search Tree Iterator

173. Binary Search Tree Iterator: https://leetcode.com/problems/binary-search-tree-iterator/


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

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;

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

}

Add statement to problem 76

Add statement to problem 76


package nl.hsac.fitnesse.fixture.slim;

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

import nl.hsac.fitnesse.fixture.util.FileUtil;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;

/**
 * Fixture to deal with Base64 values.
 */
public class Base64Fixture extends SlimFixture {
    private String saveBase = new File(filesDir, "base64").getPath() + "/";

    /**
     * Gets the content of specified file base64 encoded.
     * @param fileUrl either absolute path, or link to file inside wiki's files section.
     * @return base64 encoded file content.
     */
    public String encode(String fileUrl) {
        String file = getFilePathFromWikiUrl(fileUrl);
        try {
            byte[] content = IOUtils.toByteArray(new FileInputStream(file));
            return base64Encode(content);
        } catch (IOException e) {
            throw new SlimFixtureException("Unable to read: " + file, e);
        }
    }

    /**
     * Creates a new file with content read from base64 encoded string.
     * @param fileName (base) file name to create (if a file with specified name already exists
     *                 a number will be added to make the name unique).
     * @param base64String base64 encoded string to decode and use as file content.
     * @return location of created file.
     */
    public String createFrom(String fileName, String base64String) {
        String result;
        String baseName = FilenameUtils.getBaseName(fileName);
        String target = saveBase + baseName;
        String ext = FilenameUtils.getExtension(fileName);
        byte[] content = base64Decode(base64String);
        String downloadedFile = FileUtil.saveToFile(target, ext, content);
        String wikiUrl = getWikiUrl(downloadedFile);
        if (wikiUrl != null) {
            // make href to file
            result = String.format("%s", wikiUrl, fileName);
        } else {
            result = downloadedFile;
        }
        return result;
    }

    protected String base64Encode(byte[] content) {
        return org.apache.commons.codec.binary.Base64.encodeBase64String(content);
    }
    protected byte[] base64Decode(String base64String) {
        return org.apache.commons.codec.binary.Base64.decodeBase64(base64String);
    }

    public String getSaveBase() {
        return saveBase;
    }

    public void setSaveBase(String saveBase) {
        this.saveBase = saveBase;
    }
}

Add fixture to deal with base64 encoded binary values


package roart.service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import roart.common.config.ConfigConstants;
import roart.common.ml.TensorflowLSTMConfig;
import roart.common.pipeline.PipelineConstants;
import roart.common.util.TimeUtil;
import roart.component.ComponentPredictor;
import roart.component.model.PredictorParam;
import roart.iclij.model.MemoryItem;
import roart.util.ServiceUtil;

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

import com.fasterxml.jackson.databind.ObjectMapper;

public class PredictorService {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    public List<MemoryItem> doPredict(String market, Integer offset, String aDate, boolean doSave, boolean doPrint) throws Exception {
        ControlService srv = new ControlService();
        srv.getConfig();
        return doPredict(srv, market, offset, aDate, doSave, doPrint);
    }

    public List<MemoryItem> doPredict(ControlService srv, String market, Integer offset, String aDate, boolean doSave, boolean doPrint) throws Exception {
        long time0 = System.currentTimeMillis();
        PredictorParam param = new PredictorParam();
        param.setMarket(market);
        param.setDoPrint(doPrint);
        param.setDoSave(doSave);
        srv.conf.setMarket(market);
        String lstmConf = srv.conf.getLSTMConfig();
        int futuredays = 0;
        try {
            TensorflowLSTMConfig lstm = new ObjectMapper().readValue(lstmConf, TensorflowLSTMConfig.class);
            futuredays = lstm.getHorizon();
        } catch (Exception e) {
            log.error("Exception", e);
            return new ArrayList<>();
        }
        param.setFuturedays(futuredays);
        param.setDates(srv, futuredays, offset, aDate);
        Map<String, Object> setValueMap = new HashMap<>();
        setValueMap.put(ConfigConstants.AGGREGATORSINDICATOR, Boolean.FALSE);
        setValueMap.put(ConfigConstants.AGGREGATORSINDICATOREXTRAS, "");
        setValueMap.put(ConfigConstants.AGGREGATORSINDICATORRECOMMENDER, Boolean.FALSE);
        setValueMap.put(ConfigConstants.PREDICTORS, Boolean.TRUE);
        setValueMap.put(ConfigConstants.MACHINELEARNING, Boolean.TRUE);
        setValueMap.put(ConfigConstants.INDICATORSMACD, Boolean.FALSE);

        Map map = (Map) param.getCategoryResultMap(srv, PipelineConstants.LSTM, setValueMap);
        if (map == null) {
            return null;
        }
        param.setCategory(map);
        Map<String, List<Double>> resultMap = (Map<String, List<Double>>) map.get(PipelineConstants.RESULT);
        param.setResultMap(resultMap);
        param.getAndSetCategoryValueMap(srv);
        param.setUsedsec(time0);
        return new ComponentPredictor().calculatePredictor(param);
    }

}

Change config to JSON (I2).

Change config to JSON (I2).


package org.intermine.webservice.server;

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

public enum Format {

    /** The format for when no value is given **/
    EMPTY(null),
    /** The Unknown format **/
    UNKNOWN(null),
    /** The HTML format **/
    HTML("text/html"),
    /** Plain Text **/
    TEXT("text/plain"),
    /** XML **/
    XML("application/xml"),
    /** Comma-separated-values **/
    CSV("text/comma-separated-values"),
    /** Tab-separated-values **/
    TSV("text/tab-separated-values"),
    /** Vanilla-JSON **/
    JSON("application/json"),
    /** JSON Object format constant **/
    OBJECTS("application/json;format=objects"),
    /** JSON Table format constant **/
    TABLE("application/json;format=table"),
    /** JSON Row format constant **/
    ROWS("application/json;format=rows");

    public static final Set<Format> BASIC_FORMATS = new HashSet<Format>(Arrays.asList(
        HTML, TEXT, XML, JSON
    ));

    public static final Set<Format> JSON_FORMATS = new HashSet<Format>(Arrays.asList(
        JSON, OBJECTS, TABLE, ROWS
    ));

    public static final Set<Format> FLAT_FILES = new HashSet<Format>(Arrays.asList(
        TSV, CSV
    ));

    private final String contentType;

    private Format(String contentType) {
        this.contentType = contentType;
    }

    public String getContentType() {
        return contentType;
    }

    @Override
    public String toString() {
        return super.toString() + ((contentType == null) ? "" : (" (" + contentType + ") "));
    }

}

Move to a much cleaner format implementation

Former-commit-id: bdfd64ffe5a36a07113dc332121fe540d938cbf6


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

package com.legendzero.lzlib.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.bukkit.util.Vector;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class Vectors {

    public static Vector fromCSV(String string) {
        return fromCSV(string.split(","));
    }

    public static Vector fromCSV(String[] strings) {
        double x = 0;
        double y = 0;
        double z = 0;
        try {
            switch (strings.length) {
                case 3:
                    z = Double.valueOf(strings[2]);
                case 2:
                    y = Double.valueOf(strings[1]);
                case 1:
                    x = Double.valueOf(strings[0]);
                case 0:
                    break;
                default:

            }
        } catch (NumberFormatException e) {
            return null;
        }
        return new Vector(x, y, z);
    }

    public static String toCSV(Vector vector) {
        return vector.getX() + "," + vector.getY() + "," + vector.getZ();
    }
}

Add easy Vector String conversions

Add easy Vector String conversions


/**
 * Copyright 2015 Alessandro Daniele, Fabio Cesarato, Andrea Giraldin
 *
 * 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.salsaw.salsa.utils;

// http://www.mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname/
public class OSChecker {

	private static String OS = System.getProperty("os.name").toLowerCase();

	public static boolean isWindows() {
		return (OS.indexOf("win") >= 0);
 	}

	public static boolean isMac() {
 		return (OS.indexOf("mac") >= 0);
	}

	public static boolean isUnix() {
		return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 );
 	}

	public static boolean isSolaris() {
		return (OS.indexOf("sunos") >= 0);
	}
}

[ADD] Add class to get current opertive system


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

package org.spongepowered.api.service.command;

import org.spongepowered.api.util.command.dispatcher.Dispatcher;

/**
 * A command dispatcher watches for commands (such as those said in chat)
 * and dispatches them to the correct command handler.
 */
public interface CommandDispatcher extends Dispatcher {

}

Add preliminary command dispatcher service.


package org.telegram.telegrambots.api.commands;

import org.telegram.telegrambots.BotLogger;
import org.telegram.telegrambots.TelegramApiException;
import org.telegram.telegrambots.api.methods.send.SendMessage;

/**
 * standard help command, which gets registered by default, to supply a list of all available commands
 *
 * @author tschulz
 */
public class HelpCommand extends Command {

    private static final String LOGTAG = "HELPCOMMAND";
    private final ICommandRegistery commandRegistry;

    public HelpCommand(ICommandRegistery commandRegistry, String botToken) {
        super("help", "Gives an overview over all Commands registered for this bot", botToken);
        this.commandRegistry = commandRegistry;
    }

    @Override
    void execute(String[] arguments, long chatId) {
        for (Command registeredCommand : commandRegistry.getRegisteredCommands()) {
            SendMessage sendMessage = new SendMessage();
            sendMessage.setChatId(chatId);
            sendMessage.enableHtml(true);
            sendMessage.setText("<b>" + registeredCommand.getCommandIdentifier() + "</b>\n" + registeredCommand.getDescription());

            try {
                sendMessage(sendMessage);
            } catch (TelegramApiException e) {
                BotLogger.error("Failed to send HelpMessage", LOGTAG, e);
            }
        }
    }
}

Implement basic help command, which provides an overview over all registered commands


package com.gmail.nossr50.listeners;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;

import com.gmail.nossr50.util.Hardcore;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;

public class HardcoreListener implements Listener {

    /**
     * Monitor PlayerDeath events.
     *
     * @param event The event to monitor
     */
    @EventHandler(priority = EventPriority.MONITOR)
    public void onPlayerDeath(PlayerDeathEvent event) {
        Player player = event.getEntity();

        if (Misc.isNPCPlayer(player)) {
            return;
        }

        if (!Permissions.hardcoremodeBypass(player)) {
            Player killer = player.getKiller();

            if (killer != null && Hardcore.vampirismEnabled) {
                Hardcore.invokeVampirism(killer, player);
            }

            Hardcore.invokeStatPenalty(player);
        }
    }
}

package com.gmail.nossr50.listeners;

import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;

import com.gmail.nossr50.util.Hardcore;
import com.gmail.nossr50.util.Misc;
import com.gmail.nossr50.util.Permissions;

public class HardcoreListener implements Listener {

    /**
     * Monitor PlayerDeath events.
     *
     * @param event The event to watch
     */
    @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true)
    public void onPlayerDeath(PlayerDeathEvent event) {
        Player player = event.getEntity();

        if (Misc.isNPCPlayer(player)) {
            return;
        }

        if (!Permissions.hardcoremodeBypass(player)) {
            Player killer = player.getKiller();

            if (killer != null && Hardcore.vampirismEnabled) {
                Hardcore.invokeVampirism(killer, player);
            }

            Hardcore.invokeStatPenalty(player);
        }
    }
}

Make sure we ignore cancelled events.

Make sure we ignore cancelled events.


package com.samczsun.helios.gui;

import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;

import java.util.function.BiConsumer;

/**
 * @author DarkSeraphim.
 */
public class GenericClickListener implements MouseListener, java.awt.event.MouseListener {

    enum ClickType {
        LEFT, MIDDLE, RIGHT;
        private static ClickType fromButton(int button) {
            return ClickType.values()[button - 1];
        }
    }

    private final BiConsumer<ClickType, Boolean> handler;

    private final byte buttons;

    private final boolean doubleClick;

    public GenericClickListener(BiConsumer<ClickType, Boolean> handler, ClickType type, ClickType...others) {
        this(handler, false, type, others);
    }

    public GenericClickListener(BiConsumer<ClickType, Boolean> handler, boolean doubleClick, ClickType type, ClickType...others) {
        this.handler = handler;
        this.doubleClick = doubleClick;
        int buttons = 1 << type.ordinal();
        for (ClickType otherType : others) {
            buttons |= 1 << otherType.ordinal();
        }
        this.buttons = (byte) buttons;
    }

    /* *
     * SWT events
     * */

    @Override
    public void mouseDoubleClick(MouseEvent event) {
        handle(ClickType.fromButton(event.button), true);
    }

    @Override
    public void mouseDown(MouseEvent event) {
    }

    private void handle(ClickType type, boolean doubleClick) {
        if (this.doubleClick == doubleClick && (this.buttons & (1 << (type.ordinal()))) != 0) {
            this.handler.accept(type, doubleClick);
        }
    }

    @Override
    public void mouseUp(MouseEvent event) {
        handle(ClickType.fromButton(event.button), false);
    }

    /* *
     * AWT events
     * */

    @Override
    public void mouseClicked(java.awt.event.MouseEvent e) {
        handle(ClickType.fromButton(e.getButton()), false);
    }

    @Override
    public void mousePressed(java.awt.event.MouseEvent e) {
    }

    @Override
    public void mouseReleased(java.awt.event.MouseEvent e) {
    }

    @Override
    public void mouseEntered(java.awt.event.MouseEvent e) {
    }

    @Override
    public void mouseExited(java.awt.event.MouseEvent e) {
    }
}

Add generic click listener for AWT and SWT


package com.suse.salt.netapi.calls.modules;

import com.google.gson.reflect.TypeToken;
import com.suse.salt.netapi.calls.LocalCall;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;

/**
 * salt.modules.zypper
 *
 * https://docs.saltstack.com/en/latest/ref/modules/all/salt.modules.zypper.html
 */
public class Zypper {

    private Zypper() { }

    /**
     * The product information as returned by listProducts().
     */
    public static class ProductInfo {
        private final String name;
        private final String arch;
        private final String description;
        private final String eol;
        private final String epoch;
        private final String flavor;
        private final boolean installed;
        private final boolean isbase;
        private final String productline;
        private final String registerrelease;
        private final String release;
        private final String repo;
        private final String shortname;
        private final String summary;
        private final String vendor;
        private final String version;

        public ProductInfo(String name, String arch, String description, String eol,
                String epoch, String flavor, boolean installed, boolean isbase,
                String productline, String registerrelease, String release, String repo,
                String shortname, String summary, String vendor, String version) {
            this.name = name;
            this.arch = arch;
            this.description = description;
            this.eol = eol;
            this.epoch = epoch;
            this.flavor = flavor;
            this.installed = installed;
            this.isbase = isbase;
            this.productline = productline;
            this.registerrelease = registerrelease;
            this.release = release;
            this.repo = repo;
            this.shortname = shortname;
            this.summary = summary;
            this.vendor = vendor;
            this.version = version;
        }

        public String getName() {
            return name;
        }

        public String getVersion() {
            return version;
        }

        public String getArch() {
            return arch;
        }

        public String getDescription() {
            return description;
        }

        public String getEol() {
            return eol;
        }

        public String getEpoch() {
            return epoch;
        }

        public String getFlavor() {
            return flavor;
        }

        public boolean getInstalled() {
            return installed;
        }

        public boolean getIsbase() {
            return isbase;
        }

        public String getProductline() {
            return productline;
        }

        public String getRegisterrelease() {
            return registerrelease;
        }

        public String getRelease() {
            return release;
        }

        public String getRepo() {
            return repo;
        }

        public String getShortname() {
            return shortname;
        }

        public String getSummary() {
            return summary;
        }

        public String getVendor() {
            return vendor;
        }
    }

    public static LocalCall<List<ProductInfo>> listProducts(boolean all) {
        LinkedHashMap<String, Object> args = new LinkedHashMap<>();
        args.put("all", all);
        return new LocalCall<>("pkg.list_products", Optional.empty(), Optional.of(args),
                new TypeToken<List<ProductInfo>>() { });
    }
}

Add zypper module support containing listProducts()


package flyway.pti;

import fi.nls.oskari.util.JSONHelper;
import org.flywaydb.core.api.migration.BaseJavaMigration;
import org.flywaydb.core.api.migration.Context;
import org.json.JSONObject;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Removed layer.options.legends object (removing any override admin has given) for layers
 * returned by getLayersToModify().
 * This one removes overrides from layers with dataprovider 57 (Tilastokeskus)-
 */
public class V3_0_8__remove_legend_overrides extends BaseJavaMigration {

    class Result {
        int id;
        String options;
    }

    public void migrate(Context context) throws Exception {
        Connection connection = context.getConnection();
        List<Result> layers = getLayersToModify(connection);
        layers.forEach(r -> removeLegendOverrides(r));
        saveChanges(connection, layers);
    }

    private void removeLegendOverrides(Result result) {
        if (result.options == null) {
            return;
        }
        JSONObject options = JSONHelper.createJSONObject(result.options);
        if (options == null) {
            return;
        }
        options.remove("legends");
        result.options = options.toString();
    }

    public int getDataproviderToModify() {
        return 57;
    }

    public List<Result> getLayersToModify(Connection conn) throws Exception {
        List<Result> layers = new ArrayList<>();
        // remove legends override from layers by "Tilastokeskus"
        final String sql = "SELECT id, options FROM oskari_maplayer where dataprovider_id = " + getDataproviderToModify();
        try(PreparedStatement statement = conn.prepareStatement(sql)) {
            try (ResultSet rs = statement.executeQuery()) {
                while(rs.next()) {
                    Result result = new Result();
                    result.id = rs.getInt("id");
                    result.options = rs.getString("options");
                    layers.add(result);
                }
            }
        }
        return layers;
    }

    private void saveChanges(Connection conn, List<Result> layers) throws SQLException {
        String sql = "UPDATE oskari_maplayer SET options = ? WHERE id = ?";
        try (PreparedStatement ps = conn.prepareStatement(sql)) {
            for (Result layer : layers) {
                ps.setString(1, layer.options);
                ps.setInt(2, layer.id);
                ps.addBatch();
            }
            ps.executeBatch();
        }
    }
}

Remove legend overrides from layers from Tilastokeskus


/*
 * Copyright 2016 Vladimir Kizelbashev
 *
 * 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.haulmont.testtask.app;

import com.haulmont.testtask.entity.Group;

import com.vaadin.data.util.converter.Converter;
import java.util.Locale;

/**
 * The class {@code GroupConverter} is a class to String-Group and Group-String conversion,
 * to display group data in a table cell.
 *
 * @version 1.0
 * @author Vladimir
 */
class GroupConverter implements Converter<String, Group> {

    /**
     * Method to convert a String to a Group
     * @param s The string contains a newline-separated fields in the following form:
     *          id \n number \n faculty. Can be null.
     * @param aClass The type of the return value.
     * @param locale The locale to use for conversion. Can be null.
     * @throws ConversionException
     */
    @Override
    public Group convertToModel(String s, Class<? extends Group> aClass, Locale locale) throws ConversionException {
        if (s == null) {
            return null;
        }
        String[] parts = s.split("\n");
        if (parts.length != 3) {
            throw new ConversionException("Can not convert String to Group: " + s);
        }
        Group group = new Group();
        try {
            group.setId(Long.valueOf(parts[0]));
            group.setNumber(Integer.valueOf(parts[1]));
            group.setFaculty(parts[2]);
        } catch (Exception e) {
            throw new ConversionException(e.getMessage());
        }
        return group;
    }

    @Override
    public String convertToPresentation(Group group, Class<? extends String> aClass, Locale locale) throws ConversionException {
        if (group != null) {
            return String.valueOf(group.getNumber()) + ", " + group.getFaculty();
        } else {
            return null;
        }
    }

    @Override
    public Class<Group> getModelType() {
        return Group.class;
    }

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

Add class to group model-presentation conversion


package leetcode.remove_nth_node_from_end_of_list;

import java.util.ArrayList;

import common.ListNode;

public class Solution {
	public ListNode removeNthFromEnd(ListNode head, int n) {
		if(head == null || n == 0){
			return head;
		}
		if(n == 1 && head.next == null) return null;
		int size = 0;
		ListNode cur = head;
		while(cur != null){
			cur = cur.next;
			size += 1;
		}
		n = size - n;
		if(n == 0){
			head = head.next;
		}else{
			cur = head;
			ListNode prev = null;
			while(n > 0){
				prev = cur;
				n--;
				cur = cur.next;
			}
			prev.next = cur.next;
		}
		return head;
	}

//	public static class ListNode {
//		int val;
//		ListNode next;
//		ListNode(int x) {
//			val = x;
//			next = null;
//		}
//		public void dump(){
//			ListNode cur = this;
//			while(cur != null){
//				System.err.println("val = " + cur.val);
//				cur = cur.next;
//			}
//			System.err.println("");
//		}
//	}

	public static void main(String[] args){
		final int N = 10;
//		Solution sol = new Solution();
		for(int i = 0; i <= N; i++){
			ArrayList<ListNode> ary = new ArrayList<ListNode>();
			for(int j = 0; j < N; j++){
				ary.add(new ListNode(j));
				if(j > 0) ary.get(j - 1).next = ary.get(j);
			}
//			ListNode head = sol.removeNthFromEnd(ary.get(0), i);
//			head.dump();
		}
	}
}

Add java solution for 19. Remove Nth Node From End of List

19. Remove Nth Node From End of List: https://leetcode.com/problems/remove-nth-node-from-end-of-list/


package org.concord.otrunk.util;

import org.concord.framework.otrunk.OTObjectService;
import org.concord.framework.otrunk.view.OTLabbookManager;
import org.concord.framework.otrunk.view.OTLabbookManagerProvider;
import org.concord.otrunk.util.OTLabbookBundle.ResourceSchema;

public class OTLabbookManagerProviderImpl
    implements OTLabbookManagerProvider
{
	private ResourceSchema resources;

	public OTLabbookManagerProviderImpl(OTLabbookBundle.ResourceSchema resources)
    {
	    this.resources = resources;
    }

	public OTLabbookManager getLabbookManager(OTObjectService objectService)
	{
        try {
        	OTLabbookBundle bundle = (OTLabbookBundle) objectService.getOTObject(resources.getGlobalId());
        	this.resources = bundle.resources;
    		return new OTLabbookManagerImpl(resources);
        } catch (Exception e) {
	        e.printStackTrace();
        }
        System.err.println("Cannot create OTLabbookBundle from object service");
        return null;
	}

}

Add OTLabbookManagerProvider and implementation, which provides a service which passes back a OTLabbookManager using the OTObjectService

git-svn-id: 8ebed0c25533aaea68ca43268d4d516467f97e6a@15264 6e01202a-0783-4428-890a-84243c50cc2b


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

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

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

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

  private PartitionList partitionList;

  @Before public void setUp() {
    partitionList = new PartitionList();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullLists() {
    partitionList.split(null, 1);
  }

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

    ListNode<Integer> result = partitionList.split(list, 0);

    assertListContainsElements(new Integer[] { 3, 2, 1 }, result);
  }

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

    ListNode<Integer> result = partitionList.split(list, 4);

    assertListContainsElements(new Integer[] { 3, 2, 1 }, result);
  }

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

    ListNode<Integer> result = partitionList.split(list, 2);

    assertListContainsElements(new Integer[] { 1, 2, 3 }, result);
  }

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

  private void assertListContainsElements(Integer[] integers, ListNode<Integer> head) {
    int arrayLength = integers.length;
    ListNode<Integer> currentNode = head;

    int i = 0;
    while (i < arrayLength) {
      assertEquals(integers[i], currentNode.getData());
      currentNode = currentNode.getNext();
      i++;
    }
    assertNull(currentNode);
  }
}

Add some tests to problem 60

Add some tests to problem 60


package org.jboss.cx.remoting.core.util;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

/**
 *
 */
public final class ServiceURI {
    public static final String SCHEME = "jrs";

    private static final String FIRST_CHAR = "[$_a-zA-Z]";
    private static final String SUBSEQUENT_CHAR = "[-+$_a-zA-Z0-9]*";
    private static final String ID = FIRST_CHAR + SUBSEQUENT_CHAR;
    private static final String SEPARATOR = "[./]";

    private static final Pattern VALID_PATTERN = Pattern.compile("^(?:" + ID + "(?:" + SEPARATOR + ID + ")*)*$");

    private final URI uri;
    private final String serviceType;
    private final String groupName;
    private final String endpointName;

    public ServiceURI(final String str) throws URISyntaxException {
        this(new URI(str));
    }

    public ServiceURI(final URI uri) {
        this.uri = uri;
        if (! uri.getScheme().equals(SCHEME)) {
            throw new IllegalArgumentException("Invalid URI scheme for service");
        }
        final String ssp = uri.getSchemeSpecificPart();
        final int stcp = ssp.indexOf(':');
        if (stcp == -1) {
            serviceType = ssp;
            groupName = "";
            endpointName = "";
        } else {
            serviceType = ssp.substring(0, stcp).trim();
            final int gncp = ssp.indexOf(':', stcp + 1);
            if (gncp == -1) {
                groupName = ssp.substring(stcp + 1).trim();
                endpointName = "";
            } else {
                groupName = ssp.substring(stcp + 1, gncp).trim();
                // ignore everything after the last :
                final int encp = ssp.indexOf(':', gncp + 1);
                if (encp == -1) {
                    endpointName = ssp.substring(gncp + 1).trim();
                } else {
                    endpointName = ssp.substring(gncp + 1, encp).trim();
                }
            }
        }
        final Matcher matcher = VALID_PATTERN.matcher(serviceType);
        if (! matcher.matches()) {
            throw new IllegalArgumentException("Syntax error in service type URI part");
        }
        matcher.reset(groupName);
        if (! matcher.matches()) {
            throw new IllegalArgumentException("Syntax error in group name URI part");
        }
        matcher.reset(endpointName);
        if (! matcher.matches()) {
            throw new IllegalArgumentException("Syntax error in endpoint name URI part");
        }
    }

    public URI getUri() {
        return uri;
    }

    public String getServiceType() {
        return serviceType;
    }

    public String getGroupName() {
        return groupName;
    }

    public String getEndpointName() {
        return endpointName;
    }
}

Add service URI utility class

Add service URI utility class


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

package be.yildiz.module.graphic.ogre;

import be.yildiz.module.window.swt.SwtWindowEngine;

/**
 * @author Grégory Van den Borre
 */
public class OgreFactory {

    public static OgreGraphicEngine createOgreGraphic() {
        return new OgreGraphicEngine(new SwtWindowEngine());
    }
}

Add factory to build the engine.

[YIL-53] Add factory to build the engine.


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

/**
 * Given two integers passed as argument, can you write a function to determine the number of bits
 * required to convert integer A to integer B.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class BitsToTransform {

}

Add statement to problem 69

Add statement to problem 69


import java.util.*;
public class Solution {
    public List<List<Integer>> result = new ArrayList<List<Integer>>();
    public List<List<Integer>> subsets(int[] S) {
        Arrays.sort(S);
        List<Integer> valuelist = new ArrayList<Integer>();
        this.dfs(S, valuelist);
        return result;
    }

    public void dfs(int[] S, List<Integer> valuelist) {
        this.result.add(valuelist);
        if (S.length == 0) {
            return;
        }
        for (int i = 0; i < S.length; i++) {
            ArrayList<Integer> newList = new ArrayList<Integer>(valuelist);
            newList.add(S[i]);
            dfs(Arrays.copyOfRange(S, i+1, S.length), newList);
        }
    }
}

Revert "remove subsets for xu qian"

Revert "remove subsets for xu qian"

This reverts commit e9277076a459a077a33e10b0394c65adc949ddca.


/*
 * Copyright 2006 ProductiveMe Inc.
 * Copyright 2013 JetBrains s.r.o.
 *
 * 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.pme.exe.res.vi;

import com.pme.exe.Bin;

public class StringTable extends VersionInfoBin {

  public StringTable(String name) {
    super(name, null, new VersionInfoFactory() {
      @Override
      public VersionInfoBin createChild(int index) {
        return new StringTableEntry();
      }
    });
  }

  public void setStringValue(String key, String value) {
    for (Bin bin : getMembers()) {
      if (bin.getName().equals(key)) {
        StringTableEntry entry = (StringTableEntry) bin;
        ((WChar) entry.getMember("Value")).setValue(value);
        ((Word) entry.getMember("wValueLength")).setValue(value.length());
        return;
      }
    }
    assert false: "Could not find string with key " + key;
  }
}

/*
 * Copyright 2006 ProductiveMe Inc.
 * Copyright 2013 JetBrains s.r.o.
 *
 * 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.pme.exe.res.vi;

import com.pme.exe.Bin;

public class StringTable extends VersionInfoBin {

  public StringTable(String name) {
    super(name, null, new VersionInfoFactory() {
      @Override
      public VersionInfoBin createChild(int index) {
        return new StringTableEntry();
      }
    });
  }

  public void setStringValue(String key, String value) {
    for (Bin bin : getMembers()) {
      if (bin.getName().equals(key)) {
        StringTableEntry entry = (StringTableEntry) bin;
        ((WChar) entry.getMember("Value")).setValue(value);
        ((Word) entry.getMember("wValueLength")).setValue(value.length() + 1);
        return;
      }
    }
    assert false: "Could not find string with key " + key;
  }
}

Correct length in exe resource string tables the change done by Matt Ellis (citizenmatt)


package com.coderevisited.arrays;

import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

/**
 * 1. start from 0 to array.length -1;
 * 2. find first out of place element, i.e either positive at even index or negative at odd index
 * 3. find position of correct element, replace out of place element with correct element and shift array
 * 4. now out of place element will be 2 positions head
 */
public class RearrangePositivesAndNegative
{
    public static void main(String[] args)
    {

        PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int[] array = new int[]{-5, -2, 5, 2, 4, 7, 1, 8, 0, -8};
        rearrange(array);
        printArray(array, pw);
        pw.close();

    }

    private static void rearrange(int[] array)
    {
        int outOfPlace = -1;
        for (int i = 0; i < array.length; i++) {

            if (outOfPlace >= 0) {
                if (array[i] >= 0 && array[outOfPlace] < 0 || array[i] < 0 && array[outOfPlace] >= 0) {
                    rightRotate(array, outOfPlace, i);
                    if (i - outOfPlace > 2)
                        outOfPlace = outOfPlace + 2;
                    else
                        outOfPlace = -1;
                }
            }

            if (outOfPlace == -1) {
                if (array[i] >= 0 && ((i & 1) != 1) || array[i] < 0 && ((i & 1) == 1))
                    outOfPlace = i;
            }
        }

    }

    private static void rightRotate(int[] array, int i, int j)
    {
        int temp = array[j];
        System.arraycopy(array, i, array, i + 1, j - i);
        array[i] = temp;
    }

    private static void printArray(int[] array, PrintWriter pw)
    {
        for (int i : array) {
            pw.print(i + " ");
        }
        pw.println();
    }
}

Rearrange array in alternating positive & negative items with O(1) extra space


package org.jsmpp.util;

import static org.testng.Assert.*;
import org.jsmpp.bean.DeliveryReceipt;
import org.testng.annotations.Test;

/**
 * @author uudashr
 *
 */
public class DeliveryReceiptParserTest {
    private PDUDecomposer decomposer = new DefaultDecomposer();
    private static final String ORIGINAL_MESSAGE = "testing jsmpp bow";

    @Test
    public void parseTextWithLowerCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parsingTextWithUpperCase() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 Text:" + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), ORIGINAL_MESSAGE);
        } catch (InvalidDeliveryReceiptException e) {
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }

    @Test
    public void parseWithNoTextAttribute() {
        try {
            DeliveryReceipt delReceipt = decomposer.deliveryReceipt("id:0123456789 sub:001 dlvrd:001 submit date:200809011130 done date:200809011131 stat:DELIVRD err:000 " + ORIGINAL_MESSAGE);
            assertEquals(delReceipt.getText(), null);
        } catch (InvalidDeliveryReceiptException e) {
            e.printStackTrace();
            fail("Failed parsing delivery receipt:" + e.getMessage());
        }
    }
}

Add delivery receipt test case

Add delivery receipt test case