package helpers;

import org.apache.commons.cli.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Parse command line arguments.
 */
public class CommandLineArgumentParser {
    private static Logger logger = LoggerFactory.getLogger(CommandLineArgumentParser.class);
    private String[] args;
    private Options options = new Options();

    /**
     * Initialize options supported by the program.
     *
     * @param args program arguments.
     */
    public CommandLineArgumentParser(String[] args) {
        this.args = args;
        options.addOption("h", "help", false, "Show help");
        options.addOption("p", "pidFile", true, "Set file to store PID.");
    }

    /**
     * Parse program arguments.
     */
    public void parse() {
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = null;

        try {
            cmd = parser.parse(options, args);

            if (cmd.hasOption("h")) {
                help();
            }

            String pidFile = null;
            if (cmd.hasOption("p")) {
                pidFile = cmd.getOptionValue("p");
                if (pidFile.length() > 0) {
                    PidManipulation.writeOwnPidToFile(pidFile);
                }
            }
            else {
                PidManipulation.writeOwnPidToFile("../var/specs_monitoring_nmap_frontend.pid");
            }

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    /**
     * Print help messages.
     */
    private void help() {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar frontend.jar [arguments] [file]", options);
        System.exit(0);
    }
}

Add class for command line argument manipulation.


/*
 * #%L
 * SciJava UI components for Java Swing.
 * %%
 * Copyright (C) 2010 - 2015 Board of Regents of the University of
 * Wisconsin-Madison.
 * %%
 * 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 org.scijava.ui.swing.console;

import org.scijava.command.Command;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.ui.UIService;
import org.scijava.ui.UserInterface;
import org.scijava.ui.console.ConsolePane;

/**
 * Pops up the console window.
 *
 * @author Curtis Rueden
 */
@Plugin(type = Command.class, menuPath = "Window > Console")
public class ShowConsole implements Command {

	@Parameter
	private UIService uiService;

	@Override
	public void run() {
		final UserInterface ui = uiService.getDefaultUI();
		if (ui == null) return;
		final ConsolePane<?> console = ui.getConsolePane();
		if (console == null) return;
		console.show();
	}

}

Add a command to show the console

Add a command to show the console


/*
 * #%L
 * BroadleafCommerce Common Libraries
 * %%
 * Copyright (C) 2009 - 2013 Broadleaf Commerce
 * %%
 * 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 org.broadleafcommerce.common.extensibility.jpa.copy;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marker annotation for entity classes whose SITE_DISCRIMINATOR value should be harvested from the
 * {@link org.broadleafcommerce.common.web.BroadleafRequestContext#currentProfile} value
 *
 * @author Jeff Fischer
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface ProfileEntity {

}

Add marker annotation for entities that adhere to the profile concept


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2018 Barry DeZonia
 *
 * 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.
 */
package nom.bdezonia.zorbage.procedure;

import nom.bdezonia.zorbage.basic.procedure.Procedure;
import nom.bdezonia.zorbage.basic.tuple.Tuple2;
import nom.bdezonia.zorbage.groups.G;
import nom.bdezonia.zorbage.procedure.parse.EquationParser;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Group;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;

/**
 *
 * @author Barry DeZonia
 *
 */
public class RealEquation implements Procedure<Float64Member>{

	private final Tuple2<String, Procedure<Float64Member>> tuple;

	public RealEquation(String eqn) {
		EquationParser<Float64Group, Float64Member> parser =
				new EquationParser<Float64Group, Float64Member>();
		tuple = parser.parse(G.DBL, eqn);
	}

	@Override
	public void call(Float64Member result, Float64Member... inputs) {
		if (error() == null)
			tuple.b().call(result, inputs);
		else
			G.DBL.zero(result);
	}

	public String error() {
		return tuple.a();
	}

}

Create a placeholder for equation parsing code


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

package net.sourceforge.servestream.transport;

public class ProtocolFactory {

	public static final String HTTP_HINT = "hostname/path";
	public static final String HTTPS_HINT = "hostname/path";

	/**
	 * Default constructor
	 */
	public ProtocolFactory() {

	}

	/**
	 * Returns a hint for the protocol passed in
	 *
	 * @param protocol The protocol
	 * @return String The hint for the protocol
	 */
	public static String getProtocolHint(String protocol) {
		if (protocol.equals("http")) {
			return HTTP_HINT;
		} else if (protocol.equals("https")) {
			return HTTPS_HINT;
		} else {
			return null;
		}
	}

	/**
	 *
	 *
	 * @param scheme
	 * @return String Protocol
	 */
	public static String getProtocol(String scheme) {
		if (scheme.equals("http")) {
			return "http://";
		} else if (scheme.equals("https")) {
			return "https://";
		} else {
			return null;
		}
	}

}

Add class for protocol spinner

Add class for protocol spinner

git-svn-id: 0a6f2aeebe3a339de06b6162ef5a6b6b6e2abc00@38 b8d320ad-ce4d-463a-8333-51e6c77ad906


/*
 * Copyright 2015-2017 the original author or authors.
 *
 * All rights reserved. This program and the accompanying materials are
 * made available under the terms of the Eclipse Public License v1.0 which
 * accompanies this distribution and is available at
 *
 * http://www.eclipse.org/legal/epl-v10.html
 */

package org.junit.platform.console.options;

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

import java.nio.charset.StandardCharsets;

import org.junit.jupiter.api.Test;
import org.junit.platform.engine.TestExecutionResult;

class ThemeTests {

	@Test
	void givenUtf8ShouldReturnUnicode() {
		assertEquals(Theme.valueOf(StandardCharsets.UTF_8), Theme.UNICODE);
	}

	@Test
	void givenAnythingElseShouldReturnAscii() {
		assertAll("All character sets that are not UTF-8 should return Theme.ASCII", () -> {
			assertEquals(Theme.valueOf(StandardCharsets.ISO_8859_1), Theme.ASCII);
			assertEquals(Theme.valueOf(StandardCharsets.US_ASCII), Theme.ASCII);
			assertEquals(Theme.valueOf(StandardCharsets.UTF_16), Theme.ASCII);
		});
	}

	@Test
	void givenSuccessfulTestExecutionResultShouldReturnAsciiSuccessfulElement() {
		TestExecutionResult successful = TestExecutionResult.successful();
		assertEquals(Theme.ASCII.successful(), Theme.ASCII.status(successful));
	}

	@Test
	void givenSuccessfulTestExecutionResultShouldReturnUnicodeSuccessfulElement() {
		TestExecutionResult successful = TestExecutionResult.successful();
		assertEquals(Theme.UNICODE.successful(), Theme.UNICODE.status(successful));
	}

	@Test
	void givenAbortedTestExecutionResultShouldReturnAsciiAbortedElement() {
		TestExecutionResult aborted = TestExecutionResult.aborted(new Throwable());
		assertEquals(Theme.ASCII.aborted(), Theme.ASCII.status(aborted));
	}

	@Test
	void givenAbortedTestExecutionResultShouldReturnUnicodeAbortedElement() {
		TestExecutionResult aborted = TestExecutionResult.aborted(new Throwable());
		assertEquals(Theme.UNICODE.aborted(), Theme.UNICODE.status(aborted));
	}

	@Test
	void givenFailedTestExecutionResultShouldReturnAsciiFailedElement() {
		TestExecutionResult failed = TestExecutionResult.failed(new Throwable());
		assertEquals(Theme.ASCII.failed(), Theme.ASCII.status(failed));
	}

	@Test
	void givenFailedTestExecutionResultShouldReturnUnicodeFailedElement() {
		TestExecutionResult failed = TestExecutionResult.failed(new Throwable());
		assertEquals(Theme.UNICODE.failed(), Theme.UNICODE.status(failed));
	}
}

Introduce tests for Theme class

Introduce tests for Theme class


package org.pdxfinder.services.reporting;

/*
 * Created by csaba on 28/02/2019.
 */
public class MarkerLogEntity extends LogEntity{

    private String usedMarkerSymbol;
    private String suggestedMarkerSymbol;
    private String reasonForChange;

    public MarkerLogEntity(String reporter, String dataSource, String model, String usedMarkerSymbol, String suggestedMarkerSymbol, String reasonForChange) {
        super(reporter, dataSource, model);
        this.usedMarkerSymbol = usedMarkerSymbol;
        this.suggestedMarkerSymbol = suggestedMarkerSymbol;
        this.reasonForChange = reasonForChange;
    }
}

Add log entity for markers

Add log entity for markers


package com.github.aureliano.damihilogs.converter.output;

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

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

import com.github.aureliano.damihilogs.config.output.OutputConfigTypes;
import com.github.aureliano.damihilogs.config.output.TwitterOutputConfig;

public class TwitterOutputConverterTest {

	@Test
	public void testConvert() {
		Map<String, Object> data = new HashMap<String, Object>();
		Properties metadata = new Properties();

		metadata.setProperty("test", "test");
		metadata.setProperty("goal", "CAM");

		data.put("metadata", metadata);
		data.put("consumerKey", "consumer-key");
		data.put("consumerSecret", "consumer-secret");
		data.put("oauthToken", "oauth-token");
		data.put("oauthTokenSecret", "oauth-token-secret");
		data.put("tweet", "My status update");

		data.put("type", OutputConfigTypes.TWITTER_OUTPUT);

		TwitterOutputConfig conf = new TwitterOutputConverter().convert(data);

		Assert.assertEquals("test", conf.getMetadata("test"));
		Assert.assertEquals("CAM", conf.getMetadata("goal"));

		Assert.assertEquals("My status update", conf.getTweet());
		Assert.assertEquals("consumer-key", conf.getConsumerKey());
		Assert.assertEquals("consumer-secret", conf.getConsumerSecret());
		Assert.assertEquals("oauth-token", conf.getOauthToken());
		Assert.assertEquals("oauth-token-secret", conf.getOauthTokenSecret());
	}

	@Test
	public void testId() {
		Assert.assertEquals(OutputConfigTypes.TWITTER_OUTPUT.name(), new TwitterOutputConverter().id());
	}
}

Create Twitter output configuration converter.


package com.blocksolid.income;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class TaxCalculatorTest {

    // Tests for calculatePersonalAllowance method

    @Test
    public void testPersonalAllowanceCalculationForAnnualIncomeOf0() throws Exception {
        // The personal allowance for a salary of £0 is the maximum £10,600
        TaxCalculator taxCalculator = new TaxCalculator(0);
        int result = taxCalculator.calculatePersonalAllowance();
        assertEquals(1060000, result);
    }

    @Test
    public void testPersonalAllowanceCalculationForAnnualIncomeOf100001() throws Exception {
        // The personal allowance for a salary of £100,001 is the maximum £10,600
        TaxCalculator taxCalculator = new TaxCalculator(10000100);
        int result = taxCalculator.calculatePersonalAllowance();
        assertEquals(1060000, result);
    }

    @Test
    public void testPersonalAllowanceCalculationForAnnualIncomeOf100002() throws Exception {
        // £1 is removed from the personal allowance for every £2 over £100,000
        // The personal allowance for a salary of £100,002 should be £10,599
        TaxCalculator taxCalculator = new TaxCalculator(10000200);
        int result = taxCalculator.calculatePersonalAllowance();
        assertEquals(1059900, result);
    }

    @Test
    public void testPersonalAllowanceCalculationForAnnualIncomeOf121199() throws Exception {
        // The personal allowance for a salary of £121,199 should be £1
        TaxCalculator taxCalculator = new TaxCalculator(12119900);
        int result = taxCalculator.calculatePersonalAllowance();
        assertEquals(100, result);
    }

    @Test
    public void testPersonalAllowanceCalculationForAnnualIncomeOf121200() throws Exception {
        // There is no personal allowance for a salary of £121,200 or over
        TaxCalculator taxCalculator = new TaxCalculator(12120000);
        int result = taxCalculator.calculatePersonalAllowance();
        assertEquals(0, result);
    }

    @Test
    public void testPersonalAllowanceCalculationForAnnualIncomeOf1000000() throws Exception {
        // There is no personal allowance for a salary of £1,000,000
        // This checks that it's not possible to have a negative personal allowance
        TaxCalculator taxCalculator = new TaxCalculator(100000000);
        int result = taxCalculator.calculatePersonalAllowance();
        assertEquals(0, result);
    }

}

Add unit tests for calculatePersonalAllowance method


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

package androidx.appsearch.cts.observer;

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

import androidx.appsearch.annotation.Document;
import androidx.appsearch.observer.ObserverSpec;

import com.google.common.collect.ImmutableSet;

import org.junit.Test;

public class ObserverSpecCtsTest {
    @Test
    public void testFilterSchemas() {
        ObserverSpec observerSpec = new ObserverSpec.Builder()
                .addFilterSchemas("Schema1", "Schema2")
                .addFilterSchemas(ImmutableSet.of("Schema3", "Schema4"))
                .build();
        assertThat(observerSpec.getFilterSchemas()).containsExactly(
                "Schema1", "Schema2", "Schema3", "Schema4");
    }

// @exportToFramework:startStrip

    @Document
    public static class King {
        @Document.Namespace String mNamespace;
        @Document.Id String mId;
    }

    @Document
    public static class Queen {
        @Document.Namespace String mNamespace;
        @Document.Id String mId;
    }

    @Document
    public static class Jack {
        @Document.Namespace String mNamespace;
        @Document.Id String mId;
    }

    @Document
    public static class Ace {
        @Document.Namespace String mNamespace;
        @Document.Id String mId;
    }

    @Test
    public void testFilterSchemas_documentClass() throws Exception {
        ObserverSpec observerSpec = new ObserverSpec.Builder()
                .addFilterSchemas("Schema1", "Schema2")
                .addFilterDocumentClasses(King.class, Queen.class)
                .addFilterSchemas(ImmutableSet.of("Schema3", "Schema4"))
                .addFilterDocumentClasses(ImmutableSet.of(Jack.class, Ace.class))
                .build();
        assertThat(observerSpec.getFilterSchemas()).containsExactly(
                "Schema1", "Schema2", "King", "Queen", "Schema3", "Schema4", "Jack", "Ace");
    }

// @exportToFramework:endStrip
}

Add CTS tests for ObserverSpec.

Add CTS tests for ObserverSpec.

Bug: 221867488
Test: ObserverSpecCtsTest
Change-Id: I96ad99e9911c1649424b67c74f058fb0757dc71c


/*
 * Copyright 2017 Volker Berlin (i-net software)
 *
 * 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 de.inetsoftware.jwebassembly.module;

/**
 * Cast operations for converting one type to another
 *
 * @author Volker Berlin
 *
 */
public enum ValueTypeConvertion {
    l2i,
}

Add enum for cast operations

Add enum for cast operations


package nl.github.martijn9612.fishy;

import static org.junit.Assert.*;
import static org.mockito.Mockito.mock;

import org.junit.Test;
import org.newdawn.slick.GameContainer;

public class SinusOpponentTest {
    private final GameContainer gc = mock(GameContainer.class);

    @Test
    public void testObjectLogic() {
        Opponent opp = new SinusOpponent(1, 1);
        opp.setPosition(0, 0);
        opp.objectLogic(gc, 0);
        assertEquals(opp.speed, 1);
    }

    @Test
    public void testObjectLogic2() {
        Opponent opp = new SinusOpponent(1, 1);
        opp.setPosition(1, 1);
        opp.objectLogic(gc, 0);
        assertEquals(opp.speed, ((1 % 80) / 20 + 1));
    }
}

Test file for SinusOpponent.java <testing


/*
 * 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.android.exoplayer2.upstream;

import android.net.Uri;
import androidx.test.core.app.ApplicationProvider;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import com.google.android.exoplayer2.testutil.DataSourceContractTest;
import com.google.android.exoplayer2.testutil.TestUtil;
import com.google.common.collect.ImmutableList;
import java.io.IOException;
import org.junit.Before;
import org.junit.runner.RunWith;

/** {@link DataSource} contract tests for {@link AssetDataSource}. */
@RunWith(AndroidJUnit4.class)
public class AssetDataSourceContractTest extends DataSourceContractTest {

  // We pick an arbitrary file from the assets. The selected file has a convenient size of 1024
  // bytes.
  private static final String ASSET_PATH = "media/mp3/1024_incrementing_bytes.mp3";
  private static final Uri ASSET_URI = Uri.parse("asset:///" + ASSET_PATH);

  private byte[] data;

  @Before
  public void setUp() throws IOException {
    data = TestUtil.getByteArray(ApplicationProvider.getApplicationContext(), ASSET_PATH);
  }

  @Override
  protected ImmutableList<TestResource> getTestResources() {
    return ImmutableList.of(
        new TestResource.Builder()
            .setName("simple")
            .setUri(ASSET_URI)
            .setExpectedBytes(data)
            .build());
  }

  @Override
  protected Uri getNotFoundUri() {
    return Uri.parse("asset:///nonexistentdir/nonexistentfile");
  }

  @Override
  protected DataSource createDataSource() {
    return new AssetDataSource(ApplicationProvider.getApplicationContext());
  }
}

Add contract test for AssetDataSource

Add contract test for AssetDataSource

PiperOrigin-RevId: 352532853


//43. Multiply Strings
/**
 * Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
 *
 * Note:
 * 1. The length of both num1 and num2 is < 110.
 * 2. Both num1 and num2 contains only digits 0-9.
 * 3. Both num1 and num2 does not contain any leading zero.
 * 4. You must not use any built-in BigInteger library or convert the inputs to integer directly.
 *
 * Tags:  Math, String
 * Show Similar Problems: (M) Add Two Numbers (E) Plus One (E) Add Binary (E) Add Strings
 *
 * @author Xinyue Zhang
 *
 */

public class Solution {
    public String multiply(String num1, String num2) {
        if (num1.equals("0") || num2.equals("0"))
            return "0";
        //product length is smaller than the sum of two multipliers length
        int n1 = num1.length(), n2 = num2.length(), n = n1 + n2;
        int[] product = new int[n];
        //record the product of each digit
        for (int i = n1 - 1; i >= 0; i--)
            for (int j = n2 - 1; j >= 0; j--)
                product[i + j + 1] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
        //make each digit valid
        for (int i = n - 1; i > 0; i--) {
            product[i - 1] += product[i] / 10;
            product[i] = product[i] % 10;
        }
        //convert product to string
        StringBuilder res = new StringBuilder();
        if (product[0] != 0)
            res.append(product[0]);
        for (int i = 1; i < n; i++)
            res.append(product[i]);

        return res.toString();
    }

    public static void main(String[] args) {
        String num1 = "13", num2 = "12";
        Solution sol = new Solution();
        String res = sol.multiply(num1, num2);
        System.out.println(res);
    }
}

Add Solution for 43. Multiply Strings

Add Solution for 43. Multiply Strings


package net.sf.jabref.model.entry;

import net.sf.jabref.JabRefPreferences;
import org.junit.Test;

public class BibtexEntryTests {

    private BibtexEntry entry;

    @Test
    public void testDefaultConstructor() {
        entry = new BibtexEntry();
    }
}

Add minimal unit test for BibtexEntry

Add minimal unit test for BibtexEntry


package info.u_team.u_team_core.util.registry;

import java.util.function.Supplier;

import net.minecraft.entity.*;
import net.minecraft.entity.EntityType.Builder;
import net.minecraftforge.fml.RegistryObject;
import net.minecraftforge.registries.ForgeRegistries;

public class EntityTypeDeferredRegister {

	public static EntityTypeDeferredRegister create(String modid) {
		return new EntityTypeDeferredRegister(modid);
	}

	private final CommonDeferredRegister<EntityType<?>> register;

	protected EntityTypeDeferredRegister(String modid) {
		register = CommonDeferredRegister.create(ForgeRegistries.ENTITIES, modid);
	}

	public <E extends Entity, B extends Builder<E>> RegistryObject<EntityType<E>> register(String name, Supplier<? extends B> supplier) {
		return register.register(name, () -> supplier.get().build(register.getModid() + ":" + name));
	}

}

Add entity type deferred register to make the build method a bit nicer


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2017 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * 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.wildfly.security.auth.client;

import static org.junit.Assert.*;

import org.junit.Ignore;
import org.junit.Test;

/**
 * @author David M. Lloyd
 */
public final class AuthenticationConfigurationTest {

    @Test
    public void testBaseEquality1() {
        AuthenticationConfiguration c1;
        AuthenticationConfiguration c2;

        c1 = AuthenticationConfiguration.EMPTY.useName("name1").usePort(1234).useProtocol("abcd");
        c2 = AuthenticationConfiguration.EMPTY.useName("name1").usePort(1234).useProtocol("abcd");

        assertEquals(c1, c2);
    }

    @Test
    @Ignore("ELY-900")
    public void testBaseEquality2() {
        AuthenticationConfiguration c1;
        AuthenticationConfiguration c2;

        c1 = AuthenticationConfiguration.EMPTY.useName("name1").usePort(1234).useProtocol("abcd").usePassword("abcd");
        c2 = AuthenticationConfiguration.EMPTY.useName("name1").usePort(1234).useProtocol("abcd").usePassword("abcd");

        assertEquals(c1, c2);
    }

    @Test
    @Ignore("ELY-900")
    public void testCopying() {
        AuthenticationConfiguration c1;
        AuthenticationConfiguration c2;

        c1 = AuthenticationConfiguration.EMPTY.useName("name1").usePassword("password1").usePort(1234);
        c2 = AuthenticationConfiguration.EMPTY.useName("name2").useProtocol("abcd").usePort(1234);
        assertEquals(
            AuthenticationConfiguration.EMPTY.useName("name1").useCredentials(c1.getCredentialSource()).usePort(1234).useProtocol("abcd"),
            c2.with(c1)
        );

    }
}

Add AuthenticationConfiguration hash and equality tests


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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Socket;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import static org.mockito.Mockito.when;
import org.mockito.MockitoAnnotations;
import ships.model.Field;
import ships.model.FieldImpl;

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

    public TCPClientConnectionTest() {
    }

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @After
    public void tearDown() {
    }

    @Mock
    Socket sock;

    @InjectMocks
    TCPClientConnection sut = new TCPClientConnection(sock);

    @Test
    public void shouldSendAndReceiveMovePacket() throws IOException {
        //given
        String expected = "{"
                + "\"field\":["
                + "\"ships.model.FieldImpl\",{"
                + "\"attacked\":false,"
                + "\"state\":\"EMPTY\","
                + "\"row\":1,\"col\":2," + "\"shipHere\":false"
                + "}]}";
        Field f = new FieldImpl(1, 2);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ByteArrayInputStream bais;
        when(sock.getOutputStream()).thenReturn(baos);
        when(sock.getInputStream()).thenReturn(null);
        MovePacket mp = new MovePacket(new FieldImpl(1, 2));
        //when
        sut.sendPacket(mp);
        String s = baos.toString();/////////////////////////////////////////////
//        bais = new ByteArrayInputStream(baos.toByteArray());
//        MovePacket packet = (MovePacket) sut.receivePacket();
//        Field receivedField = packet.getField();
        //then
        assertEquals(expected, s);
//        assertEquals(f, receivedField);
    }

}

Add tests for TCP connection

Add tests for TCP connection


package com.yahoo.vespa.model.admin.metricsproxy;

import com.yahoo.vespa.model.VespaModel;
import com.yahoo.vespa.model.test.VespaModelTester;
import org.junit.Test;

import static com.yahoo.config.model.api.container.ContainerServiceType.METRICS_PROXY_CONTAINER;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

/**
 * @author gjoranv
 */
public class MetricsProxyContainerClusterTest {

