/*
 * 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.commons.compress.archivers;

/**
 * Exception thrown by ArchiveStreamFactory if a format is
 * requested/detected that doesn't support streaming.
 * @since 1.8
 */
public class StreamingNotSupportedException extends ArchiveException {
    private final String format;

    /**
     * Creates a new StreamingNotSupportedException.
     * @param format the format that has been requested/detected.
     */
    public StreamingNotSupportedException(String format) {
        super("The " + format + " doesn't support streaming.");
        this.format = format;
    }

    /**
     * Returns the format that has been requested/detected.
     * @return the format that has been requested/detected.
     */
    public String getFormat() {
        return format;
    }

}

/*
 * 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.commons.compress.archivers;

/**
 * Exception thrown by ArchiveStreamFactory if a format is
 * requested/detected that doesn't support streaming.
 * @since 1.8
 */
public class StreamingNotSupportedException extends ArchiveException {

    private static final long serialVersionUID = 1L;

    private final String format;

    /**
     * Creates a new StreamingNotSupportedException.
     * @param format the format that has been requested/detected.
     */
    public StreamingNotSupportedException(String format) {
        super("The " + format + " doesn't support streaming.");
        this.format = format;
    }

    /**
     * Returns the format that has been requested/detected.
     * @return the format that has been requested/detected.
     */
    public String getFormat() {
        return format;
    }

}

Add missing serial version ID (default).

git-svn-id: fb13a56e2874bbe7f090676f40e1dce4dcf67111@1572570 13f79535-47bb-0310-9956-ffa450edef68


/*
 * 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.trellisldp.http.impl;

import static java.time.Instant.now;
import static java.util.Optional.ofNullable;
import static java.util.UUID.randomUUID;
import static org.trellisldp.spi.RDFUtils.getInstance;

import java.time.Instant;
import java.util.Optional;

import org.apache.commons.rdf.api.IRI;

import org.trellisldp.spi.Session;
import org.trellisldp.vocabulary.Trellis;

/**
 * @author acoburn
 */
public class HttpSession implements Session {

    private final IRI identifier = getInstance().createIRI("trellis:session/" + randomUUID());
    private final IRI agent;
    private final IRI delegatedBy;
    private final Instant created;

    /**
     * Create an HTTP-based session
     * @param agent the agent
     * @param delegatedBy the delegatedBy value
     */
    public HttpSession(final IRI agent, final IRI delegatedBy) {
        this.agent = agent;
        this.delegatedBy = delegatedBy;
        this.created = now();
    }

    /**
     * Create an HTTP-based session
     * @param agent the agent
     */
    public HttpSession(final IRI agent) {
        this(agent, null);
    }

    /**
     * Create an HTTP-based session
     */
    public HttpSession() {
        this(Trellis.AnonymousUser);
    }

    @Override
    public IRI getIdentifier() {
        return identifier;
    }

    @Override
    public IRI getAgent() {
        return agent;
    }

    @Override
    public Optional<IRI> getDelegatedBy() {
        return ofNullable(delegatedBy);
    }

    @Override
    public Instant getCreated() {
        return created;
    }
}

Move session class to impl package

Move session class to impl package


/**
 * Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.engine.exec;

import static org.testng.Assert.assertEquals;

import org.mockito.Mockito;
import org.testng.annotations.Test;

import com.opengamma.engine.view.cycle.SingleComputationCycle;
import com.opengamma.util.test.TestGroup;

/**
 * Tests the {@link BatchExecutorFactory} class
 */
@Test(groups = TestGroup.UNIT)
public class BatchExecutorFactoryTest {

  public void testCreateExecutor() {
    final BatchExecutorFactory factory = new BatchExecutorFactory(new SingleNodeExecutorFactory());
    final SingleComputationCycle cycle = Mockito.mock(SingleComputationCycle.class);
    final DependencyGraphExecutor executor = factory.createExecutor(cycle);
    assertEquals(executor.getClass(), BatchExecutor.class);
  }

  public void testToString() {
    final BatchExecutorFactory factory = new BatchExecutorFactory(new SingleNodeExecutorFactory());
    assertEquals(factory.toString(), "BatchExecutorFactory delegating to SingleNodeExecutorFactory");
  }

}

Increase test coverage of package

[PLAT-3584] Increase test coverage of package


package edu.umd.cs.findbugs.tools;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.bcel.Constants;
import org.apache.bcel.classfile.Constant;

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

/**
 * Filter a property database, only passing through the annotations on public or protected methods
 */
public class FilterPropertyDatabase {

    final static int FLAGS = Constants.ACC_PROTECTED | Constants.ACC_PUBLIC;
    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
       BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
       Pattern p = Pattern.compile(",([0-9]+)|");
       while (true) {
           String s = in.readLine();
           if (s == null) break;
           Matcher m = p.matcher(s);
           if (m.find()) {
               int value = Integer.parseInt(m.group(1));
               if ((value & FLAGS) != 0)
                   System.out.println(s);
           }

       }

    }

}

Add utility method for filtering a property database

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


package com.github.pedrovgs.sample;

import android.test.ActivityInstrumentationTestCase2;
import com.github.pedrovgs.lynx.LynxActivity;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withSpinnerText;
import static android.support.test.espresso.matcher.ViewMatchers.withText;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class LynxActivityDefaultValues extends ActivityInstrumentationTestCase2<LynxActivity> {

  private static final String VERBOSE_TRACE_LEVEL = "VERBOSE";

  public LynxActivityDefaultValues() {
    super(LynxActivity.class);
  }

  @Override protected void setUp() throws Exception {
    super.setUp();
    getActivity();
  }

  public void testDoesNotUseFilterByDefault() {
    onView(withId(R.id.et_filter)).check(matches(withText("")));
  }

  public void testUsesVerboseTraceLevelFilterByDefault() {
    onView(withId(R.id.sp_filter)).check(matches(withSpinnerText(VERBOSE_TRACE_LEVEL)));
  }
}

Add some acceptance tests to check default values for LynxActivity when it's created without any special configuration.


package com.alexrnl.jbetaseries.request.shows;

import com.alexrnl.jbetaseries.request.APIAddresses;
import com.alexrnl.jbetaseries.request.Request;
import com.alexrnl.jbetaseries.request.Verb;
import com.alexrnl.jbetaseries.request.parameters.ShowId;

/**
 * Request for deleting a recommendation from the logged account.

 * @author Alex
 */
public class ShowDeleteRecommendation extends Request {

	/**
	 * Constructor #1.

	 * @param recommendationId
	 *        the id of the recommendation to delete.
	 */
	public ShowDeleteRecommendation (final Integer recommendationId) {
		super(Verb.DELETE, APIAddresses.SHOWS_RECOMMENDATION);
		addParameter(new ShowId(recommendationId));
	}
}

Add the shows/recommendation request (DELETE)


package leetcode.minimum_size_subarray_sum;

public class Solution {
    public int minSubArrayLen(int s, int[] nums) {
        int start = 0, end = 0;
        int sum = 0;
        if(nums == null || nums.length == 0 || s == 0) return 0;
        int len = nums.length;
        int minlen = nums.length + 1;
        for(start = 0; start < len; start++){
            sum += nums[start];
            while(sum >= s){
                minlen = Math.min(minlen, start - end + 1);
                sum -= nums[end++];
            }
        }
        if(minlen == nums.length + 1){
            minlen = 0;
        }
        return minlen;
    }
}

Add java solution for 209. Minimum Size Subarray Sum

209. Minimum Size Subarray Sum: https://leetcode.com/problems/minimum-size-subarray-sum/


// Copyright 2018 The Bazel Authors. 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 com.google.devtools.build.lib.analysis;

import static org.junit.Assert.fail;

import com.google.devtools.build.lib.analysis.util.AnalysisTestCase;
import com.google.devtools.build.lib.clock.BlazeClock;
import com.google.devtools.build.lib.vfs.Dirent;
import com.google.devtools.build.lib.vfs.FileSystem;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.inmemoryfs.InMemoryFileSystem;
import java.io.IOException;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/**
 * Tests verifying appropriate propagation of {@link InterruptedException} during filesystem
 * operations.
 */
@RunWith(JUnit4.class)
public class InterruptedExceptionTest extends AnalysisTestCase {

  private final Thread mainThread = Thread.currentThread();

  @Override
  protected FileSystem createFileSystem() {
    return new InMemoryFileSystem(BlazeClock.instance()) {
      @Override
      protected Collection<Dirent> readdir(Path path, boolean followSymlinks) throws IOException {
        if (path.toString().contains("causes_interrupt")) {
          mainThread.interrupt();
        }
        return super.readdir(path, followSymlinks);
      }
    };
  }

  @Test
  public void testGlobInterruptedException() throws Exception {
    scratch.file("a/BUILD", "sh_library(name = 'a', srcs = glob(['**/*']))");
    scratch.file("a/b/foo.sh", "testfile");
    scratch.file("a/causes_interrupt/bar.sh", "testfile");
    reporter.removeHandler(failFastHandler);

    try {
      update("//a:a");
      fail("Expected interrupted exception");
    } catch (InterruptedException expected) {
    }
  }

