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

import org.asteriskjava.manager.action.AbstractManagerAction;

/**
 * LocalOptimizeAway action -- Optimize away a local channel when possible.
 *

 * Available since Asterisk 1.8
 *
 * @author SYON Communications Inc.
 */
public class LocalOptimizeAwayAction extends AbstractManagerAction
{
    /**
     * Serializable version identifier.
     */
    private static final long serialVersionUID = 1L;
    private String channel;

    /**
     * Creates a new empty LocalOptimizeAwayAction.
     */
    public LocalOptimizeAwayAction()
    {

    }

    /**
     * Creates a new LocalOptimizeAwayAction with channel name.
     *
     * @param channel Name of the channel for clears the flag.
     */
    public LocalOptimizeAwayAction(String channel)
    {
	this.channel = channel;
    }

    /**
     * Returns the name of this action, i.e. "LocalOptimizeAway".
     */
    @Override
    public String getAction()
    {
	return "LocalOptimizeAway";
    }

    /**
     * Sets the name of the channel.
     *
     * @return Name of the channel for clears the flag.
     */
    public String getChannel()
    {
	return channel;
    }

    /**
     * Returns the name of tha channel.
     *
     * @param channel Name of the channel for clears the flag.
     */
    public void setChannel(String channel)
    {
	this.channel = channel;
    }

}

Add support for LocalOptimizeAway action.

Add source file: manager/action/LocalOptimizeAwayAction.java


package com.amalgam.content;

/**
 */
public final class ContentProviderUtils {
    private static final String PLURAL_MIME_TYPE = "vnd.android.cursor.dir";
    private static final String SINGULAR_MIME_TYPE = "vnd.android.cursor.item";
    private ContentProviderUtils() {}

    public static final String buildPluralMimeType(String subType) {
        return PLURAL_MIME_TYPE + "/" + subType;
    }

    public static final String buildSingularMimeType(String subType) {
        return SINGULAR_MIME_TYPE + "/" + subType;
    }
}

Add utility for content provider

Add utility for content provider


package tk.wlemuel.cotable.activity.blog.view;

import java.lang.ref.WeakReference;

import tk.wlemuel.cotable.activity.common.SimpleBackActivity;
import tk.wlemuel.cotable.base.BaseFragment;

/**
 * DetailActivity
 *
 * @author Steve Lemuel
 * @version 0.1
 * @desc DetailActivity
 * @created 2015/05/11
 * @updated 2015/05/11
 */
public class DetailActivity extends SimpleBackActivity {

    public static final int DISPLAY_BLOG = 0;
    public static final int DIESPLAY_NEWS = 1;
    public static final String BUNDLE_KEY_DISPLAY_TYPE = "BUNDLE_KEY_DISPLAY_TYPE";

    private WeakReference<BaseFragment> mFragment;

}

Add Detail Activity for display the blog or news details


package com.stefanhoth.ropasclisp.achievements;

import android.content.Context;
import android.support.annotation.StringRes;

import com.stefanhoth.ropasclisp.R;

public enum LEADERBOARD {

    PLAYED_GAMES(R.string.leaderboard_playedgames),
    WON_IN_A_ROW(R.string.leaderboard_wongamesinarow);

    private final int leaderboardId;

    LEADERBOARD(@StringRes int leaderboardId) {
        this.leaderboardId = leaderboardId;
    }

    public String getLeaderboardId(final Context context) {
        return context.getString(leaderboardId);
    }

}

Introduce Leaderboard class for holding internal ids


/*
 * #%L
 * ImageJ server for RESTful access to ImageJ.
 * %%
 * Copyright (C) 2013 - 2016 Board of Regents of the University of
 * Wisconsin-Madison.
 * %%
 * 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.
 * #L%
 */

package net.imagej.server.console;

import java.util.LinkedList;

import net.imagej.server.ImageJServer;
import net.imagej.server.ImageJServerService;

import org.scijava.console.AbstractConsoleArgument;
import org.scijava.console.ConsoleArgument;
import org.scijava.object.ObjectService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

/**
 * Handles the {@code --server} argument to signal that an ImageJ Server
 * should be started immediately when ImageJ launches.
 *
 * @author Curtis Rueden
 */
@Plugin(type = ConsoleArgument.class)
public class ServerArgument extends AbstractConsoleArgument {

	@Parameter(required = false)
	private ImageJServerService imagejServerService;

	@Parameter(required = false)
	private ObjectService objectService;

	// -- Constructor --

	public ServerArgument() {
		super(1, "--server");
	}

	// -- ConsoleArgument methods --

	@Override
	public void handle(final LinkedList<String> args) {
		if (!supports(args)) return;

		args.removeFirst(); // --server

		final ImageJServer server = imagejServerService.start();
		objectService.addObject(server);
	}
	// -- Typed methods --

	@Override
	public boolean supports(final LinkedList<String> args) {
		return imagejServerService != null && objectService != null &&
			super.supports(args);
	}
}

Add --server command line flag

Add --server command line flag


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

package org.tinylog.core.formatters;

/**
 * Message formatter can replace placeholders with real values in strings.
 */
public interface MessageFormatter {

	/**
	 * Replaces all placeholders with real values.
	 *
	 * @param message
	 *            Text message with placeholders
	 * @param arguments
	 *            Replacements for placeholders
	 * @return Formatted text message
	 */
	String format(String message, Object[] arguments);

}

Add interface for message formatters

Add interface for message formatters


package myservlet;
import org.junit.*;
import org.amc.servlet.model.*;
import static org.junit.Assert.*;

public class TestMouldClosingData
{
	@Test
	public void testGetMouldClosingTimeData()
	{
		int i=0;
		while(i<1000)
		{
			MouldingProcess p=new MouldingProcess();
			float openlimit=420f;
			float mouldClosingLimitPos=openlimit-(20*(float)Math.random());
			float mouldClosedLimitPos=mouldClosingLimitPos-(200*(float)Math.random());
			float clsSlowPos=mouldClosedLimitPos-(100*(float)Math.random());
			float clsSPPos=clsSlowPos-(clsSlowPos*(float)Math.random());
			p.setMouldClosingOpenLimitPos(mouldClosingLimitPos);
			p.setMouldClosedLimitPos(mouldClosedLimitPos);
			p.setClsSlowPos(clsSlowPos);
			p.setClsSPPos(clsSPPos);

			float mouldClosingOpenLimitSpeed=420*(float)Math.random();
			float mouldClosedLimitSpeed=420*(float)Math.random();
			float clsSPSpeed=100*(float)Math.random();

			p.setMouldClosingOpenLimitSpeed(mouldClosingOpenLimitSpeed);
			p.setMouldClosedLimitSpeed(mouldClosedLimitSpeed);
			p.setClsSPSpeed(clsSPSpeed);

			float[][] data=MouldingProcessUtil.getMouldClosingTimeData(p);
			float result=0f;
			System.out.printf("Expected:%f + %f + %f + %f = %f%n",mouldClosingLimitPos-mouldClosedLimitPos,mouldClosedLimitPos-clsSlowPos,clsSlowPos-clsSPPos,clsSPPos,(mouldClosingLimitPos-mouldClosedLimitPos)+(mouldClosedLimitPos-clsSlowPos)+(clsSlowPos-clsSPPos)+(clsSPPos));
			System.out.print("Actual:");
			for(float[] t:data)
			{
				result+=t[1];
				System.out.printf("%f +",t[1]);
			}
			System.out.printf("=%f%n", result);
			System.out.printf("(%d)Expected:%f,Actual:%f%n",i,mouldClosingLimitPos,result);
			assertEquals(mouldClosingLimitPos,result,0.01);
			i++;
		}
	}

}

Create test case for MouldOpening Chart

Create test case for MouldOpening Chart


/*
 * Java Genetic Algorithm Library (@__identifier__@).
 * Copyright (c) @__year__@ Franz Wilhelmstötter
 *
 * 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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Author:
 *     Franz Wilhelmstötter (franz.wilhelmstoetter@gmx.at)
 *
 */
package org.jenetics.util;

/**
 * This implementation is not thread-safe.
 *
 *
 * @author Franz Wilhelmstötter
 * @since 1.1
 * @version 1.1 — $Date: 2012-11-16 $
 */
public class HQ64Random {

}

Implement PRNG recommended by 'Numerical Recipes'.


package com.haxademic.core.ui;

import com.haxademic.core.app.P;
import com.haxademic.core.debug.DebugUtil;

import processing.event.KeyEvent;

public class CursorToggle {

	protected boolean isHidden;

	public CursorToggle(boolean defaultHidden) {
		if(P.p == null) DebugUtil.printErr("===========\n Please wait until setup() to init CursorToggle \n===========");
		isHidden = defaultHidden;
		P.p.registerMethod("keyEvent", this);
	}

	public void keyEvent(KeyEvent e) {
		if(e.getKey() == 'm') isHidden = !isHidden;
		if(isHidden == true) {
			P.p.noCursor();
		} else {
			P.p.cursor();
		}
	}

}

Add cursor toggle key listener object

Add cursor toggle key listener object


package leetcode.ugly_number_ii;

public class Solution {
    public int nthUglyNumber(int n) {
        int[] ugly = new int[1691];
        int ug_2 = 0, ug_3 = 0, ug_5 = 0;
        ugly[0] = 1;
        for(int i = 1; i < 1691; i++){
            int nxt = Math.min(ugly[ug_2] * 2, Math.min(ugly[ug_3] * 3, ugly[ug_5] * 5));
            ugly[i] = nxt;
            if(nxt == ugly[ug_2] * 2) ug_2++;
            if(nxt == ugly[ug_3] * 3) ug_3++;
            if(nxt == ugly[ug_5] * 5) ug_5++;
        }
        return ugly[n - 1];
    }
}