    @Test
    public void one_metrics_proxy_container_is_added_to_every_node() {
        var numberOfHosts = 4;
        var tester = new VespaModelTester();
        tester.enableMetricsProxyContainer(true);
        tester.addHosts(4);

        VespaModel model = tester.createModel(servicesXml(), true);
        assertThat(model.getRoot().getHostSystem().getHosts().size(), is(numberOfHosts));

        for (var host : model.getHostSystem().getHosts()) {
            assertThat(host.getService(METRICS_PROXY_CONTAINER.serviceName), notNullValue());
        }

    }

    private String servicesXml() {
        return String.join("\n", "<?xml version='1.0' encoding='utf-8' ?>",
                           "<services>",
                           "  <container version='1.0' id='foo'>",
                           "    <nodes count='2'/>",
                           "  </container>",
                           "  <content id='my-content' version='1.0'>",
                           "    <documents />",
                           "    <nodes count='2'/>",
                           "  </content>",
                           "</services>");
    }
}

Add simple unit test for MetricsProxyContainer.


package com.problems.geeksforgeeks;

/**
 * Created by Maks on 6/10/2017.
 */
public class CutRod {
    public int recutsiveSolution(int[] price, int n){
        if(n<=0){
            return  0;
        }
        int max=Integer.MIN_VALUE;
        for(int i=0; i<n; i++){
            max=Math.max(max, price[i]+recutsiveSolution(price,n-i-1));
        }
        return  max;
    }
}

Cut the Rod initial implementation

Cut the Rod initial implementation


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

import static org.junit.Assert.*;

import java.util.Date;

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

import com.boundary.camel.component.common.ServiceStatus;

public class UrlResultTest {