  @Test
  public void testSkylarkGlobInterruptedException() throws Exception {
    scratch.file("a/gen.bzl",
        "def gen():",
        "  native.filegroup(name = 'a', srcs = native.glob(['**/*']))");
    scratch.file("a/BUILD",
        "load('//a:gen.bzl', 'gen')",
        "gen()");

    scratch.file("a/b/foo.sh", "testfile");
    scratch.file("a/causes_interrupt/bar.sh", "testfile");
    reporter.removeHandler(failFastHandler);

    try {
      update("//a:a");
      fail("Expected interrupted exception");
    } catch (InterruptedException expected) {
    }
  }
}

Create tests verifying appropriate propagation of InterruptedException during filesystem operations.

RELNOTES: None.
PiperOrigin-RevId: 197740585


import java.util.Scanner;

/**
 * Created by Nathan_Zeplowitz on 4/11/15.
 */
public class RightTriangle {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.println("Enter a number");
        int n = in.nextInt();
        for (int i = 0; i < n; i++) {
            String line = "*";
            for (int j = 0; j < i; j++) {
                line += "*";
            }
            System.out.println(line);
        }

    }

}

Add Fourth Exercise Right Triangle

Add Fourth Exercise Right Triangle


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

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;

import io.github.bonigarcia.seljup.Options;
import io.github.bonigarcia.seljup.SeleniumExtension;

@ExtendWith(SeleniumExtension.class)
public class SeveralOptionsJupiterTest {

    @Options
    ChromeOptions chromeOptions = new ChromeOptions();
    {
        chromeOptions.addArguments("--use-fake-device-for-media-stream",
                "--use-fake-ui-for-media-stream");
    }

    @Options
    FirefoxOptions firefoxOptions = new FirefoxOptions();
    {
        firefoxOptions.addPreference("media.navigator.streams.fake", true);
        firefoxOptions.addPreference("media.navigator.permission.disabled",
                true);
    }

    @Test
    void webrtcTest(ChromeDriver chrome, FirefoxDriver firefox) {
        exercise(chrome, firefox);
    }

    void exercise(WebDriver... drivers) {
        for (WebDriver driver : drivers) {
            driver.get(
                    "https://webrtc.github.io/samples/src/content/devices/input-output/");
            assertThat(driver.findElement(By.id("video")).getTagName(),
                    equalTo("video"));
        }
    }

}

Add test using different @Options (for Chrome and Firefox) in the same class


package experimentalcode.erich;

import java.util.Iterator;

import org.w3c.dom.Node;

/**
 * Simple adapter class to iterate over a DOM tree nodes children.
 *
 * @author Erich Schubert
 *
 */
public final class XMLNodeIterator implements Iterable<Node>, Iterator<Node> {
  /**
   * Store the next node
   */
  private Node next;

  /**
   * Constructor with first element to iterate over.
   *
   * @param first first child of parent node.
   */
  public XMLNodeIterator(Node first) {
    super();
    this.next = first;
  }

  /**
   * Check if the next node is defined.
   */
  @Override
  public boolean hasNext() {
    return (next != null);
  }

  /**
   * Return next and advance iterator.
   */
  @Override
  public Node next() {
    Node cur = next;
    next = next.getNextSibling();
    return cur;
  }

  /**
   * Removal: unsupported operation.
   */
  @Override
  public void remove() {
    throw new UnsupportedOperationException("XMLNodeIterator doesn't support remove");
  }

  /**
   * Iterable interface adapter - clone.
   */
  @Override
  public Iterator<Node> iterator() {
    return new XMLNodeIterator(this.next);
  }
}

Simplify XML handling by using DOM instead of Pull API.


package com.stephenvinouze.linkifiedtextview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.support.v7.widget.AppCompatEditText;
import android.util.AttributeSet;

/**
 * Created by Stephen Vinouze on 16/10/15.
 */
public class FontEditText extends AppCompatEditText {

    public FontEditText(Context context) {
        super(context);
    }

    public FontEditText(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FontTextView);

        for (int i = 0; i < a.getIndexCount(); ++i) {

            int attr = a.getIndex(i);
            if (attr == R.styleable.FontTextView_tvFontName) {
                setFontName(a.getString(attr));
            }
        }

        a.recycle();
    }

    public void setFontName(String fontname) {
        setTypeface(Typeface.createFromAsset(getContext().getAssets(), "fonts/" + fontname));
    }

}

Add edit text with custom font

Add edit text with custom font


package de.lemona.android.testng.others;

import org.testng.annotations.Test;

public class TestFromXMLFile {

    @Test
    public void testFromXMLFile() {
        // Nothing to do, this should just run...
    }
}

Add a simple test invoked by "testng.xml".


/*
 *  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 dk.statsbiblioteket.summa.storage.database;

import dk.statsbiblioteket.summa.common.configuration.Configuration;
import dk.statsbiblioteket.summa.storage.api.Storage;
import dk.statsbiblioteket.summa.storage.database.h2.H2Storage;
import junit.framework.TestCase;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import sun.security.krb5.Config;

import java.io.IOException;

/**
 * Not a unit test. Used for debugging performance problems with H2 and relies on a local copy of a production
 * base being present.
 */
public class H2StorageDebugTest extends TestCase {
    private static Log log = LogFactory.getLog(H2StorageDebugTest.class);

    public static final String storageFolder = "/home/te/projects/summa/doms/";

    public void testPeek() throws IOException {
        H2Storage storage = getStorage();
        if (storage == null) {
            log.info("Unable to run debugging \"unit test\" as the expected H2 folder is not present: " + storageFolder);
            return;
        }

        try {
            System.out.println("******************" + storage.getStats());
        } finally {
            storage.close();
        }
    }

    private H2Storage getStorage() throws IOException {
        Configuration conf = Configuration.newMemoryBased(
                Storage.CONF_CLASS, H2Storage.class,
                DatabaseStorage.CONF_LOCATION, storageFolder,
                H2Storage.CONF_H2_SERVER_PORT, 9317,
                DatabaseStorage.CONF_FORCENEW, false,
                DatabaseStorage.CONF_CREATENEW, false
        );
        return new H2Storage(conf);
    }

}

Add debug not-unit test for H2

Add debug not-unit test for H2


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-09-30
 * Site       : https://www.acmicpc.net/problem/2920
 */

public class Boj2920 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] inputs = br.readLine().split(" ");
        if(inputs[0].equals("1") && inputs[1].equals("2") && inputs[2].equals("3") &&inputs[3].equals("4") &&inputs[4].equals("5") && inputs[5].equals("6") && inputs[6].equals("7") &&inputs[7].equals("8")){
            System.out.println("ascending");
        }else if(inputs[0].equals("8") && inputs[1].equals("7") && inputs[2].equals("6") &&inputs[3].equals("5") &&inputs[4].equals("4") && inputs[5].equals("3") && inputs[6].equals("2") &&inputs[7].equals("1")){
            System.out.println("descending");
        }else {
            System.out.println("mixed");
        }
    }

}

Solve No.2920 from Baekjoon Online Judge


/*
 * Copyright 2017 haeun kim
 *
 * 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 algorithm.boj;

import java.io.*;

/**
 * Created by haeun on 2017-10-03
 * Site       : https://www.acmicpc.net/problem/5622
 */

public class Boj5622 {

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        char[] input = br.readLine().toCharArray();
        int[] dial = new int[10];
        int result = 0;
        for(int i=0; i<input.length; i++){
            if(input[i]=='A' || input[i]=='B' || input[i]=='C'){
                result += 3;    //2
            } else if(input[i]=='D' || input[i]=='E' || input[i]=='F'){
                result += 4;    //3
            }else if(input[i]=='G' || input[i]=='H' || input[i]=='I'){
                result += 5;    //4
            }else if(input[i]=='J' || input[i]=='K' || input[i]=='L'){
                result += 6;
            }else if(input[i]=='M' || input[i]=='N' || input[i]=='O'){
                result += 7;
            }else if(input[i]=='P' || input[i]=='Q' || input[i]=='R' || input[i]=='S'){
                result += 8;
            }else if(input[i]=='T' || input[i]=='U' || input[i]=='V'){
                result += 9;
            }else if(input[i]=='W' || input[i]=='X' || input[i]=='Y' || input[i]=='Z'){
                result += 10;
            }else {
                result += 11;
            }
        }
        System.out.println(result);
    }

}

Solve No.5622 from Baekjoon Online Judge


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

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.int10.UnsignedInt10Member;

/**
 *
 * @author Barry DeZonia
 *
 */
public class TestBigList {

	@Test
	public void test() {

		UnsignedInt10Member value = G.UINT10.construct("99");
		UnsignedInt10Member zero = G.UINT10.construct();
		UnsignedInt10Member tmp = G.UINT10.construct();

		BigList<UnsignedInt10Member> b = new BigList<UnsignedInt10Member>();

		b.add(value);
		tmp.set(b.get(0));
		assertEquals(value.v(), tmp.v());

		for (int i = 0; i < 44; i++) {
			b.add(zero);
		}

		G.UINT10.succ().call(value, value);
		b.set(44, value);
		tmp.set(b.get(44));
		assertEquals(value.v(), tmp.v());

		/*
		b = new BigList<UnsignedInt10Member>(45L + Integer.MAX_VALUE);
		tmp.set(zero);
		b.set(44L + Integer.MAX_VALUE, value);
		tmp.set(b.get(44L + Integer.MAX_VALUE));
		assertEquals(value.v(), tmp.v());
		*/
	}
}

Define a simple test of BigList

Define a simple test of BigList