Add java solution for 264. Ugly Number II

264. Ugly Number II: https://leetcode.com/problems/ugly-number-ii/


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

import java.util.ServiceLoader;

/**
 * @author David BRASSELY (david at gravitee.io)
 * @author GraviteeSource Team
 */
public final class ServiceLoaderHelper {

    public static <T> T loadFactory(Class<T> clazz) {
        ServiceLoader<T> factories = ServiceLoader.load(clazz);
        if (factories.iterator().hasNext()) {
            return factories.iterator().next();
        } else {
            factories = ServiceLoader.load(clazz, ServiceLoaderHelper.class.getClassLoader());
            if (factories.iterator().hasNext()) {
                return factories.iterator().next();
            } else {
                throw new IllegalStateException("Cannot find META-INF/services/" + clazz.getName() + " on classpath");
            }
        }
    }
}

Add a service loader helper

feat(service): Add a service loader helper


package net.imagej.ops.viewOp;

import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.ExtendPeriodic;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.view.ExtendedRandomAccessibleInterval;
import net.imglib2.view.Views;

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

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

Add default implementation of ExtendPeriodic interface.


import java.net.*;
import java.io.*;
import java.net.URLEncoder;

public class ServletTest {
  public static void main(String[] args) throws Exception {
	String param = "Hopefully this is a successful testing of language translation POC";
	System.out.println(URLEncoder.encode(param, "UTF-8"));
    URL yahoo = new URL("https://clarkjavaliberty.mybluemix.net/SimpleServlet?content=" + URLEncoder.encode(param, "UTF-8"));
    URLConnection yc = yahoo.openConnection();
    //BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()), "UTF-8");
	InputStreamReader isr = new InputStreamReader(yc.getInputStream(), "UTF-8");
	BufferedReader in = new BufferedReader(isr);
    String inputLine;
    while ((inputLine = in.readLine()) != null)
        System.out.println(inputLine);
    in.close();
  }
}

Include java file to invoke SimpleServlet

Include java file to invoke SimpleServlet


package com.splunk.shep.customsearch;

import java.net.URI;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class HDFSCat {

    public static void main(String args[]) {
	try {
	    Configuration conf = new Configuration();
	    URI fileuri = URI.create(args[0]);
	    String host = fileuri.getHost();
	    int port = fileuri.getPort();
	    FileSystem fs = FileSystem.get(
		    URI.create("hdfs://" + host + ":" + port), conf);
	    Path filenamePath = new Path(args[0]);
	    if (!fs.exists(filenamePath)) {
		System.exit(1);
	    }
	    FSDataInputStream in = fs.open(filenamePath);
	    while (true) {
		String line = in.readLine();
		if (line == null) {
		    break;
		}
		System.out.println(line);
	    }
	    in.close();
	} catch (Exception e) {
	    e.printStackTrace();
	    System.exit(2);
	}
	System.exit(0);
    }
}

Use to cat an HDFS file

Use to cat an HDFS file


package com.github.aureliano.edocs.app.gui.menu;

import javax.swing.JMenuItem;

public class CloseAllTabsMenuItem extends JMenuItem {

	private static final long serialVersionUID = 5402503871207802801L;

	public CloseAllTabsMenuItem() {
		super.setText("Close all");
	}
}

Create close all tabs menu item.

Create close all tabs menu item.


package nanomsg;

import java.lang.Runnable;
import nanomsg.NativeLibrary;

public class Device implements Runnable {
    private final int sourceSocket;
    private final int destSocket;

    public Device(final int sourceSocket, final int destSocket) {
        this.sourceSocket = sourceSocket;
        this.destSocket = destSocket;
    }

    public void run() {
        NativeLibrary.nn_device(sourceSocket, destSocket);
    }
}

Add device support to java bindings.

Add device support to java bindings.


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

import javax.servlet.sip.SipErrorEvent;
import javax.servlet.sip.SipErrorListener;

public class Listener implements SipErrorListener
{

	public void noAckReceived(SipErrorEvent arg0)
	{
	}

	public void noPrackReceived(SipErrorEvent arg0)
	{
	}

}

Fix CIPANGO-139: cipango-plus is broken

Fix CIPANGO-139: cipango-plus is broken


package me.haosdent.cgroup.util;

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

public class TestShell {

  @Before
  public void setUp() {}

  @After
  public void tearDown() {}

  @Test
  public void testExec() {}

  @Test
  public void testMount() {}

  @Test
  public void testUmount() {}
}

Add shell util test class.

Add shell util test class.


package de.timroes.axmlrpc.serializer;

import static org.junit.Assert.*;

import java.util.Date;

import org.junit.Test;

import de.timroes.axmlrpc.xmlcreator.XmlElement;

public class TestSerializers {

	@Test
	public void canSerializeBase64(){
		assertExpectedSerialized("<base64>AQIDBA==</base64>", new Base64Serializer().serialize(new Byte[]{1, 2, 3, 4}));
	}

	@Test
	public void canSerializeBoolean(){
		assertExpectedSerialized("<boolean>1</boolean>", new BooleanSerializer().serialize(true));
		assertExpectedSerialized("<boolean>0</boolean>", new BooleanSerializer().serialize(false));
	}

	@Test
	public void canSerializeDouble(){
		assertExpectedSerialized("<double>3.2</double>", new DoubleSerializer().serialize(3.2));
	}

	@Test
	public void canSerializeDate(){
		assertExpectedSerialized("<dateTime.iso8601>19850503T122334</dateTime.iso8601>",
				new DateTimeSerializer().serialize(new Date(85, 4, 3, 12, 23, 34)));
	}

	@Test
	public void canSerializeInt(){
		assertExpectedSerialized("<int>4</int>", new IntSerializer().serialize(4));
	}

	@Test
	public void canSerializeLong(){
		assertExpectedSerialized("<i8>1234</i8>", new LongSerializer().serialize(1234L));
	}

	@Test
	public void canSerializeNullElement(){
		assertExpectedSerialized("<nil/>", new NullSerializer().serialize(null));
	}

	@Test
	public void canSerializeString(){
		boolean encodeString = true;
		assertExpectedSerialized("<string>te<&>st</string>", new StringSerializer(encodeString, true).serialize("te<&>st"));

		encodeString = false;
		assertExpectedSerialized("<string>te<&>st</string>", new StringSerializer(encodeString, true).serialize("te<&>st"));
	}

	private static void assertExpectedSerialized(String expected, XmlElement actual){
		assertEquals(expected, actual.toString().trim());
	}
}

Add some unit tests on serializers

Add some unit tests on serializers


/*
 Copyright (C) 2003 EBI, GRL

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

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

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

import java.sql.Connection;

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

/**
 * Check that the gene_stable_id table is populated in EST databases.
 */

public class ESTStableIDs extends SingleDatabaseTestCase {

    /**
     * Create a new ESTStableIDs testcase.
     */
    public ESTStableIDs() {

        addToGroup("post_genebuild");
        addToGroup("release");
        setDescription("Check the gene_stable_id table is populated in EST databases.");

    }

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

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

    }

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

        boolean result = true;

	Connection con = dbre.getConnection();

	int rows = getRowCount(con, "SELECT COUNT(*) FROM gene_stable_id");

	if (rows == 0) {
	    ReportManager.problem(this, con, "gene_stable_id is empty");
	    return false;
	} else {
	    ReportManager.correct(this, con, "gene_stable_id has " + rows + " rows");
	}

        return result;

    } // run

} // ESTStableIDs

Check that the gene_stable_id table is populated in EST databases (needs to be a separate healthcheck from StableIDs since this is required at a different point in the release process).


/*
 * Copyright 2019, TeamDev. All rights reserved.
 *
 * Redistribution and use in source and/or binary forms, with or without
 * modification, must retain the above copyright notice and the following
 * disclaimer.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package io.spine.validate.diags;

import com.google.common.collect.ImmutableList;
import com.google.common.testing.NullPointerTester;
import com.google.common.truth.StringSubject;
import com.google.protobuf.Timestamp;
import io.spine.base.FieldPath;
import io.spine.base.FieldPaths;
import io.spine.type.TypeName;
import io.spine.validate.ConstraintViolation;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

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

@DisplayName("ViolationText should")
class ViolationTextTest {

    @Test
    @DisplayName("not accept null violations")
    void nullTolerance() {
        new NullPointerTester()
                .testAllPublicStaticMethods(ViolationText.class);
    }

    @Test
    @DisplayName("include type info in the violation text")
    void includeType() {
        TypeName type = TypeName.of(Timestamp.class);
        ConstraintViolation violation = ConstraintViolation
                .newBuilder()
                .setTypeName(type.value())
                .build();
        ViolationText text = ViolationText.of(violation);
        assertThat(text.toString()).contains(type.value());
    }

    @Test
    @DisplayName("include field info in the violation text")
    void includeField() {
        FieldPath field = FieldPaths.parse("msg.foo.bar");
        ConstraintViolation violation = ConstraintViolation
                .newBuilder()
                .setFieldPath(field)
                .build();
        ViolationText text = ViolationText.of(violation);
        assertThat(text.toString()).contains(FieldPaths.toString(field));
    }

    @Test
    @DisplayName("compile tests for many violations into one")
    void compileManyTexts() {
        ConstraintViolation first = ConstraintViolation
                .newBuilder()
                .setMsgFormat("Errored with a message")
                .build();
        ConstraintViolation second = ConstraintViolation
                .newBuilder()
                .setMsgFormat("Messaged with an error")
                .build();
        String text = ViolationText.ofAll(ImmutableList.of(first, second));
        StringSubject assertText = assertThat(text);
        assertText.contains(ViolationText.of(first).toString());
        assertText.contains(ViolationText.of(second).toString());
    }
}

Add a test for ViolationText.

Add a test for ViolationText.


package to.etc.function;

/**
 * @author Frits Jalvingh
 * Created on 26-1-19.
 */