	private UrlResult result;

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

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

	@Before
	public void setUp() throws Exception {
		result = new UrlResult();
	}

	@After
	public void tearDown() throws Exception {
	}

	@Test
	public void testUrlInfo() {
		assertNotNull("check uri",result.getHost());
		assertNull("check url",result.getURL());
	}

	@Test
	public void testToString() {
		String url = "https://www.google.com/some/path";
		result.setStatus(ServiceStatus.SUCCESS);
		result.setURLStatus(URLStatus.UNKNOWN_HOST);
		assertEquals("check toString()",",url=https://www.google.com/some/path,timeout=5000,urlStatus=UNKNOWN_HOST",result.toString());
	}

	@Test
	public void testStatus() {
		result.setURLStatus(URLStatus.UNKNOWN_HOST);
		assertEquals("check status",URLStatus.UNKNOWN_HOST,result.getURLStatus());
	}

	@Test
	public void testGetStatus() {
		ServiceStatus status = ServiceStatus.FAIL;
		result.setStatus(status);
		assertEquals("check service status",status,result.getStatus());
	}

	@Test
	public void testMessage() {
		String message = "foobar";
		result.setMessage(message);
		assertEquals("check message",message,result.getMessage());
	}

	@Test
	public void tesHost() {
		String host = "myHost";
		result.setHost(host);
		assertEquals("check host",host,result.getHost());
	}

	@Test
	public void testTimestamp() {
		Date now = new Date();
		result.setTimestamp(now);
		assertEquals("check timestamp",now,result.getTimestamp());
	}
}

Rename to be consistent with function

Rename to be consistent with function


package com.nesscomputing.config;

import junit.framework.Assert;

import org.junit.Test;

import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;

public class ConfigProviderTest {

    interface TestConfig {

    }

    @Test
    public void testConfigBeansSingleton() {
        Injector injector = Guice.createInjector(new AbstractModule() {
            @Override
            protected void configure() {
                install (ConfigModule.forTesting());

                bind (TestConfig.class).toProvider(ConfigProvider.of(TestConfig.class));
            }
        });

        TestConfig first = injector.getInstance(TestConfig.class);
        TestConfig second = injector.getInstance(TestConfig.class);

        Assert.assertSame("not bound as singleton,", first, second);
    }
}

Add an initially failing test case to show that Config beans are not bound as singletons.


package com.parc.ccn.library.profiles;

/**
 * A place for now to place command markers
 * We are using 0xC0 and 0xC1 for these
 *
 * @author rasmusse
 *
 */
public class CommandMarkers {