/*
 * Copyright (c) 2014 Sacred Scripture Foundation.
 * "All scripture is given by inspiration of God, and is profitable for
 * doctrine, for reproof, for correction, for instruction in righteousness:
 * That the man of God may be perfect, throughly furnished unto all good
 * works." (2 Tim 3:16-17)
 *
 * 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.sacredscripture.platform.api.bible.service;

/**
 * This service defines batch operations for maintaining the bible system.
 *
 * @author Paul Benedict
 * @since Sacred Scripture Platform 1.0
 */
public interface XmlBibleBatchService {

    /**
     * Populates the database with the bible canon (book types and groups) laid
     * out by the specified document. This method is only needed to setup a new
     * enivronment.
     * <p>
     * This method returns immediately. The loading is done as a batch process.
     *
     * @param docPath the document path accessible to the server
     */
    void loadCanon(String docPath);

}

Add service for batch xml processing

Add service for batch xml processing


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

import io.atomix.core.set.DistributedSetType;
import io.atomix.primitive.PrimitiveId;
import io.atomix.primitive.service.ServiceContext;
import io.atomix.primitive.service.impl.DefaultBackupInput;
import io.atomix.primitive.service.impl.DefaultBackupOutput;
import io.atomix.primitive.session.Session;
import io.atomix.primitive.session.SessionId;
import io.atomix.storage.buffer.Buffer;
import io.atomix.storage.buffer.HeapBuffer;
import io.atomix.utils.time.WallClock;
import org.junit.Test;

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

/**
 * Distributed multiset service test.
 */
public class DefaultDistributedMultisetServiceTest {
  @Test
  @SuppressWarnings("unchecked")
  public void testSnapshot() throws Exception {
    ServiceContext context = mock(ServiceContext.class);
    when(context.serviceType()).thenReturn(DistributedSetType.instance());
    when(context.serviceName()).thenReturn("test");
    when(context.serviceId()).thenReturn(PrimitiveId.from(1));
    when(context.wallClock()).thenReturn(new WallClock());

    Session session = mock(Session.class);
    when(session.sessionId()).thenReturn(SessionId.from(1));

    DefaultDistributedMultisetService service = new DefaultDistributedMultisetService();
    service.init(context);

    service.add("foo");

    Buffer buffer = HeapBuffer.allocate();
    service.backup(new DefaultBackupOutput(buffer, service.serializer()));

    service = new DefaultDistributedMultisetService();
    service.restore(new DefaultBackupInput(buffer.flip(), service.serializer()));

    assertTrue(service.contains("foo"));
  }
}

Add distributed multiset service backup/restore test.


package com.github.database.rider.core;

import com.github.database.rider.core.api.configuration.DBUnit;
import com.github.database.rider.core.api.dataset.DataSet;
import com.github.database.rider.core.model.User;
import com.github.database.rider.core.util.EntityManagerProvider;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import javax.persistence.EntityManager;
import java.util.List;

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

/**
 * Created by pestano on 26/02/16.
 */
@RunWith(JUnit4.class)
public class AlwaysCleanBeforeAfterIt {

    @Rule
    public DBUnitRule dbUnitRule = DBUnitRule.instance(EntityManagerProvider.instance("rules-it").connection());

    @BeforeClass
    public static void before(){
        EntityManager em = EntityManagerProvider.instance("rules-it").em();
        em.getTransaction().begin();
        em.createNativeQuery("DELETE FROM USER").executeUpdate();
        em.createNativeQuery("INSERT INTO USER VALUES (6,'user6')").executeUpdate();
        em.flush();
        em.getTransaction().commit();
        List<User> users = em.createQuery("select u from User u").getResultList();
        assertThat(users).isNotNull().hasSize(1);

    }

    @AfterClass
    public static void after(){
        List<User> users = EntityManagerProvider.instance("rules-it").em().createQuery("select u from User u").getResultList();
        if(users != null && !users.isEmpty()){
            fail("users should be empty");
        }
    }

    @Test
    @DataSet(value = "datasets/yml/users.yml")
    @DBUnit(alwaysCleanAfter = true, alwaysCleanBefore = true)
    public void shouldCleanDatabaseBefore() {
        List<User> users = EntityManagerProvider.instance("rules-it").em().createQuery("select u from User u").getResultList();
        assertThat(users).isNotNull().hasSize(2);//dataset has 2 users, user inserted in @Before must not be present
        User userInsertedInBefore = new User(6);//user inserted in @before has id 6
        assertThat(users).doesNotContain(userInsertedInBefore);
    }

}

Add test for alwaysCleanAfter and alwaysCleanBefore


package org.gluu.oxauth.service;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;

import org.gluu.oxauth.model.common.WebKeyStorage;
import org.gluu.oxauth.model.configuration.AppConfiguration;
import org.gluu.oxauth.model.crypto.AbstractCryptoProvider;
import org.slf4j.Logger;

/**
 * Crypto Provider
 *
 * @author Yuriy Movchan
 * @version 11/02/2018
 */
@ApplicationScoped
@Named
public class CryptoProviderProviderFactory {

    @Inject
    private Logger log;

    @Inject
    private AppConfiguration appConfiguration;

    @Produces
    @ApplicationScoped
    public AbstractCryptoProvider getCacheProvider() throws Exception {
        log.debug("Started to create crypto provider");

        WebKeyStorage webKeyStorage = appConfiguration.getWebKeysStorage();
        if (webKeyStorage == null) {
            throw new RuntimeException("Failed to initialize cryptoProvider, cryptoProviderType is not specified!");
        }

        AbstractCryptoProvider cryptoProvider = org.gluu.oxauth.model.crypto.CryptoProviderFactory.getCryptoProvider(appConfiguration);

        if (cryptoProvider == null) {
            throw new RuntimeException("Failed to initialize cryptoProvider, cryptoProviderType is unsupported: " + webKeyStorage);
        }

        return cryptoProvider;
    }

}

Allow to inject AbstractCryptoProvider into services


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

/**
 * This class exists to force the creation of a jar for the presto-thrift-spec module.
 * This is needed to deploy the presto-thrift-spec module to Nexus.
 */
public class PrestoThriftSpecDummy
{
}

Add a dummy class to presto-thrift-spec

Add a dummy class to presto-thrift-spec


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

package com.pushtechnology.adapters.rest.metrics;

import com.pushtechnology.adapters.rest.model.latest.EndpointConfig;
import com.pushtechnology.adapters.rest.model.latest.ServiceConfig;
import com.pushtechnology.diffusion.client.callbacks.ErrorReason;
import com.pushtechnology.diffusion.datatype.Bytes;

/**
 * Listener for Diffusion topic publication events.
 *
 * @author Push Technology Limited
 */
public interface PublicationListener {
    /**
     * Notified when an attempt to update a Diffusion topic is made.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param value the initial value
     */
    void onPublicationRequest(ServiceConfig serviceConfig, EndpointConfig endpointConfig, Bytes value);

    /**
     * Notified when a Diffusion topic is updated.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param value the initial value
     */
    void onPublication(ServiceConfig serviceConfig, EndpointConfig endpointConfig, Bytes value);

    /**
     * Notified when a Diffusion topic cannot be updated.
     *
     * @param serviceConfig the service
     * @param endpointConfig the endpoint
     * @param value the initial value
     * @param reason the cause of failure
     */
    void onPublicationFailed(
        ServiceConfig serviceConfig,
        EndpointConfig endpointConfig,
        Bytes value,
        ErrorReason reason);
}

Add listener interface for publication events.


/*
 * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
 * (the "License"). You may not use this work except in compliance with the License, which is
 * available at www.apache.org/licenses/LICENSE-2.0
 *
 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied, as more fully set forth in the License.
 *
 * See the NOTICE file distributed with this work for information regarding copyright ownership.
 */

package alluxio;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

/**
 * A rule for setting a system property to a value and then restoring the property to its old value.
 */
public final class SystemPropertyRule implements TestRule {
  private final String mPropertyName;
  private final String mValue;

  /**
   * @param propertyName the name of the property to set
   * @param value the value to set it to
   */
  public SystemPropertyRule(String propertyName, String value) {
    mPropertyName = propertyName;
    mValue = value;
  }

  @Override
  public Statement apply(final Statement statement, Description description) {
    return new Statement() {
      @Override
      public void evaluate() throws Throwable {
        String previousValue = System.getProperty(mPropertyName);
        System.setProperty(mPropertyName, mValue);
        try {
          statement.evaluate();
        } finally {
          if (previousValue == null) {
            System.clearProperty(mPropertyName);
          } else {
            System.setProperty(mPropertyName, previousValue);
          }
        }
      }
    };
  }
}

Add rule for temporarily setting a system property


/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2012, Red Hat, Inc., and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * 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.jboss.marshalling;

import java.io.IOException;

/**
 * A writer for class or object tables which simply writes a flat sequence of bytes.
 *
 * @author David M. Lloyd
 */
public final class ByteWriter implements ObjectTable.Writer, ClassTable.Writer {
    private final byte[] bytes;

    /**
     * Construct a new instance.
     *
     * @param bytes the bytes to write
     */
    public ByteWriter(final byte... bytes) {
        this.bytes = bytes;
    }

    public void writeObject(final Marshaller marshaller, final Object object) throws IOException {
        marshaller.write(bytes);
    }