@FunctionalInterface
public interface RunnableEx {
	void run() throws Exception;
}

[remote] Convert all of the HubServer packets so far to protobufs, and implement core message response structures.


package com.erudika.scoold.utils.avatars;

public enum AvatarFormat {
	Square25,
	Square32,
	Square50,
	Square127,
	Profile,
}

Add enum for each size already use

Add enum for each size already use


/**
 * @author Johannes Donath
 */

@Volatile
package org.basinmc.faucet.event;

import org.basinmc.faucet.internal.warn.Volatile;

Mark the entire event API volatile for now as we will probably twiddle its bits a few more times.


package com.proofpoint.log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

public class LoggingWriter extends StringWriter
{
    private final Logger logger;
    private final Type type;

    public enum Type
    {
        DEBUG,
        INFO
    }

    public LoggingWriter(Logger logger, Type type)
    {
        this.logger = logger;
        this.type = type;
    }

    @Override
    public void close() throws IOException
    {
        flush();
        super.close();
    }

    @Override
    public void flush()
    {
        BufferedReader  in = new BufferedReader(new StringReader(getBuffer().toString()));
        for(;;)
        {
            try
            {
                String      line = in.readLine();
                if ( line == null )
                {
                    break;
                }

                switch ( type )
                {
                    default:
                    case DEBUG:
                    {
                        if ( logger.isDebugEnabled() )
                        {
                            logger.debug(line);
                        }
                        break;
                    }

                    case INFO:
                    {
                        if ( logger.isInfoEnabled() )
                        {
                            logger.info(line);
                        }
                        break;
                    }
                }
            }
            catch ( IOException e )
            {
                throw new Error(e); // should never get here
            }
        }

        getBuffer().setLength(0);
    }

    public void printMessage(String message, Object... args) throws IOException
    {
        write(String.format(message, args) + "\n");
    }
}

Revert "no longer needed". Actually used by Bootstrap

This reverts commit 1fd95b01066ef8b72ae11201ea1797dc9d7a4a21.


package fr.openium.blinkiumandroid;

import org.junit.Test;

import java.util.Arrays;

import fr.openium.blinkiumandroid.utils.ConvertUtils;

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

/**
 * Created by ogoutet on 15/03/2017.
 */

public class ConvertUtilsTest {

    @Test
    public void testAsciiToBinWithSimpleChar(){
        // expect
        byte[] expected = {0,1,1,0,0,0,0,1};
        //when
        byte[] result = ConvertUtils.asciiToBin('a');
        //assert
        assertTrue(Arrays.equals(expected,result));
    }

    @Test
    public void testAsciiToBinNulChar(){
        // expect
        byte[] expected = {0,0,0,0,0,0,0,0};
        //when
        byte[] result = ConvertUtils.asciiToBin(Character.MIN_VALUE);
        //assert
        assertTrue(Arrays.equals(expected,result));
    }

    @Test
    public void testAsciiToBinMaxAsciiChar(){
        // expect
        byte[] expected = {0,1,1,1,1,1,1,1};
        //when
        byte[] result = ConvertUtils.asciiToBin((char)127);
        //assert
        assertTrue(Arrays.equals(expected,result));
    }

    @Test
    public void testAsciiToBinUnhadledChar(){
        // expect
        byte[] expected = {0,1,1,1,1,1,1,1};
        //when
        byte[] result = ConvertUtils.asciiToBin('\u24d4');
        //assert
        assertTrue(Arrays.equals(expected,result));
    }
}

Add of the first tests of the ConvertUtils class


package com.elastisys.scale.cloudpool.api;

import com.google.gson.annotations.SerializedName;

/**
 * Supported cloud pool protocols.
 */
public enum Protocol {
    /** HTTP protocol. */
    @SerializedName("http")
    HTTP("http"),
    /** HTTPS protocol. */
    @SerializedName("https")
    HTTPS("https");

    /** The protocol name to use in URIs. */
    private final String protocolName;

    Protocol(String protocolName) {
        this.protocolName = protocolName;
    }

    /**
     * The protocol name to use in URIs. For example, "http".
     *
     * @return
     */
    public String getProtocolName() {
        return this.protocolName;
    }
}

Add supported protocols enum in api

Add supported protocols enum in api


package com.google.sps.utilities;

import com.google.sps.data.Event;
import com.google.sps.data.User;
import com.google.sps.data.VolunteeringOpportunity;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class EventRanker {
  /**
   * Sorts events based on each event's score.
   * Breaks ties with the event's number of VolunteeringOpportunity
   * requiredSkills that match the user's skills.
   *
   * @param user The user for whom the events are ranked
   * @param unrankedEvents A {@link Set} of events that need to be ranked
   * @return A {@link List} of events that is ranked according to
   * each element's score
   */
  public List<Event> rankEvents(User user, Set<Event> unrankedEvents) {
    return new ArrayList<>();
  }
}

Change event ranker class name

Change event ranker class name


package com.sunny.grokkingalgorithms.fasttrack.treesandgraphs;

import com.sunny.grokkingalgorithms.ctci.c4.util.BinaryTreeNode;
import com.sunny.grokkingalgorithms.ctci.c4.util.TreeUtils;

/**
 * Created by sundas on 6/10/2018.
 */
public class InsertANodeInABST {

  /*
  Insert a node in a binary search tree
   */

  /**
   *
   * @param root
   */
   public static void insertIntoBST(BinaryTreeNode root,int key,BinaryTreeNode parent,boolean leftChild){
     /*
     Essentially find an empty spot and insert it , fullfiling the BST criteria.
      */
     if(root == null){
       BinaryTreeNode node = new BinaryTreeNode();
       node.data = key;
       /*
       We need to know the direction
        */
       if(parent != null){
         if(leftChild){
           parent.left = node;
         }
         else{
           parent.right = node;
         }
       }
       return;
     }
     if(root.data == key){
       return;
     }
     /*
     Go left
      */
     if(key < root.data){
       insertIntoBST(root.left,key,root,true);
     }
     /*
     Go right
      */
     else{
       insertIntoBST(root.right,key,root,false);
     }
   }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    BinaryTreeNode root = TreeUtils.createBST();
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    insertIntoBST(root, 12, null, false);
    System.out.println("Inserting 12");
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    System.out.println("Inorder traversal");
    TreeUtils.inorder(root);
    insertIntoBST(root, 2, null, false);
    System.out.println("Inserting 12");
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    System.out.println("Inorder traversal");
    TreeUtils.inorder(root);
    insertIntoBST(root, 8, null, false);
    System.out.println("Inserting 8");
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    System.out.println("Inorder traversal");
    TreeUtils.inorder(root);
    insertIntoBST(root, 1, null, false);
    System.out.println("Inserting 1");
    TreeUtils.performBfsLevelMarker(root);
    System.out.println("############################");
    System.out.println("Inorder traversal");
    TreeUtils.inorder(root);
  }

}

Insert into BST recursive , O(N) worst case , O(logn) for balanced BST.


public class Solution {

    public static int countSegments(String s) {

        int spaceCount = 0;

        s += " ";

        for (int i = 1; i < s.length(); i++) {

            if (s.charAt(i) == ' ' && s.charAt(i - 1) != ' ') {
                spaceCount++;
            }

        }

        return spaceCount;

    }

}

Create : 434 Number of Segments in a String


/*
 * Copyright (C) 2014 Klaus Reimer <k@ailis.de>
 * See LICENSE.md for licensing information.
 */

package org.usb4java;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
 * Tests the {@link LibUsbException} class.
 *
 * @author Klaus Reimer (k@ailis.de)
 */
public class LibUsbExceptionTest
{
    /**
     * Tests the constructor with only an error code.
     */
    @Test
    public void testConstructorWithCode()
    {
        final LibUsbException e =
            new LibUsbException(LibUsb.ERROR_INVALID_PARAM);
        assertEquals(LibUsb.ERROR_INVALID_PARAM, e.getErrorCode());
        assertEquals("USB error 2: Invalid parameter", e.getMessage());

    }

    /**
     * Tests the constructor with an error code and a message.
     */
    @Test
    public void testConstructorWithCodeAndMessage()
    {
        final LibUsbException e =
            new LibUsbException("Custom message", LibUsb.ERROR_INVALID_PARAM);
        assertEquals(LibUsb.ERROR_INVALID_PARAM, e.getErrorCode());
        assertEquals("USB error 2: Custom message: Invalid parameter",
            e.getMessage());

    }
}

Add unit test for LibUsbException class.


package seedu.ezdo.model.task;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;

import seedu.ezdo.model.tag.UniqueTagList;
import seedu.ezdo.model.todo.DueDate;
import seedu.ezdo.model.todo.Name;
import seedu.ezdo.model.todo.Priority;
import seedu.ezdo.model.todo.StartDate;
import seedu.ezdo.model.todo.Task;
import seedu.ezdo.model.todo.UniqueTaskList;
import seedu.ezdo.model.todo.UniqueTaskList.SortCriteria;
//@@author A0139248X
@RunWith(PowerMockRunner.class)
public class UniqueTaskListEnumTest {