	/**
	 * Repository "markers"
	 */
	public static final byte[] REPO_START_WRITE = {(byte)0xc0, 'R', 0x1};
	public static final byte[] REPO_GET_HEADER = {(byte)0xc0, 'R', 0x2};

	/**
	 * Nonce marker
	 */
	public static final byte[] NONCE_MARKER = {(byte)0xc0, 'N'};
}

Make better use of sorted tree in repo ContentTree matching.


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

/**
 * Given a file we are going to read it line by line, can you write a method to remove block
 * comments marked with '/*' and '*\'. Simulate the input file if needed.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class RemoveComments {
}

Add statement to problem 23

Add statement to problem 23


package ser;

import java.io.ByteArrayInputStream;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

import org.junit.Ignore;
import org.junit.Test;
import org.nustaq.serialization.FSTConfiguration;
import org.nustaq.serialization.FSTObjectInput;
import org.nustaq.serialization.FSTObjectOutput;

public class OverflowTest {

    @Test
    @Ignore
    public void test() throws Throwable {
        FSTConfiguration fc = FSTConfiguration.createDefaultConfiguration();

        byte[] b;
        int len;
        try (FSTObjectOutput foo = new FSTObjectOutput(fc)) {
            foo.writeObject(new Outer());
            b = foo.getBuffer();
            len = foo.getWritten();
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(b, 0, len);
        FSTObjectInput foi = fc.getObjectInput(bais);
        foi.readObject();
    }

    // Up to about stream offset 16K there is this other table.  This needs to
    // be big enough to break past that and also produce enough stack frames to
    // overflow.
    private static final int OUTER_CT = 30000;

    public static class Outer implements Externalizable {
        @Override
        public void writeExternal(ObjectOutput out) throws IOException {
            for (int i = 0; i < OUTER_CT; ++i) {
                out.writeObject(new Inner());
            }
        }

        @Override
        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
            for (int i = 0; i < OUTER_CT; ++i) {
                in.readObject();
            }
        }
    }

    public static class Inner implements Externalizable {
        @Override
        public void writeExternal(ObjectOutput out) throws IOException {
            // An array of length 0 produces a period of 7 and we want to
            // target 23 which is the hash table size as picked up in the
            // debugger
            out.writeObject(new byte[16]);
        }

        @Override
        public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
            in.readObject();
        }
    }
}

Add test for objects that align poorly with FSTInt2ObjectMap


package org.musicbrainz.search.analysis;

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

import java.util.Map;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.util.TokenFilterFactory;

/**
 * Factory for {@link MusicbrainzTokenizerFilter}.
 *

 * <fieldType name="text_stndrd" class="solr.TextField" positionIncrementGap="100">
 *   <analyzer>
 *     <tokenizer class="solr.StandardTokenizerFactory"/>
 *     <filter class="solr.MusicbrainzTokenizerFilterFactory"/>
 *   </analyzer>
 * </fieldType>

 */
public class MusicbrainzTokenizerFilterFactory extends TokenFilterFactory {

    /** Creates a new MusicbrainzTokenizerFilterFactory */
    public MusicbrainzTokenizerFilterFactory(Map<String,String> args) {
        super(args);
        if (!args.isEmpty()) {
            throw new IllegalArgumentException("Unknown parameters: " + args);
        }
    }

    @Override
    public MusicbrainzTokenizerFilter create(TokenStream input) {
        return new MusicbrainzTokenizerFilter(input);
    }
}

Add a factory class to allow solr to instantiate MB tokenizer filter


package com.dataloom.hazelcast;

import com.google.common.util.concurrent.ListenableFuture;
import com.hazelcast.core.ExecutionCallback;
import com.hazelcast.core.ICompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class ListenableHazelcastFuture<T> implements ListenableFuture<T> {
    private static final Logger logger = LoggerFactory.getLogger( ListenableHazelcastFuture.class );
    private final ICompletableFuture<T> f;

    public ListenableHazelcastFuture( ICompletableFuture<T> f ) {
        this.f = f;
    }

    @Override
    public void addListener( Runnable listener, Executor executor ) {
        f.andThen( new ExecutionCallback<T>() {
            @Override public void onResponse( T response ) {
                listener.run();
            }

            @Override public void onFailure( Throwable t ) {
                logger.error( "Unable to retrieve Ace.", t );
            }
        } );
    }

    @Override
    public boolean cancel( boolean mayInterruptIfRunning ) {
        return f.cancel( mayInterruptIfRunning );
    }

    @Override public boolean isCancelled() {
        return f.isCancelled();
    }

    @Override
    public boolean isDone() {
        return f.isDone();
    }

    @Override public T get() throws InterruptedException, ExecutionException {
        return f.get();
    }

    @Override public T get( long timeout, TimeUnit unit )
            throws InterruptedException, ExecutionException, TimeoutException {
        return f.get( timeout, unit );
    }
}

Move ICompletableFuture adapter to Rhizome


/**
 * Copyright (c) 2017 Bosch Software Innovations GmbH.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Bosch Software Innovations GmbH - initial creation
 */

package org.eclipse.hono.util;

import java.util.Objects;

import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.transport.AmqpError;
import org.apache.qpid.proton.amqp.transport.ErrorCondition;

import io.vertx.proton.ProtonHelper;

/**
 * An exception wrapping an {@link AmqpError}.
 *
 */
public final class AmqpErrorException extends RuntimeException {

    private static final long serialVersionUID = 1L;
    private final Symbol error;

    /**
     * Creates a new exception for an error and description.
     *
     * @param error
     * @param description
     */
    public AmqpErrorException(final Symbol error, final String description) {
        super(Objects.requireNonNull(description));
        this.error = Objects.requireNonNull(error);
    }

    /**
     * Creates a new exception for an error and description.
     *
     * @param error
     * @param description
     */
    public AmqpErrorException(final String error, final String description) {
        super(Objects.requireNonNull(description));
        this.error = Symbol.getSymbol(Objects.requireNonNull(error));
    }

    /**
     * @return The error.
     */
    public final Symbol getError() {
        return error;
    }

    /**
     * Gets an AMQP {@link ErrorCondition} based on this exception's error and description.
     *
     * @return The condition.
     */
    public final ErrorCondition asErrorCondition() {
        return ProtonHelper.condition(error.toString(), getMessage());
    }
}

Add exception for conveying AMQP errors.

Signed-off-by: Kai Hudalla <6c3288b94355003a6c5f12ba233f9fc06ef02a62@bosch-si.com>


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

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;

/**
 * Utilization report for a Datanode cache
 */
@InterfaceAudience.Private
@InterfaceStability.Unstable
public class CacheReport {
  private final long capacity;
  private final long used;

  public CacheReport(long capacity, long used) {
    this.capacity = capacity;
    this.used = used;
  }

  public long getCapacity() {
    return capacity;
  }

  public long getUsed() {
    return used;
  }
}

Add missing file from HDFS-5141

Add missing file from HDFS-5141

git-svn-id: bfa48d55d04d89a028096ea0fa51836e9a086984@1519819 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright 2016 Philip Cohn-Cort
 *
 * 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.fuzz.emptyhusk;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.Spannable;
import android.text.SpannableString;

import com.fuzz.indicator.text.MigratoryStyleSpan;
import com.fuzz.indicator.text.TextViewGenerator;

import static android.graphics.Typeface.BOLD;

/**
 * Simple TextViewGenerator that styles text in a bold sort of way.
 *
 * @author Philip Cohn-Cort (Fuzz)
 */
class BoldTextViewGenerator extends TextViewGenerator {
    @NonNull
    @Override
    protected Spannable getTextFor(@NonNull Context context, int position) {
        String[] introStrings = context.getResources().getStringArray(R.array.introductory_messages);

        SpannableString ssb = new SpannableString(introStrings[position]);
        MigratoryStyleSpan span = new MigratoryStyleSpan(BOLD);

        int end = (int) (ssb.length() * span.getCoverage().diff());
        ssb.setSpan(span, 0, end, span.preferredFlags(0));

        return ssb;
    }
}

Add a generator for bold text

Add a generator for bold text


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

package org.codehaus.griffon.compiler.support;

import org.codehaus.groovy.ast.ClassNode;

/**
 * @author Andres Almiray
 * @since 0.9.5
 */
public abstract class AbstractASTInjector implements ASTInjector {
    protected ClassNode newClass(ClassNode classNode) {
        return new ClassNode(classNode.getTypeClass());
    }
}

Fix cli-test breakage (3) groovyc 1.8.3 has stricter rules wrt usage of cached ClassNode instances


/*
 * 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.flink.runtime.entrypoint;

import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.clusterframework.FlinkResourceManager;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.heartbeat.HeartbeatServices;
import org.apache.flink.runtime.highavailability.HighAvailabilityServices;
import org.apache.flink.runtime.metrics.MetricRegistry;
import org.apache.flink.runtime.resourcemanager.ResourceManager;
import org.apache.flink.runtime.resourcemanager.ResourceManagerConfiguration;
import org.apache.flink.runtime.resourcemanager.ResourceManagerRuntimeServices;
import org.apache.flink.runtime.resourcemanager.ResourceManagerRuntimeServicesConfiguration;
import org.apache.flink.runtime.resourcemanager.StandaloneResourceManager;
import org.apache.flink.runtime.rpc.FatalErrorHandler;
import org.apache.flink.runtime.rpc.RpcService;

/**
 * Entry point for the standalone session cluster.
 */
public class StandaloneSessionClusterEntrypoint extends SessionClusterEntrypoint {