    public void writeClass(final Marshaller marshaller, final Class<?> clazz) throws IOException {
        marshaller.write(bytes);
    }
}

Add a new byte writer class for class and object table implementations


public class Solution {

    public int maxSubArray(int[] nums) {

        int sum = 0;
        int max = Integer.MIN_VALUE;

        for (int i = 0; i < nums.length; i++) {

            sum += nums[i];

            if (max < sum) {
                max = sum;
            }

            if (sum < 0) {
                sum = 0;
            }

        }

        return max;

    }

}

Create : 53 Maximum Subarray

Create : 53 Maximum Subarray


package io.quarkus.undertow.test;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.is;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.commons.codec.Charsets;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;

import io.quarkus.test.QuarkusUnitTest;

public class MultipartConfigTestCase {

    @RegisterExtension
    static QuarkusUnitTest runner = new QuarkusUnitTest()
            .setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
                    .addClasses(MultipartServlet.class));

    @Test
    public void testMultipartConfig() {
        given().multiPart("file", "random.txt", "Some random file".getBytes(Charsets.UTF_8))
                .when().post("/foo").then()
                .statusCode(201)
                .body(is("OK"));
    }

    @WebServlet("/foo")
    @MultipartConfig()
    public static class MultipartServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            Part p = request.getPart("file");
            System.out.println(p.getName());
            response.setStatus(HttpServletResponse.SC_CREATED);
            try (PrintWriter out = response.getWriter()) {
                out.print("OK");
            }
        }
    }

}

Add failing test for Multipart bug

Add failing test for Multipart bug


package com.github.ggiamarchi.i18n.test;

import static org.junit.Assert.*;
import org.junit.Test;

import com.github.ggiamarchi.i18n.I18NGeneratorException;

public class I18NGeneratorExceptionTest {

	@Test
	public void constructI18NGeneratorExceptionTest() {

		I18NGeneratorException e;
		RuntimeException re;

		e = new I18NGeneratorException("a simple massage");
		assertEquals("a simple massage", e.getMessage());

		re = new RuntimeException("this is a RuntimeException");
		e = new I18NGeneratorException("a simple massage", re);
		assertEquals("a simple massage", e.getMessage());
		assertEquals(re, e.getCause());

		re = new RuntimeException("this is a RuntimeException");
		e = new I18NGeneratorException(re);
		assertEquals(re, e.getCause());
		assertTrue(e.getMessage().contains(re.getMessage()));

	}

}

Add I18NGeneratorException unit tests class


/*******************************************************************************
 * Copyright (c) 2014 Codenvy, S.A.
 * 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:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package com.codenvy.ide.editor.codemirror.client.jso;

import javax.annotation.Nullable;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.JsArrayString;

/**
 * Catalog of modes available in codemirror.
 * @see http://codemirror.net/doc/manual.html#addon_meta and http://codemirror.net/mode/meta.js
 */
public class CMModeInfoOverlay extends JavaScriptObject {

    /** JSO mandated protected constructor. */
    protected CMModeInfoOverlay() {}

    /**
     * Returns the human-readable name of the mode.
     * @return the name
     */
    public final native String getName() /*-{
        return this.name;
    }-*/;

    /**
     * Returns the mime-type.
     * @return the mime-type
     */
    public final native String getMime() /*-{
        return this.mime;
    }-*/;

    /**
     * Returns  the name of the mode file that defines this MIME.
     * @return the name of the mode file
     */
    public final native String getMode() /*-{
        return this.mode;
    }-*/;

    /**
     * Returns the optional array of MIME types for modes with multiple MIMEs associated
     * @return mime-types
     */
    @Nullable
    public final native JsArrayString getMimes() /*-{
        return this.mimes;
    }-*/;

    /**
     * Returns the optional array of file extensions associated with this mode.
     * @return file extensions
     */
    @Nullable
    public final native JsArrayString getExt() /*-{
        return this.ext;
    }-*/;
}

Create an overlay for mode info objects

Create an overlay for mode info objects


/*
 * Created on Apr 5, 2004
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package org.apache.commons.net.ftp.parser;

import junit.framework.Test;
import junit.framework.TestSuite;

/**
 * @author scohen
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class AllTests {

    public static Test suite() {
        TestSuite suite =
            new TestSuite("Test for org.apache.commons.net.ftp.parser");
        //$JUnit-BEGIN$
        suite.addTest(FTPTimestampParserImplTest.suite());
        suite.addTest(OS2FTPEntryParserTest.suite());
        suite.addTest(VMSFTPEntryParserTest.suite());
        suite.addTest(UnixFTPEntryParserTest.suite());
        suite.addTestSuite(DefaultFTPFileEntryParserFactoryTest.class);
        suite.addTest(EnterpriseUnixFTPEntryParserTest.suite());
        suite.addTest(OS400FTPEntryParserTest.suite());
        suite.addTest(NTFTPEntryParserTest.suite());
        suite.addTest(MVSFTPEntryParserTest.suite());

        //$JUnit-END$
        return suite;
    }
}

/*
 * Created on Apr 5, 2004
 *
 * To change the template for this generated file go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
package org.apache.commons.net.ftp.parser;

import junit.framework.Test;
import junit.framework.TestSuite;

/**
 * @author scohen
 *
 * To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Generation - Code and Comments
 */
public class AllTests {

    public static Test suite() {
        TestSuite suite =
            new TestSuite("Test for org.apache.commons.net.ftp.parser");
        //$JUnit-BEGIN$
        suite.addTest(FTPTimestampParserImplTest.suite());
        suite.addTest(OS2FTPEntryParserTest.suite());
        suite.addTest(VMSFTPEntryParserTest.suite());
        suite.addTest(UnixFTPEntryParserTest.suite());
        suite.addTestSuite(DefaultFTPFileEntryParserFactoryTest.class);
        suite.addTest(EnterpriseUnixFTPEntryParserTest.suite());
        suite.addTest(OS400FTPEntryParserTest.suite());
        suite.addTest(NTFTPEntryParserTest.suite());
        suite.addTest(MVSFTPEntryParserTest.suite());
        suite.addTest(NetwareFTPEntryParserTest.suite());

        //$JUnit-END$
        return suite;
    }
}

Add Netware parser test to all test suite

git-svn-id: 8e7fc3cb9b5e494b5390f56e4b66b18dc2b2e92b@394701 13f79535-47bb-0310-9956-ffa450edef68


package org.axonframework.messaging.metadata;

import org.axonframework.messaging.Message;

import java.util.Collections;
import java.util.Map;

/**
 * CorrelationDataProvider that provides the {@link Message#getIdentifier() identifier} of a {@link Message} to
 * other messages that are created as result of processing the first message.
 *
 * @author Rene de Waele
 */
public enum MessageOriginProvider implements CorrelationDataProvider {
    INSTANCE;

    /**
     * The default meta-data key, which is used to identify the {@link Message} that triggered another message
     */
    public static final String DEFAULT_CORRELATION_KEY = "message-origin";

    @Override
    public Map<String, ?> correlationDataFor(Message<?> message) {
        return Collections.singletonMap(DEFAULT_CORRELATION_KEY, message.getIdentifier());
    }
}

Add a correlation data provider that provides the original message identifier

When a Message is processed and another message is created as a result, this correlation data provider can be used to attach the identifier of the first message to the second message.


package to.etc.domui.util;

import javax.annotation.*;

import to.etc.domui.databinding.*;
import to.etc.webapp.annotations.*;

public class ObservableObject implements IObservableEntity {
	@Nullable
	private ObserverSupport<ObservableObject> m_osupport;

	@Nonnull
	protected ObserverSupport<ObservableObject> getObserverSupport() {
		ObserverSupport<ObservableObject> osupport = m_osupport;
		if(null == osupport) {
			osupport = m_osupport = new ObserverSupport<ObservableObject>(this);
		}
		return osupport;
	}

	protected <V> void firePropertyChange(@Nonnull String propertyName, V old, V nw) {
		ObserverSupport< ? > osupport = m_osupport;
		if(null == osupport)					// Nothing observing?
			return;
		osupport.fireModified(propertyName, old, nw);
	}

	@Override
	@Nonnull
	public IObservableValue< ? > observableProperty(@Nonnull @GProperty String property) {
		return getObserverSupport().getValueObserver(property);
	}
}

Create generic observable base class which contains basic observer infra


package com.proofpoint.cloudmanagement.service.inventoryclient;

import com.google.common.collect.ImmutableSet;
import com.proofpoint.json.JsonCodec;
import org.testng.Assert;
import org.testng.annotations.Test;

import static com.proofpoint.testing.EquivalenceTester.equivalenceTester;

public class TestInventorySystem
{
    private static final JsonCodec<InventorySystem> CODEC = JsonCodec.jsonCodec(InventorySystem.class);

    @Test
    public void testEquivalence()
    {
        equivalenceTester()
                .addEquivalentGroup(
                        new InventorySystem("name1"),
                        new InventorySystem("name1").setSerialNumber("serial1").setRoles(ImmutableSet.of("111")),
                        new InventorySystem("name1").setSerialNumber("serial2").setRoles(ImmutableSet.of("111")),
                        new InventorySystem("name1").setSerialNumber("serial1").setRoles(ImmutableSet.of("222")))
                .addEquivalentGroup(
                        new InventorySystem("name2"),
                        new InventorySystem("name2").setSerialNumber("serial1").setRoles(ImmutableSet.of("111")),
                        new InventorySystem("name2").setSerialNumber("serial2").setRoles(ImmutableSet.of("111")),
                        new InventorySystem("name2").setSerialNumber("serial1").setRoles(ImmutableSet.of("222")))
                .check();
    }