    private UniqueTaskList utl = new UniqueTaskList();

    @Test(expected = AssertionError.class)
    @PrepareForTest(SortCriteria.class)
    public void unknownValueShouldThrowException() throws Exception {
        utl.add(new Task(new Name("lol"), new Priority("1"), new StartDate("today"), new DueDate("tomorrow"),
                new UniqueTagList("jesus")));
        utl.add(new Task(new Name("lasdfol"), new Priority("1"), new StartDate("today"), new DueDate("tomorrow"),
                new UniqueTagList("jesus")));

        SortCriteria C = PowerMockito.mock(SortCriteria.class);
        Whitebox.setInternalState(C, "name", "C");
        Whitebox.setInternalState(C, "ordinal", 4);

        PowerMockito.mockStatic(SortCriteria.class);
        PowerMockito.when(SortCriteria.values()).thenReturn(new SortCriteria[]{SortCriteria.NAME, SortCriteria.PRIORITY,
                SortCriteria.DUE_DATE, SortCriteria.START_DATE, C});

        utl.sortTasks(C, true);
    }
}

Create SortCriteria enum test for UniqueTaskList


package uk.ac.edukapp.renderer;

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

import uk.ac.edukapp.model.Widgetprofile;

public class UploadResults {

	private String uploadMessage;
	private Widgetprofile widgetProfile;
	private String widgetFolderPath;
	private List<String> htmlFileList;

	/**
	 * @return the uploadMessage
	 */
	public String getUploadMessage() {
		return uploadMessage;
	}

	/**
	 * @param uploadMessage the uploadMessage to set
	 */
	public void setUploadMessage(String uploadMessage) {
		this.uploadMessage = uploadMessage;
	}

	/**
	 * @return the widgetProfile
	 */
	public Widgetprofile getWidgetProfile() {
		return widgetProfile;
	}

	/**
	 * @param widgetProfile the widgetProfile to set
	 */
	public void setWidgetProfile(Widgetprofile widgetProfile) {
		this.widgetProfile = widgetProfile;
	}

	/**
	 * @return the widgetFolderPath
	 */
	public String getWidgetFolderPath() {
		return widgetFolderPath;
	}

	/**
	 * @param widgetFolderPath the widgetFolderPath to set
	 */
	public void setWidgetFolderPath(String widgetFolderPath) {
		this.widgetFolderPath = widgetFolderPath;
	}

	public void setHTMLFileList ( List<File> inList ) {
		htmlFileList = new ArrayList<String>();
		for ( File f : inList ) {
			htmlFileList.add(f.getName());
		}
	}

	public List<String> getHtmlFileList() {
		return htmlFileList;
	}

}

Return object for the widget creator calls.


package jenkins.bugs;

import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;

import hudson.security.HudsonPrivateSecurityRealm;
import jenkins.model.Jenkins;

public class Jenkins41511Test {

    @BeforeClass
    public static void setUpClass() {
        System.setProperty(Jenkins.class.getName()+".slaveAgentPort", "10000");
        System.setProperty(Jenkins.class.getName()+".slaveAgentPortEnforce", "true");
    }

    @Rule
    public JenkinsRule j = new JenkinsRule();

    @Test
    public void configRoundTrip() throws Exception {
        Jenkins.getInstance().setSecurityRealm(new HudsonPrivateSecurityRealm(true, false, null));
        j.submit(j.createWebClient().goTo("configureSecurity").getFormByName("config"));
    }
}

Add a test showing the problem

[JENKINS-41511] Add a test showing the problem


package controllers;

import org.ow2.chameleon.wisdom.api.DefaultController;
import org.ow2.chameleon.wisdom.api.annotations.Controller;
import org.ow2.chameleon.wisdom.api.annotations.Route;
import org.ow2.chameleon.wisdom.api.http.HttpMethod;
import org.ow2.chameleon.wisdom.api.http.Result;

@Controller
public class Session extends DefaultController {

    // tag::session[]
    @Route(method= HttpMethod.GET, uri = "/session")
    public Result readSession() {
        String user = session("connected");
        if(user != null) {
            return ok("Hello " + user);
        } else {
            return unauthorized("Oops, you are not connected");
        }
    }
    // end::session[]

    // tag::login[]
    @Route(method= HttpMethod.GET, uri = "/session/login")
    public Result login() {
        String user = session("connected");
        if(user != null) {
            return ok("Already connected");
        } else {
            session("connected", "wisdom");
            return readSession();
        }
    }
    // end::login[]

    // tag::logout[]
    @Route(method= HttpMethod.GET, uri = "/session/logout")
    public Result logout() {
        session().remove("connected");
        return ok("You have been logged out");
    }
    // end::logout[]

    // tag::clear[]
    @Route(method= HttpMethod.GET, uri = "/session/clear")
    public Result clear() {
        session().clear();
        return ok("You have been logged out");
    }
    // end::clear[]

    // tag::flash[]
    @Route(method= HttpMethod.GET, uri = "/session/flash")
    public Result welcome() {
        String message = flash("success");
        if(message == null) {
            message = "Welcome!";
            flash("success", message);
        }
        return ok(message);
    }
    // end::flash[]
}

Add a session controller to support the documentation

Signed-off-by: Clement Escoffier <6397137e57d1f87002962a37058f2a1c76fca9db@gmail.com>


package org.apache.velocity.test.misc;

/*
 * Copyright 2006 The Apache Software Foundation.
 *
 * 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.
 */

public class UberspectorTestObject
{
    private String regular;
    private String premium;

    private boolean regularBool;
    private boolean premiumBool;

    private String ambigous;

    /**
     * @return the premium
     */
    public String getpremium()
    {
        return premium;
    }

    /**
     * @param premium the premium to set
     */
    public void setpremium(String premium)
    {
        this.premium = premium;
    }

    /**
     * @return the premiumBool
     */
    public boolean ispremiumBool()
    {
        return premiumBool;
    }

    /**
     * @param premiumBool the premiumBool to set
     */
    public void setpremiumBool(boolean premiumBool)
    {
        this.premiumBool = premiumBool;
    }

    /**
     * @return the regular
     */
    public String getRegular()
    {
        return regular;
    }

    /**
     * @param regular the regular to set
     */
    public void setRegular(String regular)
    {
        this.regular = regular;
    }

    /**
     * @return the regularBool
     */
    public boolean isRegularBool()
    {
        return regularBool;
    }

    /**
     * @param regularBool the regularBool to set
     */
    public void setRegularBool(boolean regularBool)
    {
        this.regularBool = regularBool;
    }

    /**
     * @return the ambigous
     */
    public String getAmbigous()
    {
        return ambigous;
    }

    /**
     * @param ambigous the ambigous to set
     */
    public void setAmbigous(String ambigous)
    {
        this.ambigous = ambigous;
    }

    /**
     * @param ambigous the ambigous to set
     */
    public void setAmbigous(StringBuffer ambigous)
    {
        this.ambigous = ambigous.toString();
    }
}

Test Object for the UberspectorTestCase

Test Object for the UberspectorTestCase

git-svn-id: 10199add9e99fdfd09a887e21850bf0d170bc390@440845 13f79535-47bb-0310-9956-ffa450edef68


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

package c5db.util;

import com.google.common.collect.Iterators;

import java.util.Iterator;

public class C5Iterators {

  /**
   * Lazily advance the passed Iterator the given number of times. A lazy variant of
   * {@link com.google.common.collect.Iterators#advance}
   *
   * @return A new Iterator object representing the given Iterator advanced a specified
   * number of times, calling the given Iterator's next() method when needed.
   */
  public static <T> Iterator<T> advanced(Iterator<T> backingIterator, int numberToAdvance) {
    return new Iterator<T>() {
      private boolean advanced;

      @Override
      public boolean hasNext() {
        lazilyAdvance();
        return backingIterator.hasNext();
      }

      @Override
      public T next() {
        lazilyAdvance();
        return backingIterator.next();
      }

      @Override
      public void remove() {
        lazilyAdvance();
        backingIterator.remove();
      }

      private void lazilyAdvance() {
        if (!advanced) {
          Iterators.advance(backingIterator, numberToAdvance);
          advanced = true;
        }
      }
    };
  }
}

Add a lazy Iterator advance method

Add a lazy Iterator advance method


/*
 * Copyright (c) 2009 Kathryn Huxtable and Kenneth Orr.
 *
 * This file is part of the SeaGlass Pluggable Look and Feel.
 *
 * 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.
 *
 * $Id$
 */
package com.seaglasslookandfeel.state;

import java.awt.Component;
import java.awt.Container;

import javax.swing.JComponent;
import javax.swing.JToolBar;

/**
 * Is the control in a toolbar?
 */
public class ControlInToolBarState extends State {
    public ControlInToolBarState() {
        super("InToolBar");
    }

    public boolean isInState(JComponent c) {
        for (Component comp = (Component) c; comp != null; comp = ((Container) comp).getParent()) {
            if (comp instanceof JToolBar) {
                return true;
            } else if (!(comp instanceof Container)) {
                break;
            }
        }
        return false;
    }
}