	@Override
	protected ResourceManager<?> createResourceManager(
			Configuration configuration,
			ResourceID resourceId,
			RpcService rpcService,
			HighAvailabilityServices highAvailabilityServices,
			HeartbeatServices heartbeatServices,
			MetricRegistry metricRegistry,
			FatalErrorHandler fatalErrorHandler) throws Exception {
		final ResourceManagerConfiguration resourceManagerConfiguration = ResourceManagerConfiguration.fromConfiguration(configuration);
		final ResourceManagerRuntimeServicesConfiguration resourceManagerRuntimeServicesConfiguration = ResourceManagerRuntimeServicesConfiguration.fromConfiguration(configuration);
		final ResourceManagerRuntimeServices resourceManagerRuntimeServices = ResourceManagerRuntimeServices.fromConfiguration(
			resourceManagerRuntimeServicesConfiguration,
			highAvailabilityServices,
			rpcService.getScheduledExecutor());

		return new StandaloneResourceManager(
			rpcService,
			FlinkResourceManager.RESOURCE_MANAGER_NAME,
			resourceId,
			resourceManagerConfiguration,
			highAvailabilityServices,
			heartbeatServices,
			resourceManagerRuntimeServices.getSlotManager(),
			metricRegistry,
			resourceManagerRuntimeServices.getJobLeaderIdService(),
			fatalErrorHandler);
	}

	public static void main(String[] args) {
		StandaloneSessionClusterEntrypoint entrypoint = new StandaloneSessionClusterEntrypoint();

		entrypoint.startCluster(args);
	}
}

[FLINK-7086] Add Flip-6 standalone session cluster entry point

This closes #4272.


package ca.thoughtwire.concurrent;

/**
 * Since {@link java.util.concurrent.atomic.AtomicLong} is not an interface, distributed
 * implementations need to be wrapped and their operations delegated. This is a universal
 * interface for implementations of atomic longs.
 *
 * @see HazelcastAtomicLong
 *
 * @author vanessa.williams
 */
public interface DistributedAtomicLong {

    /**
     * @return name of this atomic long
     */
    String getName();

    /**
     * @see java.util.concurrent.atomic.AtomicLong#incrementAndGet()
     */
    long incrementAndGet();

    /**
     * @see java.util.concurrent.atomic.AtomicLong#getAndIncrement()
     */
    long getAndIncrement();

    /**
     * @see java.util.concurrent.atomic.AtomicLong#decrementAndGet()
     */
    long decrementAndGet();

    /**
     * @see java.util.concurrent.atomic.AtomicLong#addAndGet(long)
     */
    long addAndGet(long delta);

    /**
     * @see java.util.concurrent.atomic.AtomicLong#getAndAdd(long)
     */
    long getAndAdd(long delta);

    /**
     * @see java.util.concurrent.atomic.AtomicLong#compareAndSet(long, long)
     */
    boolean compareAndSet(long expect, long update);

    /**
     * @see java.util.concurrent.atomic.AtomicLong#getAndSet(long)
     */
    long getAndSet(long newValue);

    /**
     * @see java.util.concurrent.atomic.AtomicLong#get()
     */
    long get();

    /**
     * @see java.util.concurrent.atomic.AtomicLong#set(long)
     */
    void set(long newValue);

}

Test commit one source file

Test commit one source file


/*
 * Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
 *
 * 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.search.nibrs.stagingdata.controller;

import java.util.List;

import org.joda.time.LocalDateTime;
import org.search.nibrs.stagingdata.model.Submission;
import org.search.nibrs.stagingdata.repository.SubmissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SubmissionController {
	@Autowired
	private SubmissionRepository submissionRepository;

	@PostMapping("/submissions")
	public Submission saveSubmission(@RequestBody Submission submission){
		/*
		 * To fulfill the relationship mapping.
		 */
		submission.getViolations()
			.forEach(violation->violation.setSubmission(submission));
		return submissionRepository.save(submission);
	}

	@GetMapping(value="/submissions")
	public List<Submission> getAllSubmissions(){
		return submissionRepository.findAll();
	}

	@GetMapping(value="/localDateTime")
	public String getLocalDateTime(){
		return LocalDateTime.now().toString();
	}

}

Add the controller to be able to save Submission via rest calls.


package com.yahoo.vespa.orchestrator.resources.providers;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.scala.DefaultScalaModule$;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

/**
 * Allow Scala case classes to be serialized to JSON
 * @author bjorncs
 */
@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
    private final ObjectMapper objectMapper;

    public ObjectMapperContextResolver() {
        objectMapper = new ObjectMapper();
        objectMapper.registerModule(DefaultScalaModule$.MODULE$);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return objectMapper;
    }
}

Add back ObjectMapper provider that was accidentally deleted


package org.motechproject.ScheduleTrackingDemo.listeners;

import org.motechproject.ivr.event.IVREventDelegate;
import org.motechproject.ivr.model.CallDetailRecord;
import org.motechproject.model.MotechEvent;
import org.motechproject.outbox.api.VoiceOutboxService;
import org.motechproject.outbox.api.model.MessagePriority;
import org.motechproject.outbox.api.model.OutboundVoiceMessage;
import org.motechproject.outbox.api.model.VoiceMessageType;
import org.motechproject.server.event.annotations.MotechListener;
import org.motechproject.server.voxeo.web.IvrController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

public class CallResultListener {

	private static Logger logger = LoggerFactory
			.getLogger(CallResultListener.class);

	@Autowired
	private VoiceOutboxService outboxService;

	//For demo purposes, successful calls are also stored in the outbox
	@MotechListener(subjects = {"CALL_BUSY" , "CALL_FAIL", "CALL_NO_ANSWER", "CALL_SUCCESS"})
	public void execute(MotechEvent event) {
		System.out.println("Handling event: " + event.getSubject());
		logger.debug("Handled call event");

		//if (!event.getSubject().equals("CALL_SUCCESS")) { //Call was not successful, store in outbox

			String externalId = (String) event.getParameters().get(IvrController.CALL_RESULT_ID);

			CallDetailRecord cdr = (CallDetailRecord) event.getParameters().get(IVREventDelegate.CALL_DETAIL_RECORD_KEY);

			OutboundVoiceMessage outboundVoiceMessage = new OutboundVoiceMessage();
			outboundVoiceMessage.setPartyId(cdr.getPhoneNumber()); //Content is identified by phone number for now

			VoiceMessageType voiceMessageType = new VoiceMessageType();
			voiceMessageType.setCanBeReplayed(true);
			voiceMessageType.setCanBeSaved(true);
			voiceMessageType.setPriority(MessagePriority.MEDIUM);

			//Template work-around for now, template name is based on the content

			String content = (String) event.getParameters().get(IvrController.CALL_CONTENT);
			String template = content.replace(".xml", "");
			voiceMessageType.setTemplateName(template);

			outboundVoiceMessage.setVoiceMessageType(voiceMessageType);

			outboxService.addMessage(outboundVoiceMessage);

		}
	}

Call result listener listens on call result events raised by Voxeo


/*
 * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */
package org.opendaylight.controller.sal.common.util;

import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;

/**
 * @author mirehak
 *
 */
public class RpcErrors {

    /**
     * @param applicationTag
     * @param tag
     * @param info
     * @param severity
     * @param message
     * @param errorType
     * @param cause
     * @return {@link RpcError} implementation
     */
    public static RpcError getRpcError(String applicationTag, String tag, String info,
            ErrorSeverity severity, String message, ErrorType errorType, Throwable cause) {
        RpcErrorTO ret = new RpcErrorTO(applicationTag, tag, info, severity, message,
                errorType, cause);
        return ret;
    }

    private static class RpcErrorTO implements RpcError {

        private final String applicationTag;
        private final String tag;
        private final String info;
        private final ErrorSeverity severity;
        private final String message;
        private final ErrorType errorType;
        private final Throwable cause;

        /**
         * @param applicationTag
         * @param tag
         * @param info
         * @param severity
         * @param message
         * @param errorType
         * @param cause
         */
        protected RpcErrorTO(String applicationTag, String tag, String info,
                ErrorSeverity severity, String message, ErrorType errorType, Throwable cause) {
            super();
            this.applicationTag = applicationTag;
            this.tag = tag;
            this.info = info;
            this.severity = severity;
            this.message = message;
            this.errorType = errorType;
            this.cause = cause;
        }

        @Override
        public String getApplicationTag() {
            return applicationTag;
        }

        @Override
        public String getInfo() {
            return info;
        }

        @Override
        public String getMessage() {
            return message;
        }

        @Override
        public ErrorSeverity getSeverity() {
            return severity;
        }

        @Override
        public String getTag() {
            return tag;
        }

        @Override
        public Throwable getCause() {
            return cause;
        }

        @Override
        public ErrorType getErrorType() {
            return errorType;
        }
    }
}

Add helper class for RpcError interface

Add helper class for RpcError interface