    @Test(expectedExceptions = NullPointerException.class)
    public void testNullNameThrows()
    {
        new InventorySystem(null);
    }

    @Test
    public void testJsonRoundTrip()
    {
        InventorySystem original = new InventorySystem("test").setSerialNumber("serial").setRoles(ImmutableSet.of("role1", "role2"));

        String encoded = CODEC.toJson(original);
        InventorySystem decoded = CODEC.fromJson(encoded);

        Assert.assertEquals(decoded.getFqdn(), original.getFqdn());
        Assert.assertEquals(decoded.getSerialNumber(), original.getSerialNumber());
        Assert.assertEquals(decoded.getRoles(), original.getRoles());
    }
}

Add tests for InventorySystem class

Add tests for InventorySystem class


package org.bedework.util.deployment;

import org.w3c.dom.Element;

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

/** Represent a jboss-deployment-structure.xml file.
 *
 * @author douglm
 */
public class JbossDeploymentStructureXml extends XmlFile {
  private static final String jbossAllTemplate =
        "<jboss-deployment-structure xmlns=\"urn:jboss:deployment-structure:1.1\">\n" +
        "    <deployment>\n" +
        //"        <exclusions>\n" +
        //"            <module name=\"org.javassist\" />\n" +
        //"        </exclusions>\n" +
        "    </deployment>\n" +
        "</jboss-deployment-structure>\n" +
        "\n";

  private final PropertiesChain props;

  public static void generate(final File earMeta) throws Throwable {
    // Generate a jboss-all.xml
    final File jbossAllF = new File(earMeta.getAbsolutePath(),
                                    "jboss-deployment-structure.xml");

    final FileOutputStream fos = new FileOutputStream(jbossAllF, false);
    fos.write(jbossAllTemplate.getBytes());
    fos.close();
  }

  public JbossDeploymentStructureXml(final Utils utils,
                                     final File metaInf,
                                     final PropertiesChain props) throws Throwable {
    super(utils, metaInf, "jboss-deployment-structure.xml", false);
    this.props = props;
  }

  public void update() throws Throwable {
    utils.debug("Update " + theXml.getAbsolutePath());

    final List<String> earExclusions =
            props.listProperty("app.ear.exclusions");

    if (earExclusions != null) {
      for (final String ed: earExclusions) {
        addExclusion(ed);
      }
    }
  }

  public void addExclusion(final String exc) throws Throwable {
    final Element depNode = findElement(root, "deployment");
    if (depNode == null) {
      utils.error("Cannot locate node deployment");
      return;
    }

    Element excsNode = findElement(depNode, "exclusions");
    if (excsNode == null) {
      excsNode = doc.createElement("exclusions");
      depNode.appendChild(excsNode);
    }

    final Element mdlNode = doc.createElement("module");
    mdlNode.setAttribute("name", exc);

    excsNode.appendChild(mdlNode);

    updated = true;
  }
}

Add jboss deployment structure fro wildfly


package com.test.graphs;

import java.util.LinkedList;

import com.graphs.GraphAdjacencyListRepresentation;
import com.graphs.ShortestPathWithDijkstra;

import junit.framework.TestCase;

public class TestShortestPathWithDijkstra extends TestCase{

    public void testShortestPathWithDijkstra() {

        GraphAdjacencyListRepresentation graph = new GraphAdjacencyListRepresentation(13, true);
        graph.addEdge(0, 5, 3);
        graph.addEdge(0, 1, 9);

        graph.addEdge(2, 0, 2);
        graph.addEdge(2, 3, 15);

        graph.addEdge(3, 5, 14);
        graph.addEdge(3, 2, 8);

        graph.addEdge(4, 3, 44);
        graph.addEdge(4, 2, 6);

        graph.addEdge(5, 4, 1);

        graph.addEdge(6, 4, 2);
        graph.addEdge(6, 8, 3);
        graph.addEdge(6, 0, 11);
        graph.addEdge(6, 9, 23);

        graph.addEdge(7, 6, 9);

        graph.addEdge(8, 6, 3);

        graph.addEdge(9, 11, 8);
        graph.addEdge(9, 10, 5);

        graph.addEdge(10, 12, 17);

        graph.addEdge(11, 12, 33);

        graph.addEdge(12, 9, 10);

        ShortestPathWithDijkstra sp = new ShortestPathWithDijkstra(graph, 6);
        assertEquals(0, sp.getShortestDistance(6));
        assertEquals(23, sp.getShortestDistance(3));

        LinkedList<Integer> pathTo3 = new LinkedList<>();
        pathTo3.add(6);
        pathTo3.add(4);
        pathTo3.add(2);
        pathTo3.add(3);

        assertEquals(true, pathTo3.equals(sp.getShortestPath(3)));

    }

}

Add JUnit test for ShortestPathWithDijkstra


/*
 *  JavaSMT is an API wrapper for a collection of SMT solvers.
 *  This file is part of JavaSMT.
 *
 *  Copyright (C) 2007-2019  Dirk Beyer
 *  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.sosy_lab.java_smt.solvers.yices2;

import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_exists;
import static org.sosy_lab.java_smt.solvers.yices2.Yices2NativeApi.yices_forall;

import com.google.common.primitives.Ints;
import java.util.List;
import org.sosy_lab.java_smt.api.SolverException;
import org.sosy_lab.java_smt.basicimpl.AbstractQuantifiedFormulaManager;
import org.sosy_lab.java_smt.basicimpl.FormulaCreator;

public class Yices2QuantifiedFormulaManager
    extends AbstractQuantifiedFormulaManager<Integer, Integer, Long, Integer> {

  protected Yices2QuantifiedFormulaManager(
      FormulaCreator<Integer, Integer, Long, Integer> pCreator) {
    super(pCreator);
    // TODO Auto-generated constructor stub
  }

  @Override
  protected Integer eliminateQuantifiers(Integer pExtractInfo)
      throws SolverException, InterruptedException {
    // TODO Auto-generated method stub
    throw new UnsupportedOperationException("Yices does not support eliminating Quantifiers.");
  }

  @Override
  public Integer mkQuantifier(Quantifier pQ, List<Integer> pVars, Integer pBody) {
    // TODO Auto-generated method stub
    if (pVars.isEmpty()) {
      throw new IllegalArgumentException("Empty variable list for Quantifier.");
    } else {
      int[] terms = Ints.toArray(pVars);
      if (pQ == Quantifier.FORALL) {
        return yices_forall(terms.length, terms, pBody);
      } else if (pQ == Quantifier.EXISTS) {
        return yices_exists(terms.length, terms, pBody);
      }
    }
    return null;
  }

}

Add QuantifiedFormulaManager (not yet active)

Added Yices2QuantifiedFormulaManager but not yet usable as it requires
variables created with yices_new_variable() instead of
yices_new_uininterpreted_term().


package com.atb.demo.stagger.util;

import org.junit.Test;

import static org.junit.Assert.assertNull;

public class UtilsTest {

    @Test
    public void testNullAllowedValuesReturnsNull() throws Exception {
        assertNull(Utils.allowableValuesToString(null));
    }

}

Add a single unit test

Add a single unit test


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

package org.scijava.plugin;

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

import org.junit.Test;
import org.scijava.Context;

/**
 * Tests {@link PluginFinder}.
 *
 * @author Curtis Rueden
 */
public class PluginFinderTest {

	/**
	 * Tests that the {@code scijava.plugin.blacklist} system property works to
	 * exclude plugins from the index, even when they are on the classpath.
	 */
	@Test
	public void testPluginBlacklistSystemProperty() {
		// check that the plugin is there, normally
		Context context = new Context(PluginService.class);
		PluginService pluginService = context.service(PluginService.class);
		PluginInfo<SciJavaPlugin> plugin = //
			pluginService.getPlugin(BlacklistedPlugin.class);
		assertSame(BlacklistedPlugin.class.getName(), plugin.getClassName());
		context.dispose();

		// blacklist the plugin, then check that it is absent
		System.setProperty("scijava.plugin.blacklist", ".*BlacklistedPlugin");
		context = new Context(PluginService.class);
		pluginService = context.service(PluginService.class);
		plugin = pluginService.getPlugin(BlacklistedPlugin.class);
		assertNull(plugin);
		context.dispose();

		// reset the system
		System.getProperties().remove("scijava.plugin.blacklist");
	}

	@Plugin(type = SciJavaPlugin.class)
	public static class BlacklistedPlugin implements SciJavaPlugin {
		// NB: No implementation needed.
	}

}

Add tests for the plugin blacklisting feature


package org.pdxfinder;

import org.neo4j.ogm.session.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.data.neo4j.transaction.Neo4jTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * Test configuration sets up the embedded Neo4J driver in memory mode
 */

@Configuration
@EnableTransactionManagement
@ComponentScan(value = "org.pdxfinder")
@EnableNeo4jRepositories("org.pdxfinder.graph.repositories")
public class TestConfig {