Check in state to determine if a control is in a toolbar.


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

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 DeleteListNodeTest {

  private DeleteListNode deleteNode;

  @Before public void setUp() {
    deleteNode = new DeleteListNode();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullNodes() {
    deleteNode.delete(null);
  }

  @Test public void shouldNotModifyNodeIfListContainsJustThatNode() {
    ListNode<Integer> head = new ListNode<Integer>(1);

    deleteNode.delete(head);

    assertEquals(head, head);
  }

  @Test public void shouldRemoveListNode() {
    ListNode<Integer> head = new ListNode<Integer>(0);
    ListNode<Integer> n1 = new ListNode<Integer>(1);
    ListNode<Integer> n2 = new ListNode<Integer>(2);
    head.setNext(n1);
    n1.setNext(n2);

    deleteNode.delete(n1);

    assertListContainsElements(new Integer[] { 0, 2 }, head);
  }

  @Test public void shouldRemoveHead() {
    ListNode<Integer> head = new ListNode<Integer>(0);
    ListNode<Integer> n1 = new ListNode<Integer>(1);
    ListNode<Integer> n2 = new ListNode<Integer>(2);
    head.setNext(n1);
    n1.setNext(n2);

    deleteNode.delete(head);

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

  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 59

Add some tests to problem 59


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

package org.apache.lenya.cms.publication;

import java.util.List;

/**
 * @version $Id: PublicationHelper.java,v 1.1 2004/08/26 22:18:19 roku Exp $
 */
public final class PublicationHelper {

    private Publication publication;

    public PublicationHelper(Publication publication) {
        this.publication = publication;
    }

    /**
     * Returns all documents of a publication.
     * @param area
     * @return
     * @see Document
     * @see Publication
     */
    public Document[] getAllDocuments(String area, String language) throws DocumentException {
        try {
            List allNodes = getPublication().getSiteTree(area).getNode("/").preOrder();
            Document[] documents = new Document[allNodes.size()-1];

            for(int i=1; i<allNodes.size(); i++) {
                documents[i-1] = DefaultDocumentBuilder.getInstance().createDocument(getPublication(), area,
                        ((SiteTreeNode)allNodes.get(i)).getAbsoluteId(), language);
            }
            return documents;
        } catch(SiteTreeException e) {
            throw new DocumentException("Can not access sitetree to get document ids.", e);
        } catch(DocumentBuildException e) {
            throw new DocumentException("Can not build document from id obtained from sitetree.", e);
        }
    }

    /**
     * @return Returns the publication.
     */
    public Publication getPublication() {
        return publication;
    }
}

Support for getting al docs from a pub via sitetree

git-svn-id: f6f45834fccde298d83fbef5743c9fd7982a26a3@43283 13f79535-47bb-0310-9956-ffa450edef68


import com.messagebird.MessageBirdClient;
import com.messagebird.MessageBirdService;
import com.messagebird.MessageBirdServiceImpl;
import com.messagebird.exceptions.GeneralException;
import com.messagebird.exceptions.UnauthorizedException;
import com.messagebird.objects.conversations.*;

public class ExampleUpdateConversation {

    public static void main(String[] args) {
        if (args.length < 3) {
            System.out.println("Please specify your access key, the ID of a conversation and the status to update the conversation to." +
                    " Example : java -jar <this jar file> test_accesskey test_conversationId archived");
            return;
        }

        // First create your service object
        final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]);

        // Add the service to the client
        final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr);
        final ConversationStatus newStatus = ConversationStatus.forValue(args[2]);
        try {
            final Conversation response = messageBirdClient.updateConversation(args[1], newStatus);
            // Display message response
            System.out.println(response.toString());
        } catch (UnauthorizedException | GeneralException exception) {
            if (exception.getErrors() != null) {
                System.out.println(exception.getErrors().toString());
            }
            exception.printStackTrace();
        }
    }
}

Add example for updating conversation.

Add example for updating conversation.


package org.apache.camel.component.restlet;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.util.jsse.KeyManagersParameters;
import org.apache.camel.util.jsse.KeyStoreParameters;
import org.apache.camel.util.jsse.SSLContextParameters;

import org.junit.Test;

import java.io.File;

/**
 * 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.
 */
public class RestletProducerSSLTest extends RestletTestSupport {

	public static final String BODY = "some body";

	@Override
	protected JndiRegistry createRegistry() throws Exception {

		SSLContextParameters sslContextParameters = createSSLContext();

		JndiRegistry registry = super.createRegistry();
		registry.bind("mySSLContextParameters", sslContextParameters);

		return registry;
	}

	@Test
	public void testRestletProducerComponentSSL() throws Exception {
		String out = template.requestBody("direct:startWithEndpointSSL", "neco", String.class);
		assertEquals(BODY, out);
	}

	@Override
	protected RouteBuilder createRouteBuilder() throws Exception {
		return new RouteBuilder() {
			@Override
			public void configure() throws Exception {
				from("direct:startWithEndpointSSL").to("restlet:https://localhost:" + portNum + "/?restletMethod=post&sslContextParameters=#mySSLContextParameters");

				from("restlet:https://localhost:" + portNum + "/?restletMethods=post&sslContextParameters=#mySSLContextParameters")
						.process(new Processor() {
							public void process(Exchange exchange) throws Exception {
								exchange.getOut().setBody(BODY);
							}
						});
			}
		};
	}

	protected SSLContextParameters createSSLContext() {
		KeyStoreParameters ksp = new KeyStoreParameters();
		ksp.setResource(new File("src/test/resources/jsse/localhost.ks").getAbsolutePath());
		ksp.setPassword("changeit");

		KeyManagersParameters kmp = new KeyManagersParameters();
		kmp.setKeyPassword("changeit");
		kmp.setKeyStore(ksp);

		SSLContextParameters sslContextParameters = new SSLContextParameters();
		sslContextParameters.setKeyManagers(kmp);

		return sslContextParameters;
	}
}

[CAMEL-12744] Test SSL communication on Restlet producer


package uk.ac.ebi.quickgo.annotation.validation;

import javax.validation.ConstraintValidatorContext;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationContextLoader;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;

/**
 * @author Tony Wardell
 * Date: 22/11/2016
 * Time: 09:38
 * Created with IntelliJ IDEA.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MockValidationConfig.class, loader = SpringApplicationContextLoader.class)
@ActiveProfiles(profiles = MockValidationConfig.DB_REF_VALIDATION_SUCCEEDS)
public class ReferenceValuesValidationIT {

    @Autowired
    ReferenceValuesValidation refValidator;
    private ConstraintValidatorContext mockContext;

    @Before
    public void setup(){
        mockContext = mock(ConstraintValidatorContext.class);
    }

    @Test
    public void validationSucceedsIfKnownDb(){
        assertThat(refValidator.isValid(new String[]{"PMID:123456"}, mockContext), is(true));
    }

    @Test
    public void validationSucceedsIfDbNotSpecified(){
        assertThat(refValidator.isValid(new String[]{"123456"}, mockContext), is(true));
    }

    @Test
    public void validationSucceedsIfArgumentListIsNull(){
        assertThat(refValidator.isValid(null, mockContext), is(true));
    }

    @Test
    public void validationFailsIfUnknownDb(){
        assertThat(refValidator.isValid(new String[]{"XXXX:123456"}, mockContext), is(false));
    }

    @Test(expected = IllegalArgumentException.class)
    public void validationFailsIfArgumentListContainsNull(){
       refValidator.isValid(new String[]{null}, mockContext);
    }
}

Test for validation of Reference values for annotation filtering.


package in.co.nebulax.maestro.utils;

public class Subjects {

	public static String[][] subjects = new String[][] {

			// Class 1
			{ "English", "Hindi", "Maths", "E.V.S" },

			// Class 2
			{ "English", "Hindi", "Maths", "E.V.S" },

			// Class 3
			{ "English", "Hindi", "Maths", "E.V.S", "Social Studies" },

			// Class 4
			{ "English", "Hindi", "Maths", "Science", "Social Studies" },

			// Class 5
			{ "English", "Hindi", "Maths", "Science", "Social Studies" },

			// Class 6
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 7
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 8
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 9
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 10
			{ "English", "Hindi", "Maths", "Science", "Social Studies",
					"Sanskrit" },

			// Class 11
			{ "English", "Hindi", "Maths", "Physics", "Chemistry",
					"Accountancy", "Business Studies", "Political Science",
					"History" },

			// Class 12
			{ "English", "Hindi", "Maths", "Physics", "Chemistry",
					"Accountancy", "Business Studies", "Political Science",
					"History" }, };
}

Add subjects according to class

Add subjects according to class


/**
 * Let's make our magic 8 ball game work repeatedly!
 * Maybe we'll even allow exiting...
 */
package com.comp110.lecture10;

import java.util.Scanner;

public class Magic8BallRedux {

  public static void main(String[] args) {

    System.out.println("Ask me a yes/no question...");
    Scanner keyboard = new Scanner(System.in);
    keyboard.nextLine(); // We don't care what the user asks...

    // Generate a random response value
    double randomNumber = Math.random() * 3.0;
    int response = (int)randomNumber;

    // Depending on the generated value, pick a response
    if (response == 0) {
      System.out.println("Definitely. Yes.");
    } else if (response == 1) {
      System.out.println("Eh, maybe...");
    } else {
      System.out.println("Nope, no way.");
    }

  }

}

Add magic 8 ball demo to lecture 10.

Add magic 8 ball demo to lecture 10.