Change-Id: I981d63d0c6ccc899a3f2db5985b16d31c8e2742e
Signed-off-by: Michal Rehak <ed647b1080b812bfbe42faed634d1d6f3097d57e@cisco.com>


package com.boundary.sdk.action;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;

public class ServletActionProcessor {

public void process(Exchange exchange) throws Exception {
        String contentType = exchange.getIn().getHeader(Exchange.CONTENT_TYPE, String.class);
        String path = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class);
        path = path.substring(path.lastIndexOf("/"));

        //assertEquals("Get a wrong content type", CONTENT_TYPE, contentType);
        // assert camel http header
        String charsetEncoding = exchange.getIn().getHeader(Exchange.HTTP_CHARACTER_ENCODING, String.class);
        //assertEquals("Get a wrong charset name from the message heaer", "UTF-8", charsetEncoding);
        // assert exchange charset
        //assertEquals("Get a wrong charset naem from the exchange property", "UTF-8", exchange.getProperty(Exchange.CHARSET_NAME));
        exchange.getOut().setHeader(Exchange.CONTENT_TYPE, contentType + "; charset=UTF-8");
        exchange.getOut().setHeader("PATH", path);
        exchange.getOut().setBody("<b>Hello World</b>");
    }

}

Add class to handle processing of servlet


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

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.xwiki.configuration.ConfigurationSource;
import org.xwiki.test.mockito.MockitoComponentMockingRule;

import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;

/**
 * Test class for {@link org.xwiki.lesscss.internal.LESSConfiguration}.
 *
 */
public class LESSConfigurationTest {

    @Rule
    public MockitoComponentMockingRule<LESSConfiguration> mocker =
            new MockitoComponentMockingRule<>(LESSConfiguration.class);

    private ConfigurationSource xwikiPropertiesSource;

    @Before
    public void setUp() throws Exception
    {
        this.xwikiPropertiesSource = this.mocker.getInstance(ConfigurationSource.class);
    }

    @Test
    public void maxSimultaneousCompilations() throws Exception
    {
        when(xwikiPropertiesSource.getProperty("lesscss.maximumSimultaneousCompilations",4)).thenReturn(4);
        int i = mocker.getComponentUnderTest().getMaximumSimultaneousCompilations();
        assertTrue(i == 4);
    }

    @Test
    public void generateSourceMaps() throws Exception
    {
        when(xwikiPropertiesSource.getProperty("lesscss.generateInlineSourceMaps", false)).thenReturn(true);
        boolean b  = mocker.getComponentUnderTest().isGenerateInlineSourceMaps();
        assertTrue(b == true);
    }
}

XWIKI-13128: Add the ability to output source maps in LESS compiled files.

* Add test for LESSConfiguration


package main;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public enum OptionType {
	PRIORITY("-p", "--priority", "priority") {
	}, START_TIME("-s", "--starttime", "from") {
	}, END_TIME("-d", "--deadline", "--endtime", "to", "by") {
	};

	static private final Map<String, OptionType> ALIAS_TABLE = new HashMap<String, OptionType>();
	static {
		for (OptionType opt: OptionType.values()) {
			// Normalising by lowercase all
			ALIAS_TABLE.put(opt.toString().toLowerCase(), opt);
			for (String alias: opt.aliases) {
				ALIAS_TABLE.put(alias.toLowerCase(), opt);
			}
		}
	}

	static public OptionType fromString(String value) {
		if (value == null) {
			throw new NullPointerException("Null alias");
		}

		// Normalising input
		OptionType opt = ALIAS_TABLE.get(value.toLowerCase());

		if (opt == null) {
			throw new IllegalArgumentException("Not an alias: " + value);
		}

		return opt;
	}
	private List<String> aliases;
	private OptionType(String... aliases) {
		this.aliases = Arrays.asList(aliases);
	}
}

Create an enum class to store aliases of option


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

public class Buggy {

    public void run() {
        Map<String, Integer> map = new HashMap<String, Integer>();

        map.put("one", new Integer(1));

        for (String key: map.keySet()) {
            if (key == "one") {
                System.out.print("content dump: " + map.get(key));
            }
        }
    }
}

Add class with logical bug and performance concerns.


/*
 * Copyright (C) 2015 Archie L. Cobbs. All rights reserved.
 */

package org.jsimpledb;

import java.util.NavigableSet;
import java.util.UUID;

import org.jsimpledb.annotation.JField;
import org.jsimpledb.annotation.JSimpleClass;
import org.jsimpledb.core.ObjId;
import org.jsimpledb.index.Index;
import org.jsimpledb.test.TestSupport;
import org.jsimpledb.util.NavigableSets;
import org.testng.annotations.Test;

public class IndexQuerySetsTest extends TestSupport {

    @Test
    @SuppressWarnings("unchecked")
    public void testNavigableSets() throws Exception {

        final JSimpleDB jdb = BasicTest.getJSimpleDB(Foo.class);

        final JTransaction jtx = jdb.createTransaction(true, ValidationMode.MANUAL);
        JTransaction.setCurrent(jtx);
        try {

            final Foo f1 = jtx.create(Foo.class);
            f1.setUUID(UUID.randomUUID());

            final NavigableSet<Foo> foos = jtx.queryIndex(Foo.class, "UUID", UUID.class).asMap().get(f1.getUUID());

            NavigableSets.<Foo>union(foos, NavigableSets.<Foo>empty());
            NavigableSets.<Foo>union(NavigableSets.<Foo>empty(), foos);

            NavigableSets.<Foo>intersection(foos, NavigableSets.<Foo>empty());
            NavigableSets.<Foo>intersection(NavigableSets.<Foo>empty(), foos);

            jtx.commit();

        } finally {
            JTransaction.setCurrent(null);
        }
    }

// Model Classes

    @JSimpleClass
    public abstract static class Foo implements JObject {

        @JField(indexed = true)
        public abstract UUID getUUID();
        public abstract void setUUID(UUID uuid);
    }
}

Add a unit test exhibiting a bug in NavigableSets.union().


public class NumArray {

    private int[] sums;

    public NumArray(int[] nums) {

        for (int i = 1; i < nums.length; i++) {
            nums[i] += nums[i - 1];
        }

        sums = nums;

    }

    public int sumRange(int i, int j) {

        if (i == 0) {
            return sums[j];
        }

        return sums[j] - sums[i - 1];

    }

}

/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */

Create : 303 Range Sum Query - Immutable


package com.jmb.springfactory.exceptions;

public class NotFoundException extends Exception {

  private static final long serialVersionUID = -7835455020535088700L;

  public NotFoundException() {
    super();
  }

  public NotFoundException(String message) {
    super(message);
  }

}

Implement a exception to indicate that an entity have not been founded


package me.anxuiz.settings.bukkit;

import javax.annotation.Nonnull;

import me.anxuiz.settings.Setting;
import me.anxuiz.settings.SettingCallback;
import me.anxuiz.settings.SettingManager;

import org.bukkit.entity.Player;

public abstract class PlayerSettingCallback implements SettingCallback {
    public abstract void notifyChange(@Nonnull Player player, @Nonnull Setting setting, @Nonnull Object oldValue, @Nonnull Object newValue);

    public void notifyChange(@Nonnull SettingManager manager, @Nonnull Setting setting, @Nonnull Object oldValue, @Nonnull Object newValue) {
        if(manager instanceof PlayerSettingManager) {
            Player player = ((PlayerSettingManager) manager).getPlayer();
            this.notifyChange(player, setting, oldValue, newValue);
        }
    }
}

Add a custom setting callback specific to players.


package com.crawljax.core;

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

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

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

import com.crawljax.browser.EmbeddedBrowser;
import com.crawljax.browser.WebDriverFirefox;
import com.crawljax.condition.eventablecondition.EventableConditionChecker;
import com.crawljax.util.PropertyHelper;

public class CandidateElementExtractorTest {

	private static EmbeddedBrowser browser;
	private static String url = "http://spci.st.ewi.tudelft.nl/demo/crawljax/";