  @Bean
  public org.neo4j.ogm.config.Configuration getConfiguration() {
    org.neo4j.ogm.config.Configuration config = new org.neo4j.ogm.config.Configuration();

    // To persist the database, uncomment this section
    //        String pathToDb = Paths.get(".").toAbsolutePath().normalize().toString() + "/target/test_graph.db";
    //        config
    //                .driverConfiguration()
    //                .setDriverClassName("org.neo4j.ogm.drivers.embedded.driver.EmbeddedDriver")
    //                .setURI("file://" + pathToDb);
    //
    //        System.out.println(config);

    return config;
  }

  @Bean
  public SessionFactory sessionFactory() {
    return new SessionFactory(getConfiguration(), "org.pdxfinder");
  }

  @Bean
  public Neo4jTransactionManager transactionManager() {
    return new Neo4jTransactionManager(sessionFactory());
  }

}

Disable mutiple datasource for serviceTest


package org.apache.lucene.store;

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

import java.io.IOException;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;

/** File-based {@link Directory} implementation that uses mmap for input.
 *
 * <p>To use this, invoke Java with the System property
 * org.apache.lucene.FSDirectory.class set to
 * org.apache.lucene.store.MMapDirectory.  This will cause {@link
 * FSDirectory#getDirectory(File,boolean)} to return instances of this class.
 *
 * @author Doug Cutting
 */
public class MMapDirectory extends FSDirectory {

  private class MMapIndexInput extends IndexInput {

    private ByteBuffer buffer;
    private RandomAccessFile file;
    private long length;
    private boolean isClone;

    public MMapIndexInput(String path) throws IOException {
      this.file = new RandomAccessFile(path, "r");
      this.length = file.length();
      this.buffer = file.getChannel().map(MapMode.READ_ONLY, 0, length);
    }

    public byte readByte() throws IOException {
      return buffer.get();
    }

    public void readBytes(byte[] b, int offset, int len)
      throws IOException {
      buffer.get(b, offset, len);
    }

    public long getFilePointer() {
      return buffer.position();
    }

    public void seek(long pos) throws IOException {
      buffer.position((int)pos);
    }

    public long length() {
      return length;
    }

    public Object clone() {
      MMapIndexInput clone = (MMapIndexInput)super.clone();
      clone.isClone = true;
      clone.buffer = buffer.duplicate();
      return clone;
    }

    public void close() throws IOException {
      if (!isClone)
        file.close();
    }
  }

  private MMapDirectory() {}                      // no public ctor

  public IndexInput openInput(String name) throws IOException {
    return new MMapIndexInput(new File(getFile(), name).getPath());
  }
}

Add an nio mmap based Directory implementation.

git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@150538 13f79535-47bb-0310-9956-ffa450edef68


package com.sunny.grokkingalgorithms.fasttrack.week2;

import java.util.Arrays;
import java.util.PriorityQueue;

/**
 * Created by sundas on 6/24/2018.
 */
public class MergeSortedStreamsAscending {

  /*
  Two streams of data in array, coming in ascending order.
  Copy them into master array in asc order.
  Merge k sorted arrays | Set 1
Given k sorted arrays of size n each,
merge them and print the sorted output.
Example:
Input:
k = 3, n =  4
arr[][] = { {1, 3, 5, 7},
            {2, 4, 6, 8},
            {0, 9, 10, 11}} ;
Output: 0 1 2 3 4 5 6 7 8 9 10 11
   */

  /**
   *
   * @param stream
   * @return
   */
  public static int[] sort(int[][] stream){
    /*
    1. Create an output array of size n*k.
2. Create a min heap of size k and insert 1st element in all the arrays into the heap
3. Repeat following steps n*k times.
     a) Get minimum element from heap (minimum is always at root) and store it in output array.
     b) Replace heap root with next element from the array from which the element is extracted. If the array doesnt have any more elements, then replace root with infinite.
     After replacing the root, heapify the tree.
     */
    PriorityQueue<Integer> heap = new PriorityQueue<>();
    int[] output = new int[stream.length*stream[0].length];
    for(int i = 0; i < stream.length ; i++){
      for(int j = 0 ; j < stream[i].length ; j++){
        heap.add(stream[i][j]);
      }
    }
    int index = 0;
    while(!heap.isEmpty()){
      output[index] = heap.poll();
      index++;
    }
    return output;
  }

  /**
   *
   * @param args
   */
  public static void main(String[] args) {
    int[][] input  = new int[][]{ {1, 3, 5, 7},
      {2, 4, 6, 8},
      {0, 9, 10, 11}} ;
    System.out.println(Arrays.toString(sort(input)));
  }
}

Sort k sorted lists using min heap . O(nklogk).


/*-
 * Copyright (c) 2014 Mikolaj Izdebski
 *
 * 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.lbzip2.impl;

public class RadixSortBWTTest
    extends AbstractBWTTest
{
    public RadixSortBWTTest()
    {
        super( new RadixSortBWT() );
    }
}

Add unit test for radix sort BWT

Add unit test for radix sort BWT


package de.fau.amos.virtualledger.android.views.contacts.Delete;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

import de.fau.amos.virtualledger.dtos.Contact;

/**
 * Created by Simon on 18.07.2017.
 */

public class ContactsDeleteDialog {

    private Activity activity;
    private Context context;
    private Contact contact;

    public ContactsDeleteDialog(Activity activity, Context context, Contact contact) {
        this.activity = activity;
        this.context = context;
        this.contact = contact;
    }

    public void show() {
        final AlertDialog.Builder alert = new AlertDialog.Builder(context);
        alert.setTitle("DELETE CONFIRMATION");
        alert.setMessage("Are you sure to delete " + this.contact.getFirstName()+" from your contact List?");
        alert.setPositiveButton("yes", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                ContactsDeleteAction deleteAction = new ContactsDeleteAction(activity, contact);
                deleteAction.delete();
            }
        });
        alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

                dialog.dismiss();
            }
        });

        alert.show();

    }

}

Delete dialog for deleting contacts

Delete dialog for deleting contacts


package de.philipphager.disclosure.api.adapters;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.ZoneOffset;
import org.threeten.bp.format.DateTimeParseException;

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

@RunWith(MockitoJUnitRunner.class)
public class OffsetDateTimeTypeAdapterShould {
  @Mock JsonSerializationContext serializationContext;
  @Mock JsonDeserializationContext deserializationContext;
  @InjectMocks OffsetDateTimeTypeAdapter adapter;

  @Test public void serializeDateToJson() {
    OffsetDateTime testDate = OffsetDateTime.of(2016, 1, 1, 12, 0, 30, 0, ZoneOffset.UTC);
    String expectedDate = "2016-01-01T12:00:30Z";

    JsonElement jsonDate = adapter.serialize(testDate, OffsetDateTime.class, serializationContext);
    assertThat(jsonDate.getAsString()).isEqualTo(expectedDate);
  }

  @Test public void deserializeJsonToDate() {
    String testJson = "2016-01-01T01:30:15Z";
    JsonElement json = new JsonPrimitive(testJson);

    OffsetDateTime expectedDate = OffsetDateTime.of(2016, 1, 1, 1, 30, 15, 0, ZoneOffset.UTC);
    OffsetDateTime date = adapter.deserialize(json, OffsetDateTime.class, deserializationContext);

    assertThat(date).isEqualTo(expectedDate);
  }

  @Test(expected = DateTimeParseException.class)
  public void throwErrorIfDateIsNotInIsoFormat() {
    String testJson = "2016-01-0101:30:15";
    JsonElement json = new JsonPrimitive(testJson);

    adapter.deserialize(json, OffsetDateTime.class, deserializationContext);
  }
}

Add tests for OffsetDateTimeTypeAdapter to test JSON conversion


package com.fsck.k9.mail.store.imap;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;

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

@RunWith(RobolectricTestRunner.class)
@Config(manifest = Config.NONE, sdk = 21)
public class ImapPushStateTest {
    @Test
    public void parse_withValidArgument() throws Exception {
        ImapPushState result = ImapPushState.parse("uidNext=42");

        assertNotNull(result);
        assertEquals(42L, result.uidNext);
    }

    @Test
    public void parse_withNullArgument_shouldReturnUidNextOfMinusOne() throws Exception {
        ImapPushState result = ImapPushState.parse(null);

        assertNotNull(result);
        assertEquals(-1L, result.uidNext);
    }

    @Test
    public void parse_withEmptyArgument_shouldReturnUidNextOfMinusOne() throws Exception {
        ImapPushState result = ImapPushState.parse("");

        assertNotNull(result);
        assertEquals(-1L, result.uidNext);
    }

    @Test
    public void parse_withInvalidArgument_shouldReturnUidNextOfMinusOne() throws Exception {
        ImapPushState result = ImapPushState.parse("xyz");

        assertNotNull(result);
        assertEquals(-1L, result.uidNext);
    }

    @Test
    public void parse_withIncompleteArgument_shouldReturnUidNextOfMinusOne() throws Exception {
        ImapPushState result = ImapPushState.parse("uidNext=");

        assertNotNull(result);
        assertEquals(-1L, result.uidNext);
    }

    @Test
    public void parse_withoutIntegerAsUidNext_shouldReturnUidNextOfMinusOne() throws Exception {
        ImapPushState result = ImapPushState.parse("uidNext=xyz");

        assertNotNull(result);
        assertEquals(-1L, result.uidNext);
    }