package net.imagej.ops.views;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Translate;
import net.imglib2.RandomAccessible;
import net.imglib2.view.MixedTransformView;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.Translate.class, name = ViewOps.Translate.NAME)
public class DefaultTranslate<T> extends
		AbstractView<RandomAccessible<T>, MixedTransformView<T>> implements
		Translate<RandomAccessible<T>, MixedTransformView<T>>{

	@Parameter(type = ItemIO.INPUT)
	private long[] translation;

	@Override
	public MixedTransformView<T> compute(RandomAccessible<T> input) {
		return Views.translate(input, translation);
	}

}

Add default implementation of Translate interface.


package com.github.jmchilton.blend4j.galaxy;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;

public class SslHacking {

  public static void disableCertificateCheck() {
    javax.net.ssl.TrustManager x509 = new javax.net.ssl.X509TrustManager() {
      public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
        return;
      }

      public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws java.security.cert.CertificateException {
        return;
      }

      public java.security.cert.X509Certificate[] getAcceptedIssuers() {
        return null;
      }
    };
    SSLContext ctx = null;
    try {
      ctx = SSLContext.getInstance("SSL");
      ctx.init(null, new javax.net.ssl.TrustManager[]{x509}, null);
    } catch (java.security.GeneralSecurityException ex) {
    }

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
      public boolean verify(String hostname, SSLSession session) {
        return true;
      }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
  }
}

Add utility for hacking disabling SSL checks if required.


package galileo.event;

import java.io.IOException;

import galileo.serialization.SerializationInputStream;
import galileo.serialization.SerializationOutputStream;

/**
 * Encapsulates a raw (byte[] based) event that includes a String representing
 * the event synopsis.  This can be used to essentially 'tag' particular blobs
 * of data without writing specific events.
 *
 * @author malensek
 */
public class EventWithSynopsis implements Event {

    private String synopsis;
    private byte[] data;
    private boolean compress = false;

    public EventWithSynopsis(String synopsis, byte[] data) {
        this.synopsis = synopsis;
        this.data = data;
    }

    /**
     * Enables compression when serializing this event.  When deserializing,
     * this setting has no effect.
     */
    public void enableCompression() {
        this.compress = true;
    }

    /**
     * Disables compression when serializing this event.  This is the default
     * behavior.  When deserializing, this setting has no effect.
     */
    public void disableCompression() {
        this.compress = false;
    }

    @Deserialize
    public EventWithSynopsis(SerializationInputStream in)
    throws IOException {
        this.synopsis = in.readString();
        this.data = in.readCompressableField();
    }

    @Override
    public void serialize(SerializationOutputStream out)
    throws IOException {
        out.writeString(synopsis);
        out.writeCompressableField(data, compress);
    }
}

Add event with String-based synopsis

Add event with String-based synopsis


package org.ccnx.ccn.impl.repo;

import java.io.IOException;

import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.CCNFlowControl;
import org.ccnx.ccn.protocol.ContentObject;

/**
 * Special flow controller to write CCN objects to repository internally
 *
 */

public class RepositoryInternalFlowControl extends CCNFlowControl {
	RepositoryStore _repo;

	public RepositoryInternalFlowControl(RepositoryStore repo, CCNHandle handle) throws IOException {
		super(handle);
		_repo = repo;
	}

	/**
	 * Put to the repository instead of ccnd
	 */
	public ContentObject put(ContentObject co) throws IOException {
		try {
			_repo.saveContent(co);
		} catch (RepositoryException e) {
			throw new IOException(e.getMessage());
		}
		return co;
	}

	/**
	 * Don't do waitForPutDrain
	 */
	public void afterClose() throws IOException {};
}

Add new flow controller to allow internal writes to repo


package com.zelory.kace.adressbook.presenter;

import com.zelory.kace.adressbook.data.DataManager;
import com.zelory.kace.adressbook.data.model.AddressBook;
import rx.Observable;
import rx.schedulers.Schedulers;

import javax.swing.*;
import java.io.File;

public class AddressBookPresenter {
    private View view;

    public AddressBookPresenter(View view) {
        this.view = view;
    }

    public void loadAddressBook(File file) {
        view.showLoading();
        DataManager.getInstance()
                .loadAddressBook(file)
                .subscribeOn(Schedulers.io())
                .subscribe(addressBook -> SwingUtilities.invokeLater(() -> {
                    view.showAddressBook(addressBook);
                    view.dismissLoading();
                }), throwable -> SwingUtilities.invokeLater(() -> {
                    view.onError(throwable);
                    view.dismissLoading();
                }));
    }

    public void saveAddressBook(AddressBook addressBook, String path) {
        view.showLoading();
        DataManager.getInstance()
                .save(addressBook, path)
                .subscribeOn(Schedulers.io())
                .subscribe(savedAddressBook -> SwingUtilities.invokeLater(() -> {
                    view.showAddressBook(savedAddressBook);
                    view.dismissLoading();
                }), throwable -> SwingUtilities.invokeLater(() -> {
                    view.onError(throwable);
                    view.dismissLoading();
                }));
    }

    public void sortPersonsByName(AddressBook addressBook) {
        view.showLoading();
        Observable.from(addressBook.getPersons())
                .toSortedList((person1, person2) -> person1.getName().compareTo(person2.getName()))
                .doOnNext(addressBook::setPersons)
                .subscribeOn(Schedulers.io())
                .subscribe(savedAddressBook -> SwingUtilities.invokeLater(() -> {
                    view.showAddressBook(addressBook);
                    view.dismissLoading();
                }), throwable -> SwingUtilities.invokeLater(() -> {
                    view.onError(throwable);
                    view.dismissLoading();
                }));
    }

    public void sortPersonsByZip(AddressBook addressBook) {
        view.showLoading();
        Observable.from(addressBook.getPersons())
                .toSortedList((person1, person2) -> person1.getZip().compareTo(person2.getZip()))
                .doOnNext(addressBook::setPersons)
                .subscribeOn(Schedulers.io())
                .subscribe(savedAddressBook -> SwingUtilities.invokeLater(() -> {
                    view.showAddressBook(addressBook);
                    view.dismissLoading();
                }), throwable -> SwingUtilities.invokeLater(() -> {
                    view.onError(throwable);
                    view.dismissLoading();
                }));
    }

    public interface View {

        void showAddressBook(AddressBook addressBook);

        void showLoading();

        void dismissLoading();

        void onError(Throwable throwable);
    }
}

Add presenter to handle saving and loading data asynchronously


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

package com.foundationdb.sql.pg;

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

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

public class PostgresServerProtocolV2IT extends PostgresServerITBase
{
    @Override
    protected Map<String, String> startupConfigProperties() {
        return uniqueStartupConfigProperties(PostgresServerProtocolV2IT.class);
    }

    @Override
    protected String getConnectionURL() {
        return super.getConnectionURL() + "?protocolVersion=2";
    }

    @Test
    public void checkRejection() throws Exception {
        try {
            openConnection();
        }
        catch (SQLException ex) {
            assertTrue("message is readable",
                       (ex.getMessage().indexOf("Unsupported protocol version 2") > 0));
            return;
        }
        fail("Expected connection to be rejected.");
    }

}

Add an IT for that.

Add an IT for that.


/*
 * #%L
 * ImageJ software for multidimensional image processing and analysis.
 * %%
 * Copyright (C) 2014 - 2015 Board of Regents of the University of
 * Wisconsin-Madison, University of Konstanz and Brian Northan.
 * %%
 * 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.
 * #L%
 */

package net.imagej.ops;

/**
 * Factory which creates a typed output object given two typed inputs.
 *
 * @author Curtis Rueden
 */
public interface BinaryOutputFactory<I1, I2, O> extends
	OutputFactory<BinaryInput<I1, I2>, O>
{

	/**
	 * Create an output object given two inputs.
	 *
	 * @param input1
	 *            first input which determines how to create the output
	 * @param input2
	 *            second input which determines how to create the output
	 * @return output, depending on the input
	 */
	O createOutput(I1 input1, I2 input2);

	// -- OutputFactory methods --

	@Override
	default O createOutput(final BinaryInput<I1, I2> input) {
		return createOutput(input.in1(), input.in2());
	}

}

Add OutputFactory interface for binary input pairs


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

public class Booleans {

    /**
     * @param s
     *            a {@code String} containing the {@code boolean} representation to parse, may be {@code null} or
     *            {@code ""}
     * @param defaultValue
     *            the return value, use {@code defaultValue} if {@code s} is {@code null} or {@code ""}
     * @return the boolean value represented by the argument.
     */
    public static boolean parseBoolean(String s, boolean defaultValue) {
        return Strings.isEmpty(s) ? defaultValue : Boolean.parseBoolean(s);
    }

}

Refactor duplicate code in a new API Boolean.parseBoolean(String, boolean), which also checks for empty strings in addition to nulls.

git-svn-id: de5ce936019686f47409c93bcc5e202a9739563b@1501382 13f79535-47bb-0310-9956-ffa450edef68


package webserver;

import converters.JsonConverter;
import datamodel.Job;
import datamodel.Request;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import rabbit.Sender;

import javax.servlet.http.HttpServletRequest;

@RestController
public class RequestController {

    @RequestMapping(value = "/request", method = RequestMethod.POST)
    public ResponseEntity<Job> jobRequest(@RequestBody String requestBody, HttpServletRequest httpRequest) {
        Request request = JsonConverter.jsonStringToObject(requestBody, Request.class);

        if ((request.getClientId() != null) && (request.getCommand() != null)) {
            Sender sender = new Sender();
            String jobId = sender.send(request, httpRequest.getRemoteAddr());
            sender.closeConnection();
            return new ResponseEntity<Job>(new Job(jobId), HttpStatus.ACCEPTED);
        }
        else {
            return new ResponseEntity<Job>(new Job("-1"), HttpStatus.BAD_REQUEST);
        }

    }
}