	@BeforeClass
	public static void startup() {
		browser = new WebDriverFirefox();

		try {
			browser.goToUrl(url);
		} catch (CrawljaxException e) {
			e.printStackTrace();
			fail(e.getMessage());
		}

		try {
			Thread.sleep(400);
		} catch (InterruptedException e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	@Test
	public void testExtract() {
		CandidateElementExtractor extractor =
		        new CandidateElementExtractor(browser, new EventableConditionChecker());
		assertNotNull(extractor);
		try {

			String inc = "a:{}";
			TagElement tagElementInc = PropertyHelper.parseTagElements(inc);
			List<TagElement> includes = new ArrayList<TagElement>();
			includes.add(tagElementInc);

			List<CandidateElement> candidates =
			        extractor.extract(includes, new ArrayList<TagElement>(), true);

			assertNotNull(candidates);
			assertEquals(15, candidates.size());

		} catch (CrawljaxException e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	@Test
	public void testExtractExclude() {
		CandidateElementExtractor extractor =
		        new CandidateElementExtractor(browser, new EventableConditionChecker());
		assertNotNull(extractor);

		try {

			String inc = "a:{}";
			TagElement tagElementInc = PropertyHelper.parseTagElements(inc);
			List<TagElement> includes = new ArrayList<TagElement>();
			includes.add(tagElementInc);

			// now exclude some elements
			String exc = "div:{id=menubar}";

			List<TagElement> excludes = new ArrayList<TagElement>();
			TagElement tagElementExc = PropertyHelper.parseTagElements(exc);
			excludes.add(tagElementExc);

			List<CandidateElement> candidates = extractor.extract(includes, excludes, true);

			assertNotNull(candidates);
			assertEquals(11, candidates.size());

		} catch (CrawljaxException e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	@AfterClass
	public static void closeup() {
		browser.close();
	}
}

Make it possible to recursively exclude elements from candidates. This means an element will be excluded even when an ancestor is marked for exclusion.

also moved all the static stuff (from PropertiesHelper) out of the CanidateElementExtractor, and wrote a unit test class that tests the new functionality.

git-svn-id: 6e5f6f61bd1b925b71fe8065f445f9178a317ca5@55 7701cf9b-ed3c-0410-a7c3-1ff289697e89


package com.chrisahn.popularmovies;

import android.os.Parcel;
import android.os.Parcelable;

public class MovieContainer implements Parcelable{
    private String mPosterPath;
    private String mReleaseDate;
    private String mOriginalTitle;
    private float mVoteAverage;
    private String mOverview;

    public MovieContainer() {

    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mPosterPath);
        dest.writeString(mReleaseDate);
        dest.writeString(mOriginalTitle);
        dest.writeFloat(mVoteAverage);
        dest.writeString(mOverview);
    }

    public static final Parcelable.Creator<MovieContainer> CREATOR
            = new Parcelable.Creator<MovieContainer>() {
        public MovieContainer createFromParcel(Parcel in) {
            return new MovieContainer(in);
        }

        public MovieContainer[] newArray(int size) {
            return new MovieContainer[size];
        }
    };

    private MovieContainer(Parcel in) {
        mPosterPath = in.readString();
        mReleaseDate = in.readString();
        mOriginalTitle = in.readString();
        mVoteAverage = in.readFloat();
        mOverview = in.readString();
    }

    public String getPosterPath() {
        return mPosterPath;
    }

    public void setPosterPath(String posterPath) {
        mPosterPath = posterPath;
    }

    public String getReleaseDate() {
        return mReleaseDate;
    }

    public void setReleaseDate(String releaseDate) {
        mReleaseDate = releaseDate;
    }

    public String getOriginalTitle() {
        return mOriginalTitle;
    }

    public void setOriginalTitle(String originalTitle) {
        mOriginalTitle = originalTitle;
    }

    public float getVoteAverage() {
        return mVoteAverage;
    }

    public void setVoteAverage(float voteAverage) {
        mVoteAverage = voteAverage;
    }

    public String getOverview() {
        return mOverview;
    }

    public void setOverview(String overview) {
        mOverview = overview;
    }
}

Implement container for movie element storage, and as Parceable


package ie.omk.smpp.encoding;

import ie.omk.smpp.SMPPRuntimeException;

import java.io.UnsupportedEncodingException;

import org.testng.annotations.Test;

@Test
public class AlphabetEncodingSetCharsetTest {

    @Test(expectedExceptions = {SMPPRuntimeException.class})
    public void testResettingCharsetThrowsException() throws Exception {
        class TestEncoding extends AlphabetEncoding {
            TestEncoding() throws UnsupportedEncodingException {
                super(Integer.MAX_VALUE);
                setCharset("US-ASCII");
            }

            void resetCharset() throws UnsupportedEncodingException {
                setCharset("Latin-1");
            }
        }
        new TestEncoding().resetCharset();
    }
}

Test to ensure resetting charset is not possible.


/*
 * 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.facebook.presto.jdbc;

/**
 * @deprecated Use {@link io.prestosql.jdbc.PrestoDriver} instead.
 */
@Deprecated
public class PrestoDriver
        extends io.prestosql.jdbc.PrestoDriver {}

Support backward-compatible Driver classname in JDBC


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

public class TopLevel
{
	void test(Item[] items)
	{
		// Do something else

		for (int i = 0; i < items.length; ++i)
		{
			ItemData data = items[i].getData();
			allData.add(data);
			data.detach();
		}
		resetItemCount(items.length - 1);

		// Do some more stuff
	}

	void resetItemCount(int newCount){}

	List<ItemData> allData = new ArrayList<>();
}

class ItemData
{
	void detach(){}
}

class Item
{
	ItemData getData() { return data; }

	ItemData data;
}

// Issues
// #3 Only a single item is supported
// #6 Bug: Can't establish connection using a proxy
// #11 Bug: The app crashes if I try to use the last item

// Commits:
// #4 : Add support for multiple items
// #5 : Fix off-by-one error

Add a guide file for one of the use cases


/*
 * Zorbage: an algebraic data hierarchy for use in numeric processing.
 *
 * Copyright (C) 2016-2019 Barry DeZonia
 *
 * 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.
 */
package nom.bdezonia.zorbage.type.storage;

/**
 *
 * @author Barry DeZonia
 *
 */
public class ReadOnlyDataSource<U>
	implements IndexedDataSource<ReadOnlyDataSource<U>, U>
{
	private final IndexedDataSource<?,U> source;

	public ReadOnlyDataSource(IndexedDataSource<?,U> src) {
		this.source = src;
	}

	@Override
	public ReadOnlyDataSource<U> duplicate() {
		return new ReadOnlyDataSource<U>(source);
	}

	@Override
	public void set(long index, U value) {
		throw new IllegalArgumentException("cannot write to read only data source");
	}

	@Override
	public void get(long index, U value) {
		source.get(index, value);
	}

	@Override
	public long size() {
		return source.size();
	}

}

Add a read only data source filter

Add a read only data source filter


package dbtools.common.file;

import dbtools.common.utils.StrUtils;

import java.io.File;
import java.io.FilenameFilter;

public class FileUtils {
    public static String getOutputFileName(File parent, File file, String fileExt, String fileName, String folderName) {
        if (file == null || parent == null) {
            return null;
        }

        String outputFileName = null;
        if (parent.isDirectory()) {
            // Prepare the folder firstly
            String outputFolderName = String.format("%s%s", parent.getPath(), folderName);
            File folder = new File(outputFolderName);
            if (!folder.exists()) {
                folder.mkdir();
            }

            // Output file name
            outputFileName = String.format("%s\\%s", outputFolderName, file.getName());
        } else {
            outputFileName = file.getPath();
        }

        // Format the file name
        if (!StrUtils.isEmpty(outputFileName)) {
            if (outputFileName.toLowerCase().endsWith(fileExt)) {
                outputFileName = outputFileName.substring(0, outputFileName.length() - fileExt.length());
            }
            outputFileName = String.format("%s%s", outputFileName, fileName);
        }

        return outputFileName;
    }

    public static File[] findFiles(String filePath, final String fileExt, final String ignoreFileName) {
        if (StrUtils.isEmpty(filePath)) {
            return null;
        }

        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }

        // File or directory, while not iterate sub folders
        File[] files = null;
        if (file.isFile() && filePath.toLowerCase().endsWith(fileExt)) {
            files = new File[]{file};
        } else if (file.isDirectory()) {
            files = file.listFiles(new FilenameFilter() {
                // @Override
                public boolean accept(File dir, String name) {
                    if (StrUtils.isEmpty(name)) {
                        return false;
                    }
                    String str = name.toLowerCase();
                    return str.endsWith(fileExt) && !str.endsWith(ignoreFileName);
                }
            });
        }

        return files;
    }
}

Refactor the code for findFiles and getOutputFileName


package sizebay.catalog.client.model;

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

import java.io.Serializable;

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

    long id;
    long profileIdentificationId;
    int chest;
    int waist;
    int hip;
    int sleeve;
    int length;
    int insideLeg;
    int neck;
    int fist;
    int underBust;

    public static UserProfileMeasures empty() {

        UserProfileMeasures measures = new UserProfileMeasures();

        measures.setChest(0);
        measures.setWaist(0);
        measures.setHip(0);
        measures.setSleeve(0);
        measures.setLength(0);
        measures.setInsideLeg(0);
        measures.setNeck(0);
        measures.setFist(0);
        measures.setUnderBust(0);

        return measures;
    }

}

Create the Profile Measures class

Create the Profile Measures class


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

package com.solsticesquared.schelling.task;

import com.solsticesquared.schelling.SchellingExplorer;
import sim.engine.SimState;
import sim.engine.Steppable;

/**
 * Represents a task, implemented as a {@link Steppable}, that updates a
 * randomized collection of agents each step during a simulation.
 */
public class UpdateTask implements Steppable {

    @Override
    public void step(SimState simState) {
        final SchellingExplorer model = (SchellingExplorer)simState;
        model.getAgents().step(simState);
    }
}

Add task to update all agents (using a random collection).


package org.lodder.subtools.sublibrary;

/**
 * helper class to check the operating system this Java VM runs in
 *
 * please keep the notes below as a pseudo-license
 *
 * http://stackoverflow.com/questions/228477/how-do-i-programmatically-determine
 * -operating-system-in-java compare to
 * http://svn.terracotta.org/svn/tc/dso/tags
 * /2.6.4/code/base/common/src/com/tc/util/runtime/Os.java
 * http://www.docjar.com/html/api/org/apache/commons/lang/SystemUtils.java.html
 */
public final class OsCheck {
	/**
	 * types of Operating Systems
	 */
	public enum OSType {
		Windows, MacOS, Linux, Other
	};

	// cached result of OS detection
	protected static OSType detectedOS;

	/**
	 * detect the operating system from the os.name System property and cache
	 * the result
	 *
	 * @returns - the operating system detected
	 */
	public static OSType getOperatingSystemType() {
		if (detectedOS == null) {
			String OS = System.getProperty("os.name", "generic").toLowerCase();
			if ((OS.indexOf("mac") >= 0) || (OS.indexOf("darwin") >= 0)) {
				detectedOS = OSType.MacOS;
			} else if (OS.indexOf("win") >= 0) {
				detectedOS = OSType.Windows;
			} else if (OS.indexOf("nux") >= 0) {
				detectedOS = OSType.Linux;
			} else {
				detectedOS = OSType.Other;
			}
		}
		return detectedOS;
	}
}

Add helper class to check OS Type

Add helper class to check OS Type


// Copyright 2014, Kevin Ko <kevin@faveset.com>

package com.faveset.khttp;

import java.nio.ByteBuffer;
import java.util.Map;

class MessageBodyHandler implements StateHandler {
    public boolean handleState(NonBlockingConnection conn, ByteBuffer buf, HandlerState state) throws InvalidRequestException {
        HttpRequest req = state.getRequestBuilder();

        // Trim the data buff depending on request's headers.
        switch (req.getMethod()) {
            case GET:
                return handleGet(buf, state, req);

            case POST:
            case PUT:
            case HEAD:
            default:
                return handleRaw(buf, state, req);
        }
    }

    /**
     * @return true if the state is done processing.
     */
    private boolean handleGet(ByteBuffer buf, HandlerState state, HttpRequest req) throws InvalidRequestException {
        // TODO: handle conditionals
        // TODO: handle partials

        // TODO: where do you assign the OnRequestCallback to state?
        HandlerState.OnRequestCallback handler = state.getOnRequestCallback();

        ByteBuffer getBuf = buf.duplicate();
        // Get methods have no payload.
        getBuf.clear();
        return handler.onRequest(req, getBuf, state.getResponseWriter());
    }

    private boolean handleRaw(ByteBuffer buf, HandlerState state, HttpRequest req) throws InvalidRequestException {
        HandlerState.OnRequestCallback handler = state.getOnRequestCallback();
        return handler.onRequest(req, buf, state.getResponseWriter());
    }
}

Add rudimentary request body handler.

Add rudimentary request body handler.


package org.bouncycastle.crypto.tls;

/**
 * RFC 4492 5.1.2
 */
public class ECPointFormat
{
    public static final short uncompressed = 0;
    public static final short ansiX962_compressed_prime = 1;
    public static final short ansiX962_compressed_char2 = 2;

    /*
     * reserved (248..255)
     */
}

Add another new TLS name space from RFC 4492


/***********************************************************************
 * Copyright (c) 2006 The Apache Software Foundation.                  *
 * All rights reserved.                                                *
 * ------------------------------------------------------------------- *
 * 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.james.transport.matchers;

import org.apache.mailet.GenericMatcher;

public class SMTPAuthSuccessfulTest extends AbstractHasMailAttributeTest {

    private final String SMTP_AUTH_USER_ATTRIBUTE_NAME = "org.apache.james.SMTPAuthUser";

    protected String getHasMailAttribute() {
        return "";
    }

    protected GenericMatcher createMatcher() {
        return new SMTPAuthSuccessful();
    }

    protected String getConfigOption() {

        return "SMTPAuthSuccessful";
    }

    protected void init() {
        super.init();
        setMailAttributeName(SMTP_AUTH_USER_ATTRIBUTE_NAME);
    }

}

Add junit test for SMTPAuthSuccessful matcher

git-svn-id: de9d04cf23151003780adc3e4ddb7078e3680318@416426 13f79535-47bb-0310-9956-ffa450edef68


/**
 * Project Distributed Transactions.
 * Copyright Michał Szczygieł, 2013.
 * Created at Dec 28, 2013.
 */
package com.m4gik;

import java.io.File;

import javax.sql.DataSource;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * This class sets base data sources for project.
 *
 * @author m4gik <michal.szczygiel@wp.pl>
 *
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/META-INF/spring/data-source-context.xml")
public class BaseDataSource {

    /**
     * Method for logging.
     */
    @BeforeClass
    @AfterClass
    public static void clearLog() {

        // Ensure that Atomikos logging directory exists
        File dir = new File("atomikos");
        if (!dir.exists()) {
            dir.mkdir();
        }

        // ...and delete any stale locks (this would be a sign of a crash)
        File tmlog = new File("atomikos/tmlog.lck");
        if (tmlog.exists()) {
            tmlog.delete();
        }
    }

    /**
     * JDBC object to the Finance.
     */
    private SimpleJdbcTemplate jdbcFinance;

    /**
     * JDBC object to the warehouse in Finland.
     */
    private SimpleJdbcTemplate jdbcWarehouseFinland;

    /**
     * JDBC object to the warehouse in Poland.
     */
    private SimpleJdbcTemplate jdbcWarehousePoland;

    /**
     * @return the jdbcFinance
     */
    public SimpleJdbcTemplate getJdbcFinance() {
        return jdbcFinance;
    }

    /**
     * @return the jdbcWarehouseFinland
     */
    public SimpleJdbcTemplate getJdbcWarehouseFinland() {
        return jdbcWarehouseFinland;
    }

    /**
     * @return the jdbcWarehousePoland
     */
    public SimpleJdbcTemplate getJdbcWarehousePoland() {
        return jdbcWarehousePoland;
    }

    /**
     * This method set data source for proper source from
     * data-source-context.xml.
     *
     * @param dataSourceWarehousePoland
     * @param dataSourceWarehouseFinland
     * @param dataSourceFinance
     */
    @Autowired
    public void setDataSources(
            @Qualifier("dataSourceWarehousePoland") DataSource dataSourceWarehousePoland,
            @Qualifier("dataSourceWarehouseFinland") DataSource dataSourceWarehouseFinland,
            @Qualifier("dataSourceFinance") DataSource dataSourceFinance) {
        this.jdbcWarehousePoland = new SimpleJdbcTemplate(
                dataSourceWarehousePoland);
        this.jdbcWarehouseFinland = new SimpleJdbcTemplate(
                dataSourceWarehouseFinland);
        this.jdbcFinance = new SimpleJdbcTemplate(dataSourceFinance);
    }
}

Add class to set base data sources

Add class to set base data sources


package com.matao.Q6;

import com.matao.common.TreeNode;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class ConstructBinaryTreeTest {

    private ConstructBinaryTree constructBinaryTree;

    @BeforeEach
    public void setUp() {
        constructBinaryTree = new ConstructBinaryTree();
    }

    /**
     *  Normal Binary Tree
     *              1
     *           /     \
     *          2       3
     *         /       / \
     *        4       5   6
     *         \         /
     *          7       8
     */
    @Test
    public void testNormalBinaryTree() {
        int[] pre = {1, 2, 4, 7, 3, 5, 6, 8};
        int[] in = {4, 7, 2, 1, 5, 3, 8, 6};
        TreeNode root = constructBinaryTree.reConstructBinaryTree(pre, in);
        constructBinaryTree.preTraverse(root);
        constructBinaryTree.inTraverse(root);
    }
}

TEST add unit test for reconstruct binary tree


package com.github.sparkcaller;

import picard.vcf.MergeVcfs;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class Utils {
    /*
    Get all the files in the folder 'pathToFolder' ending with 'fileExtension', and return them as an ArrayList.
    */
    public static ArrayList<File> getFilesInFolder(String pathToFolder, String fileExtension) {
        File folder = new File(pathToFolder);
        File[] listOfFiles = folder.listFiles();

        if (listOfFiles != null) {
            ArrayList<File> bamFiles = new ArrayList<File>();

            for (File file : listOfFiles) {
                if (file.isFile() && file.getName().endsWith(fileExtension)) {
                    bamFiles.add(file);
                }
            }
            return bamFiles;
        }

        System.err.println(String.format("The folder: %s is either empty or was not found!", folder.getName()));
        return null;
    }

    public static String removeExtenstion(String filepath, String ext) {
        return filepath.substring(0, filepath.length() - (ext.length()+1));
    }

    /*
    Merges all the VCF files specified in the list 'vcfFiles' and returns the filename of the output file.
    */
    public static String mergeVCFFiles(List<File> vcfFiles, String outputFileName) {
        MergeVcfs mergeEngine = new MergeVcfs();
        mergeEngine.INPUT = vcfFiles;

        // Only pass the output file as an argument,
        // as it is more efficient to set the input files directly in the object.
        String outputArgs[] = {"O=" + outputFileName};

        mergeEngine.instanceMain(outputArgs);
        return outputFileName;
    }

    public static Properties loadConfigFile(String configFilepath) {
        Properties prop = new Properties();
        InputStream input = null;

        try {
            input = new FileInputStream(configFilepath);
            prop.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return prop;
    }

    public static ArrayList<String> possibleStringToArgs(String maybeString) {
        if (maybeString == null) {
            return null;
        }

        String[] args = maybeString.split("\\s+");
        return new ArrayList<String>(Arrays.asList(args));
    }
}

Create a class containing some file related utilities commonly used in this project.