    @Test
    public void toString_shouldReturnExpectedResult() throws Exception {
        ImapPushState imapPushState = new ImapPushState(23L);

        String result = imapPushState.toString();

        assertEquals("uidNext=23", result);
    }
}

Add unit tests for ImapPushState

Add unit tests for ImapPushState


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

package org.hisp.dhis.android.core.settings.internal;

import org.hisp.dhis.android.core.arch.db.access.DatabaseAdapter;
import org.hisp.dhis.android.core.arch.db.stores.internal.ObjectWithoutUidStore;
import org.hisp.dhis.android.core.arch.di.internal.ObjectWithoutUidStoreProvider;
import org.hisp.dhis.android.core.arch.handlers.internal.Handler;
import org.hisp.dhis.android.core.arch.handlers.internal.ObjectWithoutUidHandlerImpl;
import org.hisp.dhis.android.core.arch.repositories.children.internal.ChildrenAppender;
import org.hisp.dhis.android.core.settings.UserSettings;

import java.util.Collections;
import java.util.Map;

import dagger.Module;
import dagger.Provides;
import dagger.Reusable;

@Module
public final class UserSettingsEntityDIModule implements ObjectWithoutUidStoreProvider<UserSettings> {

    @Override
    @Provides
    @Reusable
    public ObjectWithoutUidStore<UserSettings> store(DatabaseAdapter databaseAdapter) {
        return UserSettingsStore.create(databaseAdapter);
    }

    @Provides
    @Reusable
    Handler<UserSettings> handler(ObjectWithoutUidStore<UserSettings> store) {
        return new ObjectWithoutUidHandlerImpl<>(store);
    }

    @Provides
    @Reusable
    Map<String, ChildrenAppender<UserSettings>> childrenAppenders() {
        return Collections.emptyMap();
    }
}

Add user settings DI module

[androsdk-1087] Add user settings DI module


package org.apache.beam.sdk.extensions.sql.zetasql;

// Dummy class for testing spotbugs results in Jenkins.
// TODO(BEAM-11714) Delete class before merge

public class Dummy implements Cloneable {

}

Add dummy class for testing

[BEAM-11714] Add dummy class for testing


package de.biomedical_imaging.traj.features.test;

import static org.junit.Assert.*;

import org.junit.Test;

import de.biomedical_imaging.traJ.Trajectory;
import de.biomedical_imaging.traJ.features.MeanSpeedFeature;

public class MeanSpeedFeatureTest {

	@Test
	public void MeanSpeedTest() {
		Trajectory t  = new Trajectory(2);

		t.add(0, 0, 0);

		for(int i = 1; i < 20; i++){
			t.add(0,i,0);
		}
		double timelag = 1.0/30;
		MeanSpeedFeature speed = new MeanSpeedFeature(t, timelag);

		double meanspeed = speed.evaluate()[0];

		assertEquals(30, meanspeed,0.01);
	}

}

Add unit test for MeanSpeedFeature

Add unit test for MeanSpeedFeature


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

import com.vladmihalcea.book.hpjp.util.AbstractTest;
import org.junit.Test;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

import static org.junit.Assert.assertEquals;

/**
 * SortIndexCollectionInheritance -
 *
 * @author Vlad Mihalcea
 */
public class TwoMapsIdsTest extends AbstractTest {

    @Override
    protected Class<?>[] entities() {
        return new Class<?>[] {
            Address.class,
            Location.class,
            Person.class,
        };
    }

    @Test
    public void testScopeIdentity() {
        doInJPA(entityManager -> {
            Address address = new Address();
            address.id = 1L;

            Location location = new Location();
            location.id = 1L;

            Person person = new Person();
            person.personId = 1L;
            person.address = address;
            person.location = location;

            entityManager.persist(address);
            entityManager.persist(location);
            entityManager.persist(person);
        });

        doInJPA(entityManager -> {
            Person person = entityManager.find(Person.class, 1L);
            assertEquals(Long.valueOf(1L), person.address.id);
            assertEquals(Long.valueOf(1L), person.location.id);
        });
    }

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

        @Id
        private Long id;
    }

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

        @Id
        private Long id;
    }

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

        @Id
        private Long personId;

        @OneToOne
        @MapsId
        @JoinColumn(name = "personId")
        private Address address;

        @OneToOne
        @MapsId
        @JoinColumn(name = "personId")
        private Location location;
    }
}

Add test for multiple mapsid

Add test for multiple mapsid


package org.verapdf.model.impl.pb.operator.base;

import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.cos.COSObjectKey;
import org.apache.pdfbox.cos.COSStream;
import org.apache.pdfbox.pdfparser.PDFStreamParser;
import org.apache.pdfbox.pdmodel.PDResources;
import org.junit.Assert;
import org.verapdf.model.baselayer.Object;
import org.verapdf.model.coslayer.CosDict;
import org.verapdf.model.factory.operator.OperatorFactory;
import org.verapdf.model.impl.BaseTest;
import org.verapdf.model.operator.Operator;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;

/**
 * @author Evgeniy Muravitskiy
 */
public abstract class PBOperatorTest extends BaseTest {

	public static final String FILE_RELATIVE_PATH = "operator/Operators.pdf";

	private static final COSObjectKey KEY = new COSObjectKey(15, 0);

	protected static void setUpOperatorsList(String type, String id) throws IOException, URISyntaxException {
		expectedType = TYPES.contains(type) ? type : null;
		expectedID = id;
		setUp(FILE_RELATIVE_PATH);

		COSObject objectFromPool = document.getDocument().getObjectFromPool(KEY);
		COSStream stream = (COSStream) objectFromPool.getObject();
		PDResources resources = document.getPage(0).getResources();

		PDFStreamParser parser = new PDFStreamParser(stream, true);
		parser.parse();

		List<Operator> operators = OperatorFactory.operatorsFromTokens(parser.getTokens(), resources);
		actual = getActual(operators, expectedType);

		operators.clear();
	}

	private static Object getActual(List<Operator> operators, String type) {
		for (Operator operator : operators) {
			if (type.equals(operator.getType())) {
				return operator;
			}
		}

		return null;
	}

	protected void testLinksToReals(String link, int count, String type) {
		List<? extends Object> linkedObjects = actual.getLinkedObjects(link);

		Assert.assertEquals(count, linkedObjects.size());

		for (Object object : linkedObjects) {
			Assert.assertEquals(type, object.getType());
		}

	}

	protected static void testLinkToDictionary(String link, String type, Number expectedResult) {
		Object object = getObject(link, 1, type);
		Assert.assertEquals(expectedResult, ((CosDict) object).getsize());
	}

	protected static Object getObject(String link, int count, String type) {
		List<? extends Object> linkedObjects = actual.getLinkedObjects(link);

		Assert.assertEquals(count, linkedObjects.size());

		Object object = linkedObjects.get(0);

		Assert.assertEquals(type, object.getType());
		return object;
	}

}

Add base unit test for operators

Add base unit test for operators


package org.gluu.oxtrust.ws.rs.controller;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

/**
 * Health check controller
 *
 * @author Yuriy Movchan
 * @version Jul 24, 2020
 */
@ApplicationScoped
@Path("/")
public class HealthCheckController {

	@GET
	@POST
	@Path("/health-check")
	@Produces(MediaType.APPLICATION_JSON)
	public String healthCheckController() {
		return "{\"status\":\"running\"}";
	}

}

Add health-check controller to oxtrust-server


/**
 * Copyright 2017 Palantir Technologies
 *
 * Licensed under the BSD-3 License (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://opensource.org/licenses/BSD-3-Clause
 *
 * 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.palantir.atlasdb.timelock.paxos;

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

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

import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;

import com.google.common.collect.Lists;
import com.palantir.paxos.PaxosLearner;
import com.palantir.paxos.PaxosLearnerImpl;
import com.palantir.paxos.PaxosValue;

public class PaxosSynchronizerTest {
    @ClassRule
    public static final TemporaryFolder TEMPORARY_FOLDER = new TemporaryFolder();

    private static final int NUM_NODES = 5;
    private static final String LEADER_ID = "foo";
    private static final byte[] PAXOS_DATA = new byte[0];
    private static final long SEQUENCE_ONE = 1L;
    private static final PaxosValue VALUE_ONE = new PaxosValue(LEADER_ID, SEQUENCE_ONE, PAXOS_DATA);
    private static final long SEQUENCE_TWO = 2L;
    private static final PaxosValue VALUE_TWO = new PaxosValue(LEADER_ID, SEQUENCE_TWO, PAXOS_DATA);

    private final List<PaxosLearner> learners = Lists.newArrayList();

    private PaxosLearner ourLearner;

    @Before
    public void setUp() throws IOException {
        for (int i = 0; i < NUM_NODES; i++) {
            learners.add(PaxosLearnerImpl.newLearner(TEMPORARY_FOLDER.newFolder().getPath()));
        }
        ourLearner = learners.get(0);
    }

    @Test
    public void synchronizeDoesNotThrowIfThereIsNoState() {
        PaxosSynchronizer.synchronizeLearner(ourLearner, learners);
    }

    @Test
    public void synchronizeUpdatesOurLearnerToValuesOthersHaveLearned() {
        learners.get(1).learn(SEQUENCE_ONE, VALUE_ONE);
        PaxosSynchronizer.synchronizeLearner(ourLearner, learners);
        assertThat(ourLearner.getGreatestLearnedValue()).isEqualTo(VALUE_ONE);
    }

    @Test
    public void synchronizeDoesNotUpdateUsIfWeHaveTheMostRecentData() {
        learners.get(1).learn(SEQUENCE_ONE, VALUE_ONE);
        ourLearner.learn(SEQUENCE_TWO, VALUE_TWO);
        PaxosSynchronizer.synchronizeLearner(ourLearner, learners);
        assertThat(ourLearner.getGreatestLearnedValue()).isEqualTo(VALUE_TWO);
    }
}

Add some basic tests for synchronizer

Add some basic tests for synchronizer


package utils;

/**
 * Created by emma on 13/04/2016.
 *
 * @author emma
 *         <p>
 *         Simple utility class to tidy up user entered strings before saving to database
 */