Add controller for REST calls.

Add controller for REST calls.


package com.mapswithme.maps.widget.placepage;

import android.support.annotation.NonNull;

public class HotelPriceInfo
{
  @NonNull
  private final String mId;
  @NonNull
  private final String mPrice;
  @NonNull
  private final String mCurrency;
  private final int mDiscount;
  private final boolean mHasSmartDeal;

  public HotelPriceInfo(@NonNull String id, @NonNull String price, @NonNull String currency,
                        int discount, boolean hasSmartDeal)
  {
    mId = id;
    mPrice = price;
    mCurrency = currency;
    mDiscount = discount;
    mHasSmartDeal = hasSmartDeal;
  }

  @NonNull
  public String getId()
  {
    return mId;
  }

  @NonNull
  public String getPrice()
  {
    return mPrice;
  }

  @NonNull
  public String getCurrency()
  {
    return mCurrency;
  }

  public int getDiscount()
  {
    return 20;
  }

  public boolean hasSmartDeal()
  {
    return mHasSmartDeal;
  }

  @Override
  public String toString()
  {
    final StringBuilder sb = new StringBuilder("HotelPriceInfo{");
    sb.append("mId='").append(mId).append('\'');
    sb.append(", mPrice='").append(mPrice).append('\'');
    sb.append(", mCurrency='").append(mCurrency).append('\'');
    sb.append(", mDiscount=").append(mDiscount);
    sb.append(", mHasSmartDeal=").append(mHasSmartDeal);
    sb.append('}');
    return sb.toString();
  }
}

package com.mapswithme.maps.widget.placepage;

import android.support.annotation.NonNull;

public class HotelPriceInfo
{
  @NonNull
  private final String mId;
  @NonNull
  private final String mPrice;
  @NonNull
  private final String mCurrency;
  private final int mDiscount;
  private final boolean mHasSmartDeal;

  public HotelPriceInfo(@NonNull String id, @NonNull String price, @NonNull String currency,
                        int discount, boolean hasSmartDeal)
  {
    mId = id;
    mPrice = price;
    mCurrency = currency;
    mDiscount = discount;
    mHasSmartDeal = hasSmartDeal;
  }

  @NonNull
  public String getId()
  {
    return mId;
  }

  @NonNull
  public String getPrice()
  {
    return mPrice;
  }

  @NonNull
  public String getCurrency()
  {
    return mCurrency;
  }

  public int getDiscount()
  {
    return mDiscount;
  }

  public boolean hasSmartDeal()
  {
    return mHasSmartDeal;
  }

  @Override
  public String toString()
  {
    final StringBuilder sb = new StringBuilder("HotelPriceInfo{");
    sb.append("mId='").append(mId).append('\'');
    sb.append(", mPrice='").append(mPrice).append('\'');
    sb.append(", mCurrency='").append(mCurrency).append('\'');
    sb.append(", mDiscount=").append(mDiscount);
    sb.append(", mHasSmartDeal=").append(mHasSmartDeal);
    sb.append('}');
    return sb.toString();
  }
}

Revert discount value for hotel price

[android] Revert discount value for hotel price


package cz.cuni.mff.d3s.spl.core.data.storage;

import java.util.Collection;

import cz.cuni.mff.d3s.spl.core.data.PrecomputedStatistics;
import cz.cuni.mff.d3s.spl.core.data.SampleStorage;
import cz.cuni.mff.d3s.spl.core.data.SerieDataSource;
import cz.cuni.mff.d3s.spl.core.data.Statistics;

public class OriginalSerieDataSource implements SerieDataSource {

	private SampleStorage samples;
	private long myStartTime;
	private long myEndTime;

	public OriginalSerieDataSource(SampleStorage storage) {
		this(storage, Long.MIN_VALUE, Long.MAX_VALUE);
	}

	private OriginalSerieDataSource(SampleStorage storage, long segmentStartTime, long segmentEndTime) {
		samples = storage;
		myStartTime = segmentStartTime;
		myEndTime = segmentEndTime;
	}

	@Override
	public Statistics get() {
		Collection<Long> all = getSamples();
		return PrecomputedStatistics.create(all);
	}

	@Override
	public SerieDataSource getSegment(long startTime, long endTime) {
		return new OriginalSerieDataSource(samples, startTime, endTime);
	}

	@Override
	public String toString() {
		return String.format("SerieDataSource on '%s' (%d)",
				samples, getSamples().size());
	}

	private Collection<Long> getSamples() {
		return samples.get(myStartTime, myEndTime).values();
	}
}

Implement source directly working above samples


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

import static io.jenetics.CharacterGene.DEFAULT_CHARACTERS;

import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

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

/**
 * @author Franz Wilhelmstötter
 */
public class EscaperTest {

	private static final Escaper ESCAPER = new Escaper('\\', 'a', 'b', 'c');

	@Test(dataProvider = "strings")
	public void escape(final String original, final String escaped) {
		final String esc = ESCAPER.escape(original);
		final String orig = ESCAPER.unescape(esc);

		Assert.assertEquals(esc, escaped);
		Assert.assertEquals(orig, original);
	}

	@DataProvider
	public Object[][] strings() {
		return new Object[][] {
			{"", ""},
			{"t", "t"},
			{"a", "\\a"},
			{"\\", "\\"}
		};
	}

	@Test(invocationCount = 10)
	public void escapeRandomStrings() {
		final String original = nextString(new Random());
		final String escaped = ESCAPER.escape(original);
		Assert.assertEquals(ESCAPER.unescape(escaped), original);
	}

	private static String nextString(final Random random) {
		return random.ints(0, DEFAULT_CHARACTERS.length())
			.limit(100)
			.mapToObj(DEFAULT_CHARACTERS::get)
			.map(Objects::toString)
			.collect(Collectors.joining());
	}

}

Add tests for 'Escaper' class.

Add tests for 'Escaper' class.


/*
 * Copyright 2016 EPAM Systems
 *
 *
 * This file is part of EPAM Report Portal.
 * https://github.com/reportportal/service-api
 *
 * Report Portal is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Report Portal 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Report Portal.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.epam.ta.reportportal.config;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.util.text.BasicTextEncryptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Encrypt beans configuration for password values
 *
 * @author Andrei_Ramanchuk
 */
@Configuration
public class EncryptConfiguration {

	private static final String DEFAULT_PASS = "reportportal";

	@Bean(name = "basicEncryptor")
	public BasicTextEncryptor getBasicEncrypt() {
		BasicTextEncryptor basic = new BasicTextEncryptor();
		basic.setPassword(DEFAULT_PASS);
		return basic;
	}

	@Bean(name = "strongEncryptor")
	public StandardPBEStringEncryptor getStrongEncryptor() {
		StandardPBEStringEncryptor strong = new StandardPBEStringEncryptor();
		strong.setPassword(DEFAULT_PASS);
		strong.setAlgorithm("PBEWithMD5AndTripleDES");
		return strong;
	}
}

Encrypt bean configuration was added.

Encrypt bean configuration was added.


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blazzify.jasonium.ui;

import com.blazzify.jasonium.MainApp;
import com.blazzify.jasonium.models.Server;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.Window;

/**
 *
 * @author Azzuwan Aziz <azzuwan@gmail.com>
 */
public class ServerTree extends TreeView<Server> {

    ObjectMapper mapper = new ObjectMapper();

    public ServerTree() {
    }

    public ServerTree(Window root, Map<String, String> servers) {
        Image imgRoot = new Image(getClass().getClassLoader().getResourceAsStream("icons/servers.png"));
        Server node = new Server();
        node.setName("Servers");
        TreeItem<Server> rootNode = new TreeItem<>(node, new ImageView(imgRoot));
        servers.forEach((t, u) -> {
            Server s = new Server();
            try {
                s = mapper.readValue(u.toString(), Server.class);
            } catch (IOException ex) {
                Logger.getLogger(MainApp.class.getName()).log(Level.SEVERE, null, ex);
            }
            Image imgOffline = new Image(getClass().getClassLoader().getResourceAsStream("icons/server-off.png"));
            TreeItem<Server> child = new TreeItem<>(s, new ImageView(imgOffline));
            rootNode.getChildren().add(child);
        });
        this.setRoot(rootNode);
        this.setOnContextMenuRequested((event) -> {
            ServerTreeContextMenu menu = new ServerTreeContextMenu();
            Window w = root.getScene().getWindow();
            Double winX = w.getX();
            Double winY = w.getY();
            menu.show(w, event.getSceneX() + winX, event.getSceneY() + winY);
        });
    }

}

Refactor server tree into it's own component


package net.imagej.ops.views;

import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.UnShear;
import net.imglib2.RandomAccessible;
import net.imglib2.view.TransformView;

import org.scijava.ItemIO;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

@Plugin(type = ViewOps.UnShear.class, name = ViewOps.UnShear.NAME)
public class DefaultUnshear<T> extends
		AbstractView<RandomAccessible<T>, TransformView<T>> implements
		UnShear<RandomAccessible<T>, TransformView<T>> {

	@Parameter(type = ItemIO.INPUT)
	private int shearDimension;

	@Parameter(type = ItemIO.INPUT)
	private int referenceDimension;

	@Override
	public TransformView<T> compute(RandomAccessible<T> input) {
		throw new UnsupportedOperationException();
	}

}

Add default implementation of Unshear interface.


package Logger;

import Constant.FilePath;
import Database.Config;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;