public class StringProcessingService {

    public static String tidy_curator_entered_string(String string) {
        String newString = string.trim();
        String newline = System.getProperty("line.separator");

        if (newString.contains(newline)) {
            newString = newString.replace(newline, "");
        }
        return newString;
    }
}

Move string tidy method to simple utility class


package leetcode;

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

/**
 * https://leetcode.com/problems/count-of-smaller-numbers-after-self/
 */
public class Problem315 {
    public List<Integer> countSmaller(int[] nums) {
        List<Integer> result = new ArrayList<>();
        // TODO:
        return result;
    }

    public static void main(String[] args) {
        Problem315 prob = new Problem315();
        System.out.println(prob.countSmaller(new int[]{5, 2, 6, 1})); // [2, 1, 1, 0]
    }
}

Create skeleton for problem 315

Create skeleton for problem 315


package org.fidonet.tests.toss;

/**
 * Created by IntelliJ IDEA.
 * User: sly
 * Date: 9/2/11
 * Time: 5:42 PM
 * To change this template use File | Settings | File Templates.
 */
public class TestTosser {
}

Add fake test for tosser

Add fake test for tosser


package org.eclipse.viatra.cep.mqtt.commons.utils;

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

import org.apache.log4j.Logger;
import org.eclipse.viatra.cep.mqtt.commons.mqtt.Publisher;
import org.eclipse.viatra.cep.mqtt.commons.utils.LoggerUtil;

import com.eclipsesource.json.JsonObject;

public class DashboardUtil {

	private final static SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
	private static final Logger log4jLogger = Logger.getLogger(DashboardUtil.class);
	private static final LoggerUtil LOGGER = new LoggerUtil(log4jLogger);

	public static String brokerAddress = "";

	private static Publisher publisher = new Publisher(brokerAddress, "IOT_CEP_DASHBOARD");;

	public static void publishSimpleEvent(String eventMessage) {
		publish(eventMessage, "SIMPLE");
	}

	public static void publishHighlightedEvent(String eventMessage) {
		publish(eventMessage, "HIGHLIGHTED");
	}

	private static void publish(String eventMessage, String marker) {
		try {
			if (!publisher.isConnected()) {
				publisher.connect();
			}
			JsonObject eventMsg = new JsonObject();
			JsonObject event = new JsonObject();
			event.add("event_msg", eventMessage);
			event.add("event_type", marker);
			event.add("timestamp", sdf.format(new Date()));
			eventMsg.add("CEP_EVENT_MESSAGE", event);
			publisher.publish("dashboard/cep", eventMsg.toString().getBytes());

		} catch (Exception ex) {
			LOGGER.error("Unable publish message to dashboard: " + ex.getMessage());
		}
	}

}

Add dashboard util to commons project

Add dashboard util to commons project


package org.jetbrains.idea.maven.dom.intentions;

import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider;
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar;
import com.intellij.psi.PsiJavaCodeReferenceElement;

public class ResolveReferenceQuickFixProvider implements UnresolvedReferenceQuickFixProvider{
  public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) {
    registrar.register(new DependencyQuickFix(ref));
  }
}

package org.jetbrains.idea.maven.dom.intentions;

import com.intellij.codeInsight.quickfix.UnresolvedReferenceQuickFixProvider;
import com.intellij.codeInsight.daemon.QuickFixActionRegistrar;
import com.intellij.psi.PsiJavaCodeReferenceElement;

public class ResolveReferenceQuickFixProvider implements UnresolvedReferenceQuickFixProvider{
  public void registerFixes(PsiJavaCodeReferenceElement ref, QuickFixActionRegistrar registrar) {
    registrar.register(new AddMavenDependencyQuickFix(ref));
  }
}

Maven: Add Dependency QuickFix improvement
Maven: Runner optimization
Maven: better process cancelling handling


/*
 * Copyright 2014-2015 Red Hat, Inc. and/or its affiliates
 * and other 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.hawkular.metrics.core.impl.request;

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

import org.hawkular.metrics.core.api.Availability;
import org.hawkular.metrics.core.api.Guage;

import com.google.common.base.Objects;
import com.wordnik.swagger.annotations.ApiModel;

/**
 * @author Stefan Negrea
 */
@ApiModel
public class MixedMetricsRequest {

    private List<Guage> guageMetrics = new ArrayList<>();
    private List<Availability> availabilityMetrics = new ArrayList<>();

    public List<Guage> getGuageMetrics() {
        return guageMetrics;
    }

    public void setGuageMetric(List<Guage> guageMetrics) {
        this.guageMetrics = guageMetrics;
    }

    public List<Availability> getAvailabilityMetrics() {
        return availabilityMetrics;
    }

    public void setAvailabilityMetrics(List<Availability> availabilityMetrics) {
        this.availabilityMetrics = availabilityMetrics;
    }

    @Override
    public String toString() {
        return Objects.toStringHelper(this)
            .add("guageMetrics", guageMetrics)
            .add("availibilityMetrics", availabilityMetrics)
            .toString();
    }
}

Add mixed metric request to be used for inserting multiple types of metrics.


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

import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.impl.Log4jLogEvent;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 *
 */
public class ThreadNamePatternConverterTest {

    @Test
    public void testConverterAppendsLogEventNanoTimeToStringBuilder() {
        final LogEvent event = Log4jLogEvent.newBuilder() //
                .setThreadName("Hello-1").build();
        final StringBuilder sb = new StringBuilder();
        final ThreadPatternConverter converter = ThreadPatternConverter.newInstance(null);
        converter.format(event, sb);
        assertEquals("Hello-1", sb.toString());
    }
}

[LOG4J2-1299] Add pattern converter for thread id in PatternLayout. Add
missing unit test on existing thread name converter.


package org.openforis.collect.earth.sampler.utils;

import java.io.File;

import org.geotools.referencing.GeodeticCalculator;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.openforis.collect.earth.core.utils.CsvReaderUtils;

import au.com.bytecode.opencsv.CSVReader;

public class CheckDistances {

	public static void main(String[] args) {

		File csvFile = new File( "C:\\Users\\SanchezPausDiaz\\Downloads\\ecuador.csv");
		if( csvFile.exists() ){
			try {

				CSVReader reader = CsvReaderUtils.getCsvReader(csvFile.getAbsolutePath());
				String[] csvRow = reader.readNext();

				while ( csvRow != null ) {
					try {
						double[] coordinates0 = {new Double(csvRow[1]),	new Double(csvRow[2])};
						if( (csvRow = reader.readNext()) !=null){
							double[] coordinates1 = {new Double(csvRow[1]),	new Double(csvRow[2])};

							final GeodeticCalculator calc = new GeodeticCalculator(DefaultGeographicCRS.WGS84);

							calc.setStartingGeographicPoint( coordinates0[1], coordinates0[0]);
							calc.setDestinationGeographicPoint( coordinates1[1], coordinates1[0]);
							System.out.print( ( coordinates0[0] - coordinates1[0] ) + " " +  ( coordinates0[1] - coordinates1[1] ) + "  :  " );
							System.out.println( calc.getOrthodromicDistance() );
						}else{
							System.out.println( "Last row!!!" );
							break;
						}
					}catch(Exception e){
						csvRow = reader.readNext();
						e.printStackTrace();

					}
				}

			}catch(Exception e){
				e.printStackTrace();
			}
		}else{
			System.out.println("CSV file not found " + csvFile.getAbsolutePath());
		}
	}

}

Add class to check distance between plots


package com.aspose.words.examples.programming_documents.comments;

import com.aspose.words.*;
import com.aspose.words.examples.Utils;

@SuppressWarnings("unchecked")
public class RemoveCommentRegionText {
    public static void main(String[] args) throws Exception {

        // The path to the documents directory.
        String dataDir = Utils.getDataDir(RemoveCommentRegionText.class);

        // Open the document.
        Document doc = new Document(dataDir + "TestFile.doc");
		CommentRangeStart commentStart = (CommentRangeStart)doc.getChild(NodeType.COMMENT_RANGE_START, 0, true);
		CommentRangeEnd commentEnd = (CommentRangeEnd)doc.getChild(NodeType.COMMENT_RANGE_END, 0, true);

		Node currentNode = commentStart;
		Boolean isRemoving = true;
		while (currentNode != null && isRemoving)
		{
			if (currentNode.getNodeType() == NodeType.COMMENT_RANGE_END)
				isRemoving = false;

			Node nextNode = currentNode.nextPreOrder(doc);
			currentNode.remove();
			currentNode = nextNode;
		}

        doc.save(dataDir + "output.doc");

    }
}

Remove text between CommentRangeStart and CommentRangeEnd