import static org.junit.Assert.*;

public class LogWriterTest {

    LogWriter logWriter;

    @Before
    public void setUp() throws Exception {
        logWriter = new LogWriter(new File(FilePath.LOG_FILE_PATH.toString()));
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void testWrite() throws Exception {
        logWriter.write(Log.p(
                this.getClass().getSimpleName(),
                "wrote to file", System.currentTimeMillis()
        ));
    }
}

Add Test to fail LogWriter

Add Test to fail LogWriter


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

package com.google.gerrit.server.cancellation;

import com.google.gerrit.common.Nullable;
import java.util.Optional;

/** Exception to signal that the current request is cancelled and should be aborted. */
public class RequestCancelledException extends RuntimeException {
  private static final long serialVersionUID = 1L;

  private final RequestStateProvider.Reason cancellationReason;
  private final Optional<String> cancellationMessage;

  /**
   * Create a {@code RequestCancelledException}.
   *
   * @param cancellationReason the reason why the request is cancelled
   * @param cancellationMessage an optional message providing details about the cancellation
   */
  public RequestCancelledException(
      RequestStateProvider.Reason cancellationReason, @Nullable String cancellationMessage) {
    super(createMessage(cancellationReason, cancellationMessage));
    this.cancellationReason = cancellationReason;
    this.cancellationMessage = Optional.ofNullable(cancellationMessage);
  }

  private static String createMessage(
      RequestStateProvider.Reason cancellationReason, @Nullable String message) {
    StringBuilder messageBuilder = new StringBuilder();
    messageBuilder.append(String.format("Request cancelled: %s", cancellationReason.name()));
    if (message != null) {
      messageBuilder.append(String.format(" (%s)", message));
    }
    return messageBuilder.toString();
  }

  /** Returns the reason why the request is cancelled. */
  public RequestStateProvider.Reason getCancellationReason() {
    return cancellationReason;
  }

  /**
   * Returns a message providing details about the cancellation, or {@link Optional#empty()} if none
   * is available.
   */
  public Optional<String> getCancellationMessage() {
    return cancellationMessage;
  }
}

Define an exception that is thrown if a request is cancelled

Signed-off-by: Edwin Kempin <d43fb6c98c97e553b671ed9a9318100f1de386e7@google.com>
Change-Id: Ibd7d788de1f90911ecada25ea45f04c459323e0b


package com.sibisoft.faizaniftikhartdd;

import static org.junit.Assert.*;

import org.junit.Test;

public class DollarEquality {

	@Test
	public void testEquality()
	{
		assertTrue(new Dollar(5).equals(new Dollar(5)));
	}

}

Add new test case for equal method(Fake Implementation) to make red bar


/**
 *
 */
package algorithms.implementation;

import java.util.Scanner;

/**
 * Challenge: https://www.hackerrank.com/challenges/lisa-workbook
 *
 * @author Sudharsanan Muralidharan
 */
public class LisasWorkbook {
  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    int k = in.nextInt();
    int[] t = new int[n];

    for (int i = 0; i < n; i++) {
      t[i] = in.nextInt();
    }

    int page = 0;
    int special = 0;
    for (int i = 0; i < t.length; i++) {
      int num = t[i];
      int start = 0, end = 0;
      while (num > 0) {
        start = end + 1;
        page++;
        if (num > k) {
          num = num - k;
          end += k;
        } else {
          end += num;
          num = 0;
        }

        if (page >= start && page <= end) {
          special++;
        }
      }
    }

    System.out.println(special);
    in.close();
  }
}

Add Naive solution for Lisas Workbook

Add Naive solution for Lisas Workbook


/*
 ************************************************************************
 ****  C A N A D I A N   A S T R O N O M Y   D A T A   C E N T R E  *****
 *
 * (c) 2010.                         (c) 2010.
 * National Research Council            Conseil national de recherches
 * Ottawa, Canada, K1A 0R6              Ottawa, Canada, K1A 0R6
 * All rights reserved                  Tous droits reserves
 *
 * NRC disclaims any warranties         Le CNRC denie toute garantie
 * expressed, implied, or statu-        enoncee, implicite ou legale,
 * tory, of any kind with respect       de quelque nature que se soit,
 * to the software, including           concernant le logiciel, y com-
 * without limitation any war-          pris sans restriction toute
 * ranty of merchantability or          garantie de valeur marchande
 * fitness for a particular pur-        ou de pertinence pour un usage
 * pose.  NRC shall not be liable       particulier.  Le CNRC ne
 * in any event for any damages,        pourra en aucun cas etre tenu
 * whether direct or indirect,          responsable de tout dommage,
 * special or general, consequen-       direct ou indirect, particul-
 * tial or incidental, arising          ier ou general, accessoire ou
 * from the use of the software.        fortuit, resultant de l'utili-
 *                                      sation du logiciel.
 *
 *
 * @author jenkinsd
 * Jan 6, 2010 - 10:15:22 AM
 *
 *
 *
 ****  C A N A D I A N   A S T R O N O M Y   D A T A   C E N T R E  *****
 ************************************************************************
 */
package ca.nrc.cadc.uws.web;

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import ca.nrc.cadc.uws.web.restlet.resources.*;

@RunWith(Suite.class)
@Suite.SuiteClasses
({
        AsynchResourceTestCase.class,
        JobAsynchResourceExecutionTest.class,
        JobSyncSubmissionResourceTest.class,
        ResultResourceTest.class
})
public class CADCUWSTestSuite
{
}

Add unit tests to build.xml.

Add unit tests to build.xml.

git-svn-id: 311fcc5b8b03427d323cee07bbb9e5a14d8d22e9@328 728ff76a-78ac-11de-a72b-d90af8dea425


package guitests;

import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.jobs.model.task.UniqueTaskList.IllegalTimeException;
import seedu.jobs.testutil.TestTask;

//@@author A0164440M
public class ListCommandTest extends TaskBookGuiTest {

    @Test
  //TODO add success cases listed by all, complete, in-progress
    public void list_nonEmptyList() throws IllegalArgumentException, IllegalTimeException {

        //list all tasks
        assertListWithoutArgumentResult("list", td.CS3101, td.CS3102, td.CS3103, td.CS3104,
                td.CS3105, td.CS3106, td.CS3107, td.CS5101);

        // complete some tasks
        int completeTasks = 6;
        for (int i = 0; i < completeTasks; i++) {
            commandBox.runCommand("complete " + (i + 1));
        }

        // list all completed tasks
        assertListWithArgumentResult("list complete", td.CS3101, td.CS3102, td.CS3103, td.CS3104,
                td.CS3105, td.CS3106);

        // list all in-progress tasks
        assertListWithArgumentResult("list in-progress", td.CS3107, td.CS5101);
    }

    @Test
    public void find_emptyList() throws IllegalArgumentException, IllegalTimeException {
        // list with wrong argument
        assertListWithArgumentResult("list abc");

        commandBox.runCommand("clear");
        assertListWithoutArgumentResult("list"); // no results
    }

    private void assertListWithArgumentResult(String command, TestTask... expectedHits)
            throws IllegalArgumentException, IllegalTimeException {
        commandBox.runCommand(command);
        assertListSize(expectedHits.length);
        assertResultMessage(expectedHits.length + " tasks listed!");
        assertTrue(taskListPanel.isListMatching(expectedHits));
    }

    private void assertListWithoutArgumentResult(String command, TestTask... expectedHits)
            throws IllegalArgumentException, IllegalTimeException {
        commandBox.runCommand(command);
        assertListSize(expectedHits.length);
        assertResultMessage("Listed all tasks");
        assertTrue(taskListPanel.isListMatching(expectedHits));
    }
}

Add test case for list command

Add test case for list command


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

package org.openmhealth.dsu.domain;

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

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;
import static org.openmhealth.dsu.domain.DataPointModality.SELF_REPORTED;

/**
 * A suite of unit tests for the data point modality enumeration.
 *
 * @author Emerson Farrugia
 */
@RunWith(BlockJUnit4ClassRunner.class)
public class DataPointModalityUnitTests {

    @Test
    public void getJsonValueShouldReturnCorrectValue() throws Exception {
        assertThat(SELF_REPORTED.getJsonValue(), equalTo("self reported"));
    }

    @Test
    public void findByJsonValueShouldReturnNullWithUndefinedValue() throws Exception {
        assertThat(DataPointModality.findByJsonValue(null), nullValue());
    }

    @Test
    public void findByJsonValueShouldReturnNullWithUnknownValue() throws Exception {
        assertThat(DataPointModality.findByJsonValue("foo"), nullValue());
    }

    @Test
    public void findByJsonValueShouldReturnMatchingValue() throws Exception {
        assertThat(DataPointModality.findByJsonValue("self reported"), equalTo(SELF_REPORTED));
    }
}

Add data point modality unit tests.

Add data point modality unit tests.


/*
 * Copyright 2016 Martijn van der Woud - The Crimson Cricket Internet Services
 *
 *    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.crimsoncricket.ddd.port.adapter.jpa;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.time.ZoneId;

@Converter(autoApply = true)
public class ZoneIdConverter implements AttributeConverter<ZoneId, String> {

    @Override
    public String convertToDatabaseColumn(ZoneId attribute) {
        if (attribute == null)
            return null;

        return attribute.getId();
    }

    @Override
    public ZoneId convertToEntityAttribute(String dbData) {
        if (dbData == null)
            return null;

        return ZoneId.of(dbData);
    }
}

Add Jpa converter for ZoneId from the java.time API