/*
 * Copyright 2013 The Netty Project
 *
 * The Netty Project 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.jboss.netty.handler.codec.http.multipart;

import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.handler.codec.http.*;
import org.jboss.netty.util.CharsetUtil;
import org.junit.Test;

import java.util.Arrays;

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

/** {@link HttpPostRequestDecoder} test case. */
public class HttpPostRequestDecoderTest {
    @Test
    public void testBinaryStreamUpload() throws Exception {
        final String boundary = "dLV9Wyq26L_-JQxk6ferf-RT153LhOO";

        final DefaultHttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "http://localhost");

        req.setContent(ChannelBuffers.EMPTY_BUFFER);
        req.setHeader(HttpHeaders.Names.CONTENT_TYPE, "multipart/form-data; boundary=" + boundary);
        req.setHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED);
        req.setChunked(true);

        // Force to use memory-based data.
        final DefaultHttpDataFactory inMemoryFactory = new DefaultHttpDataFactory(false);

        for (String data : Arrays.asList("", "\r", "\r\r", "\r\r\r")) {
            final String body = ""
                + "--" + boundary + "\r\n" +
                "Content-Disposition: form-data; name=\"file\"; filename=\"tmp-0.txt\"\r\n" +
                "Content-Type: image/gif\r\n" +
                "\r\n" +
                data + "\r\n" +
                "--" + boundary + "--\r\n";

            // Create decoder instance to test.
            final HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(inMemoryFactory, req);

            decoder.offer(new DefaultHttpChunk(ChannelBuffers.copiedBuffer(body, CharsetUtil.UTF_8)));
            decoder.offer(new DefaultHttpChunk(ChannelBuffers.EMPTY_BUFFER));

            // Validate it's enough chunks to decode upload.
            assertTrue(decoder.hasNext());

            // Decode binary upload.
            MemoryFileUpload upload = (MemoryFileUpload) decoder.next();

            // Validate data has been parsed correctly as it was passed into request.
            assertArrayEquals("Invalid decoded data [data=" + data + "upload=" + upload + ']',
                data.getBytes(), upload.get());
        }
    }
}

Add test for HttpPostRequestDecoder: validate '\r' symbols in the end of binary stream are parsed correctly.


package org.matthewjwhite.stata.error;

import com.stata.sfi.SFIToolkit;

public class StataError {
	public static void display(String message, Throwable throwable) {
		if (message != null & !message.equals(""))
			SFIToolkit.errorln(message);
		SFIToolkit.errorln("Java error message:\n" + throwable.getMessage());
	}

	public static void display(Throwable throwable) {
		display(null, throwable);
	}
}

Add class for managing Stata errors

Add class for managing Stata errors


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

/**
 * This is just used so that we can force the genration of xxx-soruces.jar and xxx-javadoc.jar.
 */
public interface Uberjar {
}

Add a dummy interface inside the uberjar in order to force generation of sources and javadoc jars.


package editor.gui.ccp;

import static java.awt.event.ActionEvent.ACTION_PERFORMED;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.function.Supplier;

import javax.swing.JMenuItem;
import javax.swing.KeyStroke;
import javax.swing.TransferHandler;

/**
 * This is a convenience class for creating a set of cut, copy, and paste menu items
 * with commonly-used keyboard accelerators (Ctrl+X, Ctrl+C, Ctrl+V, respectively)
 * optionally already installed. The menu text and keyboard accelerators are not
 * customizable.
 *
 * @author Alec Roelke
 */
public class CCPItems
{
    /** Cut menu item. */
    public final JMenuItem cut;
    /** Copy menu item. */
    public final JMenuItem copy;
    /** Paste menu item. */
    public final JMenuItem paste;

    /**
     * Create a new set of cut, copy, and paste menu items that allow the reference to the source
     * component performing the action to change what it points to over time.
     *
     * @param source function for getting the component performing the actions
     * @param accelerate add keyboard accelerators
     */
    public CCPItems(Supplier<? extends Component> source, boolean accelerate)
    {
        cut = new JMenuItem("Cut");
        copy = new JMenuItem("Copy");
        paste = new JMenuItem("Paste");

        cut.addActionListener((e) -> TransferHandler.getCutAction().actionPerformed(new ActionEvent(source.get(), ACTION_PERFORMED, null)));
        copy.addActionListener((e) -> TransferHandler.getCopyAction().actionPerformed(new ActionEvent(source.get(), ACTION_PERFORMED, null)));
        paste.addActionListener((e) -> TransferHandler.getPasteAction().actionPerformed(new ActionEvent(source.get(), ACTION_PERFORMED, null)));

        if (accelerate)
        {
            cut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, KeyEvent.CTRL_DOWN_MASK));
            copy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK));
            paste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, KeyEvent.CTRL_DOWN_MASK));
        }
    }

    /**
     * Create a new set of cut, copy, and paste menu items with a static source reference
     * (i.e. if the reference passed here changes later, these items won't see the change).
     *
     * @param source component performing the actions
     * @param accelerate add keyboard accelerators
     */
    public CCPItems(Component source, boolean accelerate)
    {
        this(() -> source, accelerate);
    }
}

Add convenience class for CCP menu items


/**
 * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies
 *
 * Please see distribution for license.
 */
package com.opengamma.integration.viewer.status;

import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNotNull;

import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.PosixParser;
import org.testng.annotations.Test;

import com.opengamma.OpenGammaRuntimeException;
import com.opengamma.livedata.UserPrincipal;
import com.opengamma.util.test.TestGroup;

/**
 * Tests {@link ViewStatusOption}
 */
@Test(groups = TestGroup.UNIT)
public class ViewStatusOptionTest {

  private static final Options s_options = ViewStatusOption.createOptions();
  private static final CommandLineParser s_parser = new PosixParser();

  public void defaultUser() throws Exception {
    String[] args = {"-n", "PORTFOLIO_NAME"};

    ViewStatusOption statusOption = ViewStatusOption.getViewStatusReporterOption(s_parser.parse(s_options, args));
    assertNotNull(statusOption);
    assertNotNull(statusOption.getUser());
    assertEquals(UserPrincipal.getLocalUser(), statusOption.getUser());
  }

  public void userOption() throws Exception {
    String[] args = {"-n", "PORTFOLIO_NAME", "-u", "test/127.0.0.1"};
    ViewStatusOption statusOption = ViewStatusOption.getViewStatusReporterOption(s_parser.parse(s_options, args));
    assertNotNull(statusOption);
    assertNotNull(statusOption.getUser());
    assertEquals("test", statusOption.getUser().getUserName());
    assertEquals("127.0.0.1", statusOption.getUser().getIpAddress());
  }

  @Test(expectedExceptions = OpenGammaRuntimeException.class)
  public void invalidUserOption() throws Exception {
    String[] args = {"-n", "PORTFOLIO_NAME", "-u", "test~127.0.0.1"};
    ViewStatusOption.getViewStatusReporterOption(s_parser.parse(s_options, args));
  }
}

Add unit testcase for ViewStatusOption

[PLAT-3494] Add unit testcase for ViewStatusOption


/*
 * Copyright 2012 Shared Learning Collaborative, LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * 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.slc.sli.api.security.context.resolver;

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

import org.slc.sli.api.constants.EntityNames;
import org.slc.sli.api.security.context.AssociativeContextHelper;
import org.slc.sli.api.security.context.traversal.cache.impl.SessionSecurityCache;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.domain.Repository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * Resolves Teachers context to Students. Finds accessible students through section, program, and cohort associations.
 */
@Component
public class TeacherToStudentCompetencyResolver implements EntityContextResolver {

    @Autowired
    private AssociativeContextHelper helper;
    @Autowired
    private SessionSecurityCache securityCachingStrategy;

    @Autowired
    private TeacherStudentResolver studentResolver;

    @Autowired
    @Qualifier("validationRepo")
    private Repository<Entity> repo;

    @Override
    public boolean canResolve(String fromEntityType, String toEntityType) {
//        return false;
        return EntityNames.TEACHER.equals(fromEntityType) && EntityNames.STUDENT_COMPETENCY.equals(toEntityType);
    }

    @Override
    public List<String> findAccessible(Entity principal) {
        List<String> studentIds = new ArrayList<String>();
        if (!securityCachingStrategy.contains(EntityNames.STUDENT)) {
            studentIds = studentResolver.findAccessible(principal);
        } else {
            studentIds = new ArrayList<String>(securityCachingStrategy.retrieve(EntityNames.STUDENT));
        }
        Iterable<String> assocIds = repo.findAllIds(EntityNames.STUDENT_SECTION_ASSOCIATION, new NeutralQuery(new NeutralCriteria(
                "studentId", NeutralCriteria.CRITERIA_IN, studentIds)));
        List<String> ids = new ArrayList<String>();
        for (String id : assocIds) {
            ids.add(id);
        }
        List<String> finalIds = helper.findEntitiesContainingReference(EntityNames.STUDENT_COMPETENCY, "studentSectionAssociationId", ids);
        securityCachingStrategy.warm(EntityNames.STUDENT_COMPETENCY, new HashSet<String>(finalIds));
        return finalIds;
    }
}

Add an ugly competency resolver

Add an ugly competency resolver


package org.jenkinsci.plugins.relution_publisher.unittest.mocks;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.jenkinsci.plugins.relution_publisher.net.responses.ApiResponse;
import org.jenkinsci.plugins.relution_publisher.unittest.io.ResourceReader;

import java.io.IOException;

public class ResponseBuilder {

    public ApiResponse create(final String resourceName, final int httpStatus, final String reason) throws IOException {
        final StatusLine statusLine = new MockStatusLine(httpStatus, reason);

        final HttpResponse httpResponse = new MockHttpResponse();
        httpResponse.setStatusLine(statusLine);

        final ResourceReader reader = new ResourceReader();
        final String json = reader.readString(resourceName);

        final ApiResponse response = ApiResponse.fromJson(json);
        response.setHttpResponse(httpResponse);
        return response;
    }
}

Add response builder for unit tests

Add response builder for unit tests


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

package com.google.sps.data;
import com.google.auto.value.AutoValue;

/**
 * Class representing each user object
 */
@AutoValue
public abstract class RecentBuy {
    public static RecentBuy create(String name, String email, int amtInvested, String searchQuery, long dateInvested) {
        return new AutoValue_RecentBuy(name, email, amtInvested, searchQuery, dateInvested);
    }
    public abstract String name();
    public abstract String email();
    public abstract int amtInvested();
    public abstract String searchQuery();
    public abstract long dateInvested();
}

Add object for recent buy data

Add object for recent buy data


/* This file is part of SableCC ( http://sablecc.org ).
 *
 * See the NOTICE file distributed with this work for copyright information.
 *
 * 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.sablecc.sablecc.util;

import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;

import org.sablecc.sablecc.exception.InternalException;

public class WorkSet<T> {

    private final Set<T> done = new HashSet<T>();

    private final LinkedHashSet<T> toDo = new LinkedHashSet<T>();

    public boolean hasNext() {

        return !this.toDo.isEmpty();
    }

    public T next() {

        T next = this.toDo.iterator().next();

        this.toDo.remove(next);
        this.done.add(next);

        return next;
    }

    public void add(
            T element) {

        if (element == null) {
            throw new InternalException("element may not be null");
        }

        if (!this.done.contains(element)) {
            this.toDo.add(element);
        }
    }
}

Add class to manage work sets.

Add class to manage work sets.

Signed-off-by: Etienne M. Gagnon <bf06ec0eb40152cd863534753d026b021022c851@j-meg.com>


package org.opennms.core.test;

import java.util.Arrays;
import java.util.List;

import org.junit.Assert;

public abstract class OnmsAssert {

    public static void assertArrayEqualsIgnoreOrder(final Object[] a, final Object[] b) {
        final List<?> aList = Arrays.asList(a);
        final List<?> bList = Arrays.asList(b);
        Assert.assertTrue(aList.containsAll(bList) && bList.containsAll(aList));
    }

}

Add a utility method for asserting array equality regardless of order


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

/**
 * Contains all classes and exceptions for the key storage framework.
 *
 * @see com.google.k2crypto.storage.K2Storage
 *
 * @author darylseah@gmail.com (Daryl Seah)
 */
package com.google.k2crypto.storage;

Add javadoc for storage package.

Add javadoc for storage package.


package org.ojalgo.matrix;

import static org.ojalgo.function.aggregator.Aggregator.*;

import org.junit.jupiter.api.Test;
import org.ojalgo.TestUtils;
import org.ojalgo.matrix.BasicMatrix.Builder;

public class ReductionTest {

    public ReductionTest() {
        super();
    }

    /**
     * https://stackoverflow.com/questions/49682219/how-to-get-average-of-elements-along-columns-or-rows-in-an-ojalgo-matrix
     * <br>
     * https://github.com/optimatika/ojAlgo/issues/91#issuecomment-379399975
     */
    @Test
    public void testReduction() {

        Builder<PrimitiveMatrix> builder = PrimitiveMatrix.FACTORY.getBuilder(2, 3);
        builder.set(0, 0, 1.0);
        builder.set(0, 1, 2.0);
        builder.set(0, 2, 3.0);
        builder.set(1, 0, 4.0);
        builder.set(1, 1, 5.0);
        builder.set(1, 2, 6.0);
        PrimitiveMatrix matrix = builder.get();

        PrimitiveMatrix reducedRows = matrix.reduceRows(AVERAGE);
        PrimitiveMatrix reducedColumns = matrix.reduceColumns(AVERAGE);

        TestUtils.assertEquals(2, reducedRows.count());
        TestUtils.assertEquals(2, reducedRows.countRows());
        TestUtils.assertEquals(1, reducedRows.countColumns());

        TestUtils.assertEquals(2.0, reducedRows.doubleValue(0, 0));
        TestUtils.assertEquals(5.0, reducedRows.doubleValue(1, 0));

        TestUtils.assertEquals(2.0, reducedRows.doubleValue(0));
        TestUtils.assertEquals(5.0, reducedRows.doubleValue(1));

        TestUtils.assertEquals(3, reducedColumns.count());
        TestUtils.assertEquals(1, reducedColumns.countRows());
        TestUtils.assertEquals(3, reducedColumns.countColumns());

        TestUtils.assertEquals(2.5, reducedColumns.doubleValue(0, 0));
        TestUtils.assertEquals(3.5, reducedColumns.doubleValue(0, 1));
        TestUtils.assertEquals(4.5, reducedColumns.doubleValue(0, 2));

        TestUtils.assertEquals(2.5, reducedColumns.doubleValue(0));
        TestUtils.assertEquals(3.5, reducedColumns.doubleValue(1));
        TestUtils.assertEquals(4.5, reducedColumns.doubleValue(2));
    }

}

Add test case for the original example

Add test case for the original example


package com.haxademic.demo.draw.image;

import com.haxademic.core.app.P;
import com.haxademic.core.app.PAppletHax;
import com.haxademic.core.draw.image.ImageUtil;
import com.haxademic.core.file.DemoAssets;

import processing.core.PGraphics;
import processing.core.PImage;

public class Demo_BlurByTextureTransfer
extends PAppletHax {
	public static void main(String args[]) { PAppletHax.main(Thread.currentThread().getStackTrace()[1].getClassName()); }

	protected PImage sourceImg;
	protected PGraphics copySmallBuffer;
	protected PGraphics copyBackBuffer;

	public void setupFirstFrame() {
		// prep buffers
		sourceImg = DemoAssets.smallTexture();
		float scaleDown = 0.2f;
		copySmallBuffer = p.createGraphics(P.round(sourceImg.width * scaleDown), P.round(sourceImg.height * scaleDown), P.P3D);
		copyBackBuffer = p.createGraphics(sourceImg.width, sourceImg.height, P.P3D);

		// copy image down and back up for blur
		ImageUtil.copyImage(sourceImg, copySmallBuffer);
		ImageUtil.copyImage(copySmallBuffer, copyBackBuffer);

	}

	public void drawApp() {
		// set up context
		p.background(100);
		p.noStroke();

		// draw steps/results to screen
		p.image(sourceImg, 0, 0);
		p.image(copySmallBuffer, sourceImg.width, 0);
		p.image(copyBackBuffer, sourceImg.width + copySmallBuffer.width, 0);
	}
}

Test blur effect by texture resampling

Test blur effect by texture resampling


/**
 * Copyright (C) 2015 Deutsches Forschungszentrum für Künstliche Intelligenz (http://freme-project.eu)
 *
 * 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 eu.freme.eservices.pipelines;

import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.Unirest;
import com.mashape.unirest.http.exceptions.UnirestException;
import eu.freme.conversion.rdf.RDFConstants;
import org.apache.http.HttpStatus;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
 * @author Gerald Haesendonck
 */
public class TestWrongRequests extends LocalServerTestBase {

	/**
	 * Send a pipelines request without body. This is not acceptable!
	 * @throws UnirestException
	 */
	@Test
	public void testNoBody() throws UnirestException {
		HttpResponse<String> response = Unirest.post("http://localhost:9000/pipelining/chain")
				.header("content-type", RDFConstants.RDFSerialization.JSON.contentType())
				.asString();
		assertEquals(HttpStatus.SC_NOT_ACCEPTABLE, response.getStatus());
	}

}

Test send request without body.

Test send request without body.


package moe.tristan.easyfxml.model.fxml;

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

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

public class FxmlLoaderTest {

    private int succ = 0;
    private int fail = 0;
    private FxmlLoader fxmlLoader;

    @Before
    public void setUp() {
        fxmlLoader = new FxmlLoader();
        fxmlLoader.setOnSuccess(n -> succ++);
        fxmlLoader.setOnFailure(e -> fail++);
    }

    @Test
    public void onSuccess() {
        fxmlLoader.onSuccess(null);
        assertThat(succ).isEqualTo(1);
        assertThat(fail).isEqualTo(0);
    }

    @Test
    public void onFailure() {
        fxmlLoader.onFailure(null);
        assertThat(succ).isEqualTo(0);
        assertThat(fail).isEqualTo(1);
    }
}

Add some very light contract-testing to FxmlLoader


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

import junit.framework.TestCase;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.net.URI;

public class CachedContentFetcherTest extends TestCase {
  private RemoteContentFetcher fetcher
      = new CachedContentFetcher(new BasicRemoteContentFetcher(Integer.MAX_VALUE));

  public void testFetch() throws Exception {
    String content = "Hello, world!";
    File temp = File.createTempFile(this.getName(), ".txt");
    temp.deleteOnExit();
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(content);
    out.close();
    RemoteContentRequest request = new RemoteContentRequest(temp.toURI());
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
    temp.delete();
    response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
  }

  public void testDontCache() throws Exception {
    String content = "Hello, world!";
    File temp = File.createTempFile(this.getName(), ".txt");
    temp.deleteOnExit();
    BufferedWriter out = new BufferedWriter(new FileWriter(temp));
    out.write(content);
    out.close();
    RemoteContentRequest request = RemoteContentRequest.getRequest(temp.toURI(), true);
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_OK, response.getHttpStatusCode());
    assertEquals(content, response.getResponseAsString());
    temp.delete();
    response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_NOT_FOUND, response.getHttpStatusCode());
  }

  public void testNotExists() throws Exception {
    RemoteContentRequest request
        = new RemoteContentRequest(new URI("file:///does/not/exist"));
    RemoteContent response = fetcher.fetch(request);
    assertEquals(RemoteContent.SC_NOT_FOUND, response.getHttpStatusCode());
  }

  // TODO test caching of POST requests, headers, options, etc.
}

Test that nocache is honored by CachedContentFetcher

git-svn-id: 3f2e04d30bd9db331bbfc569b45e7de8c0d84ef0@646542 13f79535-47bb-0310-9956-ffa450edef68


/*
 * Copyright (c) 2011-2019, Meituan Dianping. All Rights Reserved.
 *
 * 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 com.site.lookup.util;

import java.util.ArrayList;
import java.util.Arrays;

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

public class StringUtilsTest {

    @Test
    public void testIsEmpty() {
        Assert.assertTrue(StringUtils.isEmpty(""));
        Assert.assertTrue(StringUtils.isEmpty(null));
        Assert.assertFalse(StringUtils.isEmpty("foo"));
    }

    @Test
    public void testIsNotEmpty() {
        Assert.assertFalse(StringUtils.isNotEmpty(""));
        Assert.assertFalse(StringUtils.isNotEmpty(null));
        Assert.assertTrue(StringUtils.isNotEmpty("foo"));
    }

    @Test
    public void testJoinArray() {
        Assert.assertEquals("", StringUtils
                .join(new String[0], ","));
        Assert.assertEquals("foo", StringUtils
                .join(new String[]{"foo"}, ","));
        Assert.assertEquals("foo,bar,baz", StringUtils
                .join(new String[]{"foo", "bar", "baz"}, ","));
    }

    @Test
    public void testJoinCollection() {
        Assert.assertEquals("", StringUtils
                .join(new ArrayList<String>(), ","));
        Assert.assertEquals("foo", StringUtils
                .join(new ArrayList<>(Arrays.asList("foo")), ","));
        Assert.assertEquals("foo,bar,baz", StringUtils
                .join(new ArrayList<>(
                        Arrays.asList("foo", "bar", "baz")), ","));
    }

    @Test
    public void testNormalizeSpace() {
        Assert.assertEquals(" f o o b a r",
                StringUtils.normalizeSpace(" f\to\ro\nb a r "));
    }

    @Test
    public void testTrimAll() {
        Assert.assertNull(StringUtils.trimAll(null));
        Assert.assertEquals("foobar", StringUtils.trimAll(" f\to\ro\nb a r "));
    }
}

Add unit tests for com.site.lookup.util.StringUtils

These tests were written using Diffblue Cover.


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

import static org.junit.Assert.assertEquals;

import java.sql.Timestamp;

import org.junit.Test;
import org.springframework.test.context.transaction.AfterTransaction;
import org.springframework.test.context.transaction.BeforeTransaction;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * This class test behavior during testing distributed transaction.
 *
 * @author m4gik <michal.szczygiel@wp.pl>
 *
 */
public class DistrbutedTransactionDataSourceTest extends BaseDataSourceTest {

    @AfterTransaction
    public void checkPostConditions() {

        int count = getJdbcWarehousePoland().queryForInt(
                "SELECT COUNT(*) FROM DEPOT");
        // This change was rolled back by the test framework
        assertEquals(0, count);

        count = getJdbcWarehouseFinland().queryForInt(
                "SELECT COUNT(*) FROM DEPOT");
        // This rolled back as well because of the XA
        assertEquals(0, count);

    }

    @BeforeTransaction
    public void clearData() {
        getJdbcFinance().update("DELETE FROM REGISTER");
        getJdbcWarehouseFinland().update("DELETE FROM DEPOT");
        getJdbcWarehousePoland().update("DELETE FROM DEPOT");
    }

    @Transactional
    @Test
    public void testInsertIntoTwoDataSources() throws Exception {

        assertEquals(
                1,
                getJdbcFinance()
                        .update("INSERT INTO REGISTER (id, name, register_date, price) VALUES (?,?,?,?)",
                                0, "stuff", (new Timestamp(0)), 16.0));

        assertEquals(
                1,
                getJdbcWarehouseFinland()
                        .update("INSERT INTO DEPOT (id, name, depot_date, amount) VALUES (?,?,?,?)",
                                0, "stuff", (new Timestamp(0)), 16.0));

        assertEquals(
                1,
                getJdbcWarehousePoland()
                        .update("INSERT INTO DEPOT (id, name, depot_date, amount) VALUES (?,?,?,?)",
                                0, "stuff", (new Timestamp(0)), 16.0));

    }

}

Add test for distributed transaction for data sources


package de.developgroup.mrf.rover.collision;

import com.pi4j.io.gpio.GpioController;
import de.developgroup.mrf.server.ClientManager;
import de.developgroup.mrf.server.rpc.JsonRpc2Request;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;

import static org.mockito.Mockito.verify;

public class CollisionRunnableTest {

    CollisionRunnable runnable;
    IRSensorFactory irSensorFactory;
    GpioController gpio;
    ClientManager clientManager;

    @Before
    public void setUp() {
        irSensorFactory = Mockito.mock(IRSensorFactory.class);
        gpio = Mockito.mock(GpioController.class);
        clientManager = Mockito.mock(ClientManager.class);

        runnable = new CollisionRunnable(irSensorFactory, gpio, clientManager);
    }

    @Test
    public void testSendToClients() {
        ArgumentCaptor<JsonRpc2Request> requestCaptor = ArgumentCaptor.forClass(JsonRpc2Request.class);
        RoverCollisionInformation info = new RoverCollisionInformation();

        runnable.sendToClients(info);

        verify(clientManager).notifyAllClients(requestCaptor.capture());
        JsonRpc2Request actualRequest = requestCaptor.getValue();
        Assert.assertEquals(info, actualRequest.getParams().get(0));
        Assert.assertEquals("updateCollisionInformation", actualRequest.getMethod());
    }

    @Test
    public void testConvertSensorReadingToCollisionState() {
        Assert.assertEquals(CollisionState.None, runnable.convertSensorReadingToCollisionState(0.2));
        Assert.assertEquals(CollisionState.None, runnable.convertSensorReadingToCollisionState(0.34));
        Assert.assertEquals(CollisionState.Far, runnable.convertSensorReadingToCollisionState(0.35));
        Assert.assertEquals(CollisionState.Far, runnable.convertSensorReadingToCollisionState(0.39));
        Assert.assertEquals(CollisionState.Medium, runnable.convertSensorReadingToCollisionState(0.4));
        Assert.assertEquals(CollisionState.Medium, runnable.convertSensorReadingToCollisionState(0.49));
        Assert.assertEquals(CollisionState.Close, runnable.convertSensorReadingToCollisionState(0.5));
    }
}

Add unit tests for CollisionRunnable

Add unit tests for CollisionRunnable


package com.mindoo.domino.jna.test;

import java.util.EnumSet;
import java.util.List;
import java.util.Map;

import org.junit.Test;

import com.mindoo.domino.jna.NotesCollection;
import com.mindoo.domino.jna.NotesDatabase;
import com.mindoo.domino.jna.NotesViewEntryData;
import com.mindoo.domino.jna.constants.Navigate;
import com.mindoo.domino.jna.constants.ReadMask;

import lotus.domino.Session;

/**
 * Test case to read counts from the view index
 *
 * @author Karsten Lehmann
 */
public class TestViewTraversalReadCounts extends BaseJNATestClass {

	@Test
	public void testReadingCounts() {
		runWithSession(new IDominoCallable<Object>() {

			@Override
			public Object call(Session session) throws Exception {
				NotesDatabase dbData = getFakeNamesDb();
				NotesCollection companiesView = dbData.openCollectionByName("CompaniesHierarchical");

				String[] categoriesToLookUp = new String[] {"A", "A\\Abbas", "B", "B\\Balbus", "XYZXYZ--doesnotexist--"};

				for (String category : categoriesToLookUp) {
					List<NotesViewEntryData> catEntries = companiesView.getAllEntriesInCategory(category, 0,
							//stay at the category entry:
							EnumSet.of(Navigate.CURRENT),
							//pre-buffer only one row:
							1,
							//read index counts from view index;
							//ReadMask.SUMMARYVALUES is just here so that we can print the column values
							EnumSet.of(
									ReadMask.SUMMARYVALUES,
									ReadMask.INDEXCHILDREN,
									ReadMask.INDEXDESCENDANTS,
									ReadMask.INDEXSIBLINGS
									),
							//return entry data for exactly one entry:
							new NotesCollection.EntriesAsListCallback(1)
							);

					if (!catEntries.isEmpty()) {
						NotesViewEntryData catEntry = catEntries.get(0);
						Map<String,Object> colValues = catEntry.getColumnDataAsMap();
						int descendants = catEntry.getDescendantCount();
						int siblings = catEntry.getSiblingCount();
						int children = catEntry.getChildCount();

						System.out.println("Category found: "+category);
						System.out.println("Column values: "+colValues);
						System.out.println("descendants: "+descendants);
						System.out.println("siblings: "+siblings);
						System.out.println("children: "+children);
					}
					else {
						System.out.println("Category not found: "+category);
					}
					System.out.println("==============");
				}

				return null;
			}
		});
	};

}

Test case to read counts from view index (ignoring reader fields)


package org.intermine.webservice.server;

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

public enum Format {

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

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

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

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

    private final String contentType;

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

    public String getContentType() {
        return contentType;
    }

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

}

Move to a much cleaner format implementation

Former-commit-id: bdfd64ffe5a36a07113dc332121fe540d938cbf6


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

package com.google.sps.servlets;

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

// Delivers a list of strings representing today's trending searches worldwide
@WebServlet("/trending")
public class TrendingServlet extends HttpServlet {

    private List<String> trendingSearches = new ArrayList<>();

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        getTrendingSearches();
        Gson gson = new Gson();
        response.setContentType("text/html;");
        response.getWriter().println(gson.toJson(trendingSearches));
    }

    public void getTrendingSearches() {
        //fetch trending searches from db - hard coded data for now
        trendingSearches.add("Giraffes");
        trendingSearches.add("Chicken nuggets");
    }
}

Add servlet to deliver today's trending searches


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

package org.eclipse.dawnsci.analysis.api.io;

import org.eclipse.dawnsci.analysis.api.dataset.IDataset;
import org.eclipse.dawnsci.analysis.api.dataset.SliceND;
import org.eclipse.dawnsci.analysis.api.monitor.IMonitor;

/**
 * Used by lazy writeable datasets to write slices to a file
 */
public interface ILazySaver extends ILazyLoader {
	/**
	 *
	 * @return true if file is writeable
	 */
	public boolean isFileWriteable();

	/**
	 * @param mon
	 * @param data
	 * @param slice
	 * @throws Exception
	 */
	public void setSlice(IMonitor mon, IDataset data, SliceND slice) throws Exception;
}

Add new saver interface for use by lazy writeable dataset


/******************************************************************
 * File:        SecurityAccess.java
 * Created by:  Dave Reynolds
 * Created on:  2 May 2016
 *
 * (c) Copyright 2016, Epimorphics Limited
 *
 *****************************************************************/

package com.epimorphics.appbase.security;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;

import com.epimorphics.appbase.core.ComponentBase;
import com.epimorphics.appbase.security.AppRealm;
import com.epimorphics.appbase.security.UserInfo;

/**
 * Component to support access to the security features
 */
public class SecurityAccess extends ComponentBase {

    public Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public List<UserInfo> listUsers() {
        return AppRealm.getRealm().getUserStore().listUsers("");
    }

    public boolean checkPermission(UserInfo user, String permission) {
        AppRealm realm = AppRealm.getRealm();
        PrincipalCollection pc = new SimplePrincipalCollection(user, realm.getName());
        try {
            realm.checkPermission(pc, permission);
            return true;
        } catch (AuthorizationException e) {
            return false;
        }
    }
}

Add appbase helper component for accessing security info


package net.imagej.ops.viewOp;

import org.scijava.plugin.Plugin;

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

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

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

}

Add default implementation of ExtendMirrorDouble interface.


/*
 * https://leetcode.com/problems/swap-nodes-in-pairs/
 * Given a linked list, swap every two adjacent nodes and return its head.
 * For example,
 * Given 1->2->3->4, you should return the list as 2->1->4->3.
 * Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed
. */
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null)
            return head;
        ListNode slow = head;
        ListNode fast = head.next;

        while(slow != null && fast != null) {
            int tmp = slow.val;
            slow.val = fast.val;
            fast.val = tmp;
            if(fast.next != null)
                fast = fast.next;
            else
                break;
            slow = fast;

            if(fast.next != null)
                fast = fast.next;
            else
                break;
        }

        return head;
    }
    public void print(ListNode head) {
      while(head != null) {
        System.out.println(head.val);
        head = head.next;
      }
    }
    public ListNode createList(int num) {
        ListNode head = null;
        ListNode tail = head;
        for(int i = 0; i < num; i++) {
            ListNode tmp = new ListNode(i);
            if(head == null) {
                head = tail = tmp;
            } else {
              tail.next = tmp;
              tail = tmp;
            }
        }
        return head;
    }
}

class Main {
  public static void main(String[] args) {
    Solution solution = new Solution();
    ListNode head = solution.createList(11);
    solution.print(head);
    System.out.println();
    solution.swapPairs(head);
    solution.print(head);
  }
}

Add solution 24. Swap Nodes in Pairs

Add solution 24. Swap Nodes in Pairs


package at.ac.tuwien.inso.method_security_tests;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import at.ac.tuwien.inso.service.UserAccountService;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@SpringBootTest
@ActiveProfiles("test")
@Transactional
public class UserAccountServiceSecurityTests {

    @Autowired
    private UserAccountService userAccountService;

    @Test(expected = AuthenticationCredentialsNotFoundException.class)
    public void getCurrentLoggedInUserNotAuthenticated() {
        userAccountService.getCurrentLoggedInUser();
    }

    @Test(expected = UsernameNotFoundException.class)
    @WithMockUser
    public void getCurrentLoggedInUserAuthenticated() {
        userAccountService.getCurrentLoggedInUser();
    }
}

Add tests for UserAccountService security


/*
 * Copyright 2014 MovingBlocks
 *
 * 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.
 */

@API package org.terasology.rendering.nui.layers.ingame.inventory;

import org.terasology.engine.API;

Work stations and crafting in hand now is using NUI/


/*
 * Copyright 2012 Google Inc. 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.errorprone.bugpatterns;

import com.google.errorprone.CompilationTestHelper;
import com.google.errorprone.bugpatterns.InvalidStringEquality;
import com.google.errorprone.matchers.DescribingMatcher;

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

import java.io.File;
import java.net.URL;

/**
 * @author Bill Pugh (bill.pugh@gmail.com)
 */
public abstract class BugPatternUnitTest {

    protected CompilationTestHelper compilationHelper;
    protected String testname;

    protected void setScanner(com.google.errorprone.Scanner scanner) {

        Class<?> c = scanner.getClass().getEnclosingClass();
        if (c == null)
            throw new IllegalArgumentException("Scanner must be an inner class");
        if (!DescribingMatcher.class.isAssignableFrom(c))
            throw new IllegalArgumentException("Bad outer class for scanner: "
                    + c);
        testname = c.getSimpleName();
        compilationHelper = new CompilationTestHelper(
                scanner);
    }

    public void testPositiveCase() throws Exception {
        String name = testname + "PositiveCases.java";
        URL resource = this.getClass().getResource(name);
        if (resource == null)
            throw new RuntimeException("Could not find resource " + name);
        compilationHelper.assertCompileFailsWithMessages(new File(resource
                .toURI()));
    }

    public void testNegativeCase() throws Exception {
        String name = testname + "NegativeCases.java";
        URL resource = this.getClass().getResource(name);
        if (resource == null)
            throw new RuntimeException("Could not find resource " + name);
        compilationHelper.assertCompileSucceeds(new File(resource.toURI()));

    }

}

Add abstract base class for bug pattern unit tests


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

import org.junit.Test;
import rx.Observer;
import rx.schedulers.TestScheduler;

import java.util.concurrent.TimeUnit;

import static org.mockito.Mockito.*;

public class TestSubjectTest {

    @Test
    public void testObserverPropagateValueAfterTriggeringActions() {
        final TestScheduler scheduler = new TestScheduler();

        final TestSubject<Integer> subject = TestSubject.create(scheduler);
        @SuppressWarnings("unchecked")
        Observer<Integer> observer = mock(Observer.class);
        subject.subscribe(observer);

        subject.onNext(1);
        scheduler.triggerActions();

        verify(observer, times(1)).onNext(1);
    }

    @Test
    public void testObserverPropagateValueInFutureTimeAfterTriggeringActions() {
        final TestScheduler scheduler = new TestScheduler();
        scheduler.advanceTimeTo(100, TimeUnit.SECONDS);

        final TestSubject<Integer> subject = TestSubject.create(scheduler);
        @SuppressWarnings("unchecked")
        Observer<Integer> observer = mock(Observer.class);
        subject.subscribe(observer);

        subject.onNext(1);
        scheduler.triggerActions();

        verify(observer, times(1)).onNext(1);
    }
}

Test that finds a TestScheduler bug

Test that finds a TestScheduler bug


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

/**
 * @author Vitaliy.Bibaev
 */
public class SpecialCasesTest extends TraceExecutionTestCase {
  public void testSortedSignedDoubleZeros() {
    doTest(false);
  }
}

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

/**
 * @author Vitaliy.Bibaev
 */
public class SpecialCasesTest extends TraceExecutionTestCase {
  public void testSortedSignedDoubleZeros() {
    doTest(false);
  }

  public void testExceptionAsStreamResult() {
    doTest(false);
  }
}

Check that trace is correct if exception is a result of stream chain


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.biojava3.core.sequence;

/**
 *
 * @author Scooter
 */
public class SequenceOptimizationHints {

    /**
     * @return the sequenceUsage
     */
    public static SequenceUsage getSequenceUsage() {
        return sequenceUsage;
    }

    /**
     * @param aSequenceUsage the sequenceUsage to set
     */
    public static void setSequenceUsage(SequenceUsage aSequenceUsage) {
        sequenceUsage = aSequenceUsage;
    }

    /**
     * @return the sequenceColection
     */
    public static SequenceCollection getSequenceCollection() {
        return sequenceCollection;
    }

    /**
     * @param aSequenceColection the sequenceColection to set
     */
    public static void setSequenceCollection(SequenceCollection aSequenceColection) {
        sequenceCollection = aSequenceColection;
    }

    public enum SequenceUsage {

        FULL_SEQUENCE_DATA, SUB_SEQUENCE_DATA, MINIMAL_SEQUENCE_DATA;
    }

    public enum SequenceCollection {

        ALL_SEQUENCES, VARIABLE_SEQUENCES, MINIMINAL_SEQUENCES;
    }

    static private SequenceUsage sequenceUsage = SequenceUsage.FULL_SEQUENCE_DATA;
    static private SequenceCollection sequenceCollection = SequenceCollection.ALL_SEQUENCES;

}

Introduce class that can provide hints on how the sequences will be used to help optimize for performance or memory

git-svn-id: a754228c0d23e99fefe44e35d84d6184990ceaa2@7341 7c6358e6-4a41-0410-a743-a5b2a554c398


package moe.tristan.easyfxml.model.components.listview;

import moe.tristan.easyfxml.api.FxmlController;
import moe.tristan.easyfxml.api.FxmlFile;
import moe.tristan.easyfxml.api.FxmlNode;
import moe.tristan.easyfxml.model.components.listview.cell.ComponentCellFxmlSampleController;
import moe.tristan.easyfxml.model.components.listview.view.ComponentListViewSampleFxmlController;

public enum CustomListViewTestComponents implements FxmlNode {
    VIEW("view/ComponentListViewSample.fxml", ComponentListViewSampleFxmlController.class),
    CELL("cell/ComponentCell.fxml", ComponentCellFxmlSampleController.class);

    private final String relFileName;
    private final Class<? extends FxmlController> controllerClass;

    CustomListViewTestComponents(String relFileName, Class<? extends FxmlController> controllerClass) {
        this.relFileName = relFileName;
        this.controllerClass = controllerClass;
    }

    @Override
    public FxmlFile getFile() {
        return () -> "moe/tristan/easyfxml/model/components/listview/" + relFileName;
    }

    @Override
    public Class<? extends FxmlController> getControllerClass() {
        return controllerClass;
    }
}

Use a FxmlNode-implementing enum for ComponentListView testing


package javaEndOfFile;

import java.util.Scanner;

public class Solution {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int iterationNumber = 1;
        while(scanner.hasNext()) {
        	String line = scanner.nextLine();
        	System.out.println((iterationNumber++) + " " + line);
        }
        scanner.close();
    }
}

Add solution for problem Java End-of-file, HackerRank/Java/Introduction/Java End-of-file


package net.floodlightcontroller.acamp.msgele;

import net.floodlightcontroller.packet.BasePacket;
import net.floodlightcontroller.packet.IPacket;
import net.floodlightcontroller.packet.PacketParsingException;

public class APBoardData extends BasePacket implements IPacket {

	private String boardDiscription;
	@Override
	public byte[] serialize() {
		byte[] boardDataBytes = null;
		if(boardDiscription != null) {
			boardDataBytes = boardDiscription.getBytes();
		}
		return boardDataBytes;
	}

	@Override
	public IPacket deserialize(byte[] data, int offset, int length)
			throws PacketParsingException {
		if(data.length != 0) {
			this.boardDiscription = new String(data);
		}
		return this;
	}

	public String getBoardDiscription() {
		return boardDiscription;
	}

	public void setBoardDiscription(String boardDiscription) {
		this.boardDiscription = boardDiscription;
	}

}

Complete ALL message element specification, wait for a test!


package org.verapdf.metadata.fixer.utils;

import org.verapdf.metadata.fixer.entity.Metadata;
import org.verapdf.metadata.fixer.entity.PDFDocument;
import org.verapdf.metadata.fixer.utils.parser.ProcessedObjectsParser;
import org.verapdf.validation.profile.model.ValidationProfile;
import org.verapdf.validation.report.model.Result;

/**
 * @author Evgeniy Muravitskiy
 */
public interface FixerConfig {

	Result getValidationResult();

	ValidationProfile getValidationProfile();

	Metadata getMetadata();

	PDFDocument getDocument();

	ProcessedObjectsParser getParser();
}

Add config object for metadata fixer

Add config object for metadata fixer


package net.buycraft.plugin.sponge.util;

import com.google.common.collect.ImmutableList;
import lombok.Getter;
import net.buycraft.plugin.util.CommandOutput;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.source.ConsoleSource;
import org.spongepowered.api.service.context.Context;
import org.spongepowered.api.service.permission.Subject;
import org.spongepowered.api.service.permission.SubjectCollection;
import org.spongepowered.api.service.permission.SubjectData;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.channel.MessageChannel;
import org.spongepowered.api.util.Tristate;

import java.util.List;
import java.util.Optional;
import java.util.Set;

public class LoggingCommandSource implements ConsoleSource {
    @Getter
    private final CommandOutput output = new CommandOutput();

    @Override
    public String getName() {
        return "CONSOLE^BC";
    }

    @Override
    public String getIdentifier() {
        return Sponge.getServer().getConsole().getIdentifier();
    }

    @Override
    public Set<Context> getActiveContexts() {
        return Sponge.getServer().getConsole().getActiveContexts();
    }

    @Override
    public void sendMessage(Text text) {
        output.addLine(text.toPlain());
    }

    @Override
    public MessageChannel getMessageChannel() {
        return MessageChannel.fixed(this);
    }

    @Override
    public void setMessageChannel(MessageChannel messageChannel) {

    }

    @Override
    public Optional<CommandSource> getCommandSource() {
        return Optional.of(this);
    }

    @Override
    public SubjectCollection getContainingCollection() {
        return Sponge.getServer().getConsole().getContainingCollection();
    }

    @Override
    public SubjectData getSubjectData() {
        return Sponge.getServer().getConsole().getSubjectData();
    }

    @Override
    public SubjectData getTransientSubjectData() {
        return Sponge.getServer().getConsole().getTransientSubjectData();
    }

    @Override
    public boolean hasPermission(Set<Context> set, String s) {
        return true;
    }

    @Override
    public Tristate getPermissionValue(Set<Context> set, String s) {
        return Tristate.TRUE;
    }

    @Override
    public boolean isChildOf(Set<Context> set, Subject subject) {
        return true;
    }

    @Override
    public List<Subject> getParents(Set<Context> set) {
        return ImmutableList.of();
    }
}

Add command sender logging support for Sponge


/*
* 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.jackrabbit.oak.plugins.document.util;

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

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

import org.junit.Test;

public class UTF8EncoderTest {

    private static char[] SURROGATE_PAIR = Character.toChars(0x1f4a9);

    @Test
    public void encodeValid() throws IOException {

        // a a-umlaut euro plane-1-char
        String test = "a \u00E4 \u20ac " + new String(SURROGATE_PAIR);

        byte[] withStringClass = test.getBytes(StandardCharsets.UTF_8);
        byte[] withUtilsClass = UTF8Encoder.encodeAsByteArray(test);
        assertArrayEquals(withStringClass, withUtilsClass);
        assertEquals(test, new String(withUtilsClass, StandardCharsets.UTF_8));
    }

    @Test
    public void encodeInValid() {

        // a a-umlaut euro plane-1-char, second char in surrogate pair missing
        String test = "a \u00E4 \u20ac " + SURROGATE_PAIR[0];

        try {
            UTF8Encoder.encodeAsByteArray(test);
            fail("expected encoding to fail");
        } catch (IOException expected) {
            // expected
        }
    }

    @Test
    public void encodeMultiThreaded() throws InterruptedException {

        int tc = 20;

        Thread[] threads = new Thread[tc];

        for (int i = 0; i < tc; i++) {
            threads[i] = new Thread(new Runnable() {
                @Override
                public void run() {
                    // encode and decode 100 random UUID strings
                    for (int j = 0; j < 100; j++) {
                        String test = UUID.randomUUID().toString();
                        String roundtripped = null;
                        try {
                            byte[] bytes = UTF8Encoder.encodeAsByteArray(test);
                            roundtripped = new String(bytes, StandardCharsets.UTF_8);
                        } catch (IOException exignored) {
                        }
                        assertEquals(test, roundtripped);
                    }

                }
            });
        }
        for (int i = 0; i < tc; i++) {
            threads[i].start();
        }
        for (int i = 0; i < tc; i++) {
            threads[i].join();
        }
    }
}

OAK-7268: Create charset encoding utility that detects malformed input

(add test coverage)

git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1824255 13f79535-47bb-0310-9956-ffa450edef68


package org.biojava.nbio.structure.symmetry.core;

/**
 * Method used for symmetry perception in the {@link QuatSymmetryDetector}.
 *
 * @author Aleix Lafita
 * @since 5.0.0
 *
 */
public enum SymmetryPerceptionMethod {
	NO_ROTATION,
	C2_ROTATION,
	ROTATION,
	ROTO_TRANSLATION;
}

Create an ENUM for the symmetry perception methods


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

package org.scijava.notebook.converter;

import org.scijava.Priority;
import org.scijava.convert.Converter;
import org.scijava.notebook.converter.output.HTMLNotebookOutput;
import org.scijava.plugin.Plugin;

@Plugin(type = Converter.class, priority = Priority.LOW_PRIORITY)
public class NumberToHTMLNotebookConverter
        extends NotebookOutputConverter<Number, HTMLNotebookOutput> {

    @Override
    public Class<Number> getInputType() {
        return Number.class;
    }

    @Override
    public Class<HTMLNotebookOutput> getOutputType() {
        return HTMLNotebookOutput.class;
    }

    @Override
    public HTMLNotebookOutput convert(Object object) {
        return new HTMLNotebookOutput(object.toString());
    }

}

Add number to HTML converter

Add number to HTML converter


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

import org.auraframework.def.ComponentDef;
import org.auraframework.def.DefDescriptor;
import org.auraframework.impl.AuraImplTestCase;
import org.auraframework.impl.root.component.BaseComponentDefImpl;
import org.junit.Test;

@SuppressWarnings("unchecked")
public class BaseComponentDefImplTest extends AuraImplTestCase{

    @Test
    public void testHasFacetLocalDependenciesWhenServerDependedCmpOnFacet() throws Exception {
        // Arrange
        String cmpWithServerProvider =
                "<aura:component abstract='true' extensible='true' provider='java://org.auraframework.impl.java.provider.TestProviderAbstractBasic'>\n" +
                "</aura:component>";
        DefDescriptor<ComponentDef> facetCmp = addSourceAutoCleanup(ComponentDef.class, cmpWithServerProvider);

        String cmpMarkup = String.format("<aura:component> <%s/> </aura:component>", facetCmp.getDescriptorName());
        DefDescriptor<ComponentDef> desc = addSourceAutoCleanup(ComponentDef.class, cmpMarkup);

        // Act
        BaseComponentDefImpl<ComponentDef> def = (BaseComponentDefImpl<ComponentDef>) definitionService.getDefinition(desc);
        boolean actual = def.hasFacetLocalDependencies();

        // Assert
        assertTrue(actual);
    }

}

Add a test for local dependencies

Add a test for local dependencies


package com.jwetherell.algorithms.strings.test;

import com.jwetherell.algorithms.strings.StringInformations;
import org.junit.Test;

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

import static org.junit.Assert.*;

public class StringInformationTest {

    @Test
    public void getPrefixSuffixes() throws Exception {
        List<Object[]> data = Arrays.asList(new Object[][]{
                {"", new ArrayList<Integer>()},
                {"a", Arrays.asList(0)},
                {"aaa", Arrays.asList(0, 1, 2)},
                {"abbabb", Arrays.asList(0, 0, 0, 1, 2, 3)},
                {"bbabbbbaab", Arrays.asList(0, 1, 0, 1, 2, 2, 2, 3, 0, 1)},
                {
                    "( ͡° ͜ʖ ͡° )( ͡° a( ͡° ͜ʖ ͡°",
                     Arrays.asList(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
                }
        });
        for(Object[] testCase: data) {
            String input = (String) testCase[0];
            List<Integer> expected = (List<Integer>) testCase[1];
            assertEquals(expected, StringInformations.getPrefSufTable(input));
        }
    }

}

Test for finding prefix-suffix table

Test for finding prefix-suffix table


import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

import java.util.Arrays;

public class ConvertArray {

	public int getOriginalIndex(int currentIndex, int length) {
		return (currentIndex % 3) * length + currentIndex/3;
	}

	public int[] convert(int[] input) {
	  // When array size is less than 3, returns an error.
	  if (input.length % 3 != 0 ) {
			System.out.println("Error! Array cannot be divided into three equal parts");
			return;
		}
		for (int i = 0; i < input.length; ++i) {
			int originalIndex = getOriginalIndex(i, input.length/3);
			while (originalIndex < i) {
				originalIndex = getOriginalIndex(originalIndex, input.length/3);
			}
			int temp = input[i];
			input[i] = input[originalIndex];
			input[originalIndex] = temp;
		}
		return input;
	}

	public static void main(String[] args) {
		ConvertArray c = new ConvertArray();
		int[] test1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		System.out.println(Arrays.toString(c.convert(test1)));

	}
}

Update to handle an edge case

Update to handle an edge case

Added an update to handle the case when array size is not a multiple of 3.
Without this the program will run into an infinite loop!


package com.xtremelabs.robolectric.shadows;

import static org.junit.Assert.*;

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

import com.xtremelabs.robolectric.Robolectric;
import com.xtremelabs.robolectric.WithTestDefaultsRunner;

import android.media.AudioManager;

@RunWith(WithTestDefaultsRunner.class)
public class AudioManagerTest {

	private AudioManager audioManager;
	private ShadowAudioManager shadowAudioManager;

	@Before
	public void setUp() throws Exception {
        Robolectric.bindDefaultShadowClasses();

        audioManager = Robolectric.newInstanceOf( AudioManager.class );
        shadowAudioManager = Robolectric.shadowOf( audioManager );
	}

	@After
	public void tearDown() throws Exception {
	}

    @Test
    public void shouldGetStreamMaxVolume() throws Exception {
    	shadowAudioManager.setStreamMaxVolume( 45 );

    	assertEquals( 45, audioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC ));
    }

    @Test
    public void shouldGetVolume() throws Exception {
    	shadowAudioManager.setStreamVolume( 5 );

    	assertEquals( 5, audioManager.getStreamVolume( AudioManager.STREAM_MUSIC ));
    }

    @Test
    public void shouldSetVolume() throws Exception {
    	audioManager.setStreamVolume( AudioManager.STREAM_MUSIC, 8, 0 );

    	assertEquals( 8, audioManager.getStreamVolume( AudioManager.STREAM_MUSIC ));
    	assertEquals( 8, shadowAudioManager.getStreamVolume() );
    }

}

Remove streamType field for ShadowAudioManager, as it is not used. Add test case.


package org.tinyj.lava;

/**
 * A supplier of `boolean` values. This is the exception declaring version of
 * Java's [`BooleanSupplier`](https://docs.oracle.com/javase/8/docs/api/java/util/function/BooleanSupplier.html)
 *
 * There is no requirement that a new or distinct result be returned each
 * time the supplier is invoked.
 *
 * This is a functional interface whose functional method is `checkedGetAsBoolean()`.
 *
 * @param <E> upper limit of thrown exception types
 */
@FunctionalInterface
public interface LavaBooleanSupplier<E extends Exception> {

  /**
   * Produce a value.
   *
   * @return a value
   */
  boolean checkedGetAsBoolean() throws E;

  /**
   * Safely casts between different (#LavaSupplier) parametrization
   *
   * @param <E> required exception limit
   * @param supplier supplier to adopt
   * @return `supplier` casted to the compatible parametrization (#LavaSupplier)`<R, E>`
   */
  @SuppressWarnings("unchecked")
  static <E extends Exception>
  LavaBooleanSupplier<E> castDown(LavaBooleanSupplier<? extends E> supplier) {
    return (LavaBooleanSupplier<E>) supplier;
  }
}

Add lava version of `BooleanSupplier`

Add lava version of `BooleanSupplier`


package forager.server;

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

public class EventMap {

    protected static final Map<Integer, Class<?>> intToClass = new HashMap<>();
    protected static final Map<Class<?>, Integer> classToInt = new HashMap<>();

    public EventMap() { }

    protected static void addMapping(int id, Class<?> clazz) {
        intToClass.put(id, clazz);
        classToInt.put(clazz, id);
    }

    public static Class<?> getClass(int id) {
        return intToClass.get(id);
    }

    public static int getInt(Class<?> clazz) {
        return classToInt.get(clazz);
    }
}

Add event map base class

Add event map base class


package tachyon.worker.block.io;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.ByteChannel;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;

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

import com.google.common.base.Preconditions;
import com.google.common.io.Closer;

import tachyon.Constants;
import tachyon.util.CommonUtils;
import tachyon.worker.block.meta.BlockMeta;

/**
 * This class provides write access to a block data file locally stored in managed storage.
 * <p>
 * This class does not provide thread-safety. Corresponding lock must be acquired.
 */
public class LocalFileBlockWriter implements BlockWriter {
  private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
  private final BlockMeta mBlockMeta;
  private final String mFilePath;
  private final RandomAccessFile mLocalFile;
  private final FileChannel mLocalFileChannel;
  private final Closer mCloser = Closer.create();

  public LocalFileBlockWriter(BlockMeta blockMeta) throws IOException {
    mBlockMeta = Preconditions.checkNotNull(blockMeta);
    mFilePath = mBlockMeta.getPath();
    mLocalFile = mCloser.register(new RandomAccessFile(mFilePath, "w"));
    mLocalFileChannel = mCloser.register(mLocalFile.getChannel());
  }

  @Override
  public WritableByteChannel getChannel() {
    return mLocalFileChannel;
  }

  @Override
  public long append(ByteBuffer inputBuf) throws IOException {
    return write(mLocalFileChannel.size(), inputBuf);
  }

  /**
   * Writes data to the block from an input ByteBuffer.
   *
   * @param offset starting offset of the block file to write
   * @param inputBuf ByteBuffer that input data is stored in
   * @return the size of data that was written
   * @throws IOException
   */
  private long write(long offset, ByteBuffer inputBuf) throws IOException {
    int inputBufLength = inputBuf.limit();
    ByteBuffer outputBuf =
        mLocalFileChannel.map(FileChannel.MapMode.READ_WRITE, offset, inputBufLength);
    outputBuf.put(inputBuf);
    CommonUtils.cleanDirectBuffer(outputBuf);
    return outputBuf.limit();
  }

  @Override
  public boolean delete() {
    return new File(mFilePath).delete();
  }

  @Override
  public boolean move(String dstPath) {
    // Check if destPath equals the current path, in this case, do nothing.
    if (mFilePath.equals(dstPath)) {
      return true;
    }
    return new File(mFilePath).renameTo(new File(dstPath));
  }
}

Add a implementation of BlockWriter based on local file


package com.pspdfkit.vangogh.api;

import io.reactivex.Completable;

/**
 * Class containing convenient animation scheduling methods.
 */
public final class AnimationSchedulers {

    public static Completable together(Completable... animations) {
        return Completable.mergeArray(animations);
    }

    public static Completable sequentially(Completable... animations) {
        return Completable.concatArray(animations);
    }

}

Add simple animation scheduling methods

Add simple animation scheduling methods


/*
 *     Copyright 2015 IBM Corp.
 *     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.ibm.mobilefirstplatform.clientsdk.android.analytics.api.internal;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

/**
 * Implements the android life cycle callbacks to be registered with the application.
 *
 * Implemented as a singleton so that application callbacks can only be registered once.
 */
public class MFPAnalyticsActivityLifecycleListener implements Application.ActivityLifecycleCallbacks{
    private static MFPAnalyticsActivityLifecycleListener instance;

    public static void init(Application app) {
        if (instance == null) {
            instance = new MFPAnalyticsActivityLifecycleListener();
            app.registerActivityLifecycleCallbacks(instance);
        }
    }

    @Override
    public void onActivityResumed(Activity activity) {
        //WLLifecycleHelper.getInstance().onPause();
    }

    @Override
    public void onActivityPaused(Activity activity) {
        //WLLifecycleHelper.getInstance().onResume();
    }

    // we do not currently instrument any other lifecycle callbacks
    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {}

    @Override
    public void onActivityStarted(Activity activity) {}

    @Override
    public void onActivityStopped(Activity activity) {}

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {}

    @Override
    public void onActivityDestroyed(Activity activity) {}
}

Add activity lifecycle listener that will be used with ActivityManager.


package org.nuxeo.ecm.platform.content.template.tests;

import org.nuxeo.ecm.core.api.DocumentModel;
import org.nuxeo.ecm.core.api.DocumentModelList;
import org.nuxeo.ecm.core.repository.jcr.testing.RepositoryOSGITestCase;

/**
*   Simple test class for ContentCreationListener
* @ JULIEN THIMONIER < jt@nuxeo.com >
**/
public class ContentCreationListenerTest extends RepositoryOSGITestCase {

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        deployBundle("org.nuxeo.ecm.platform.content.template");
        deployBundle("org.nuxeo.ecm.relations");
        openRepository();
    }

    public void testContentCreationListener() throws Exception {
        DocumentModel root = getCoreSession().getRootDocument();
        DocumentModel model = getCoreSession().createDocumentModel(
                root.getPathAsString(), "mondomaine", "Domain");
        DocumentModel doc = getCoreSession().createDocument(model);
        getCoreSession().saveDocument(doc);
        assert (doc != null);

        DocumentModelList modelList = getCoreSession().getChildren(doc.getRef());

        // Check that 3 elements have been created on the new domain
        // (Section,Workspace and Templates)
        // This should be done by ContentCreationListener
        assert (modelList.size() == 3);
    }
}

Add a new test case for ContentCreationListener


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

package org.scijava.sjep;

/**
 * A mutable parse position. Similar to {@link java.text.ParsePosition}, but
 * less complex.
 *
 * @author Curtis Rueden
 */
public class Position {

	private int index;

	public int get() {
		return index;
	}

	public void set(final int index) {
		this.index = index;
	}

	public void inc() {
		inc(1);
	}

	public void inc(final int count) {
		index += count;
	}

	/** Throws {@link IllegalArgumentException} when syntax is incorrect. */
	public void die(final String message) {
		throw new IllegalArgumentException(messageWithDetails(message));
	}

	/** Throws {@link IllegalStateException} if something goes wrong. */
	public void assertThat(final boolean condition, final String message) {
		if (condition) return;
		fail(message);
	}

	/** Throws {@link IllegalStateException} when something is wrong. */
	public void fail(final String message) {
		throw new IllegalStateException(messageWithDetails(message));
	}

	// -- Object methods --

	@Override
	public String toString() {
		return "" + get();
	}

	// -- Helper methods --

	private String messageWithDetails(final String message) {
		return message + " at index " + get();
	}

}

Add a little helper for tracking parse position

This will take the place of the currently-used ParsePosition,
once we migrate the number parsing logic away from NumberFormat.


package nl.hsac.fitnesse.fixture.slim;

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

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

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

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

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

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

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

    public String getSaveBase() {
        return saveBase;
    }

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

Add fixture to deal with base64 encoded binary values


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

package org.cyanogenmod.hardware;

import org.cyanogenmod.hardware.util.FileUtils;

/*
 * Disable capacitive keys
 *
 * This is intended for use on devices in which the capacitive keys
 * can be fully disabled for replacement with a soft navbar. You
 * really should not be using this on a device with mechanical or
 * otherwise visible-when-inactive keys
 */

public class KeyDisabler {

    private static String CONTROL_PATH = "/sys/class/sec/sec_touchkey/input/enabled";

    public static boolean isSupported() {
        return true;
    }

    public static boolean isActive() {
        return (FileUtils.readOneLine(CONTROL_PATH).equals("0"));
    }

    public static boolean setActive(boolean state) {
        return FileUtils.writeLine(CONTROL_PATH, (state ? "0" : "1"));
    }

}

Allow capacitive buttons to be disabled

zero: Allow capacitive buttons to be disabled


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

package org.springframework.boot.actuate.autoconfigure.metrics.export.properties;

import java.time.Duration;

import org.junit.Test;

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

/**
 * Base test for {@link StepRegistryPropertiesConfigAdapter} implementations.
 *
 * @author Stephane Nicoll
 */
public abstract class StepRegistryPropertiesConfigAdapterTests<P extends StepRegistryProperties, A extends StepRegistryPropertiesConfigAdapter<P>> {

	protected abstract P createProperties();

	protected abstract A createConfigAdapter(P properties);

	@Test
	public void whenPropertiesStepIsSetAdapterStepReturnsIt() {
		P properties = createProperties();
		properties.setStep(Duration.ofSeconds(42));
		assertThat(createConfigAdapter(properties).step())
				.isEqualTo(Duration.ofSeconds(42));
	}

	@Test
	public void whenPropertiesEnabledIsSetAdapterEnabledReturnsIt() {
		P properties = createProperties();
		properties.setEnabled(false);
		assertThat(createConfigAdapter(properties).enabled()).isFalse();
	}

	@Test
	public void whenPropertiesConnectTimeoutIsSetAdapterConnectTimeoutReturnsIt() {
		P properties = createProperties();
		properties.setConnectTimeout(Duration.ofMinutes(42));
		assertThat(createConfigAdapter(properties).connectTimeout())
				.isEqualTo(Duration.ofMinutes(42));
	}

	@Test
	public void whenPropertiesReadTimeoutIsSetAdapterReadTimeoutReturnsIt() {
		P properties = createProperties();
		properties.setReadTimeout(Duration.ofMillis(42));
		assertThat(createConfigAdapter(properties).readTimeout())
				.isEqualTo(Duration.ofMillis(42));
	}

	@Test
	public void whenPropertiesNumThreadsIsSetAdapterNumThreadsReturnsIt() {
		P properties = createProperties();
		properties.setNumThreads(42);
		assertThat(createConfigAdapter(properties).numThreads()).isEqualTo(42);
	}

	@Test
	public void whenPropertiesBatchSizeIsSetAdapterBatchSizeReturnsIt() {
		P properties = createProperties();
		properties.setBatchSize(10042);
		assertThat(createConfigAdapter(properties).batchSize()).isEqualTo(10042);
	}

}

Add base test for StepRegistryPropertiesConfigAdapter


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

package c5db.util;

import com.google.common.collect.Iterators;

import java.util.Iterator;

public class C5Iterators {

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

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

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

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

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

Add a lazy Iterator advance method

Add a lazy Iterator advance method


package fr.tvbarthel.apps.sayitfromthesky.helpers;

import android.database.Cursor;

/**
 * Static utility methods for dealing with cursor.
 */
public final class CursorHelper {

    // Non-instantiability
    private CursorHelper() {
    }

    public static String getString(Cursor cursor, String columnName, String defaultValue) {
        final int columnIndex = cursor.getColumnIndex(columnName);
        if (columnIndex == -1) return defaultValue;
        return cursor.getString(columnIndex);
    }

    public static long getLong(Cursor cursor, String columnName, long defaultValue) {
        final int columnIndex = cursor.getColumnIndex(columnName);
        if (columnIndex == -1) return defaultValue;
        return cursor.getLong(columnIndex);
    }

}

Add an helper class to deal with cursor

Add an helper class to deal with cursor


// Use an enum constructor, instance variable, and method.
enum Transport {
	CAR(65), TRUCK(55), AIRPLANE(600), TRAIN(70), BOAT(22);

	private int speed; // typical speed of each transport

	// Constructor
	Transport(int s) { speed = s; }

	int getSpeed() { return speed; }
}

class EnumDemo3 {
	public static void main(String args[]) {
		Transport tp;
		// Display speed of an airplane.
		System.out.println("Typical speed for an airplane is " + Transport.AIRPLANE.getSpeed() + " miles per hour.\n");

		// Display all Transports and speeds.
		System.out.println("All Transport speeds: ");
		for(Transport t : Transport.values())
			System.out.println(t + " typical speed is " + t.getSpeed() + " miles per hour.");
	}
}

Use an enum constructor, instance variable, and method

http://ideone.com/0anDBm


package info.u_team.u_team_core.tileentity;

import net.minecraft.tileentity.*;

public abstract class UTickableTileEntity extends UTileEntity implements ITickableTileEntity {

	private boolean first;

	public UTickableTileEntity(TileEntityType<?> type) {
		super(type);
	}

	@Override
	public void tick() {
		if (!first) {
			first = true;
			firstTick();
		}
		if (world.isRemote()) {
			tickClient();
		} else {
			tickServer();
		}
	}

	protected void firstTick() {
	}

	protected void tickServer() {
	}

	protected void tickClient() {
	}

}

Add u tickable tile entity

Add u tickable tile entity


package water;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import water.util.JProfile;

public class ProfilerTest extends TestUtil {

  @BeforeClass public static void stall() { stall_till_cloudsize(3); }

  @Test public void testProfiler() {
    for( int i=0; i<10; i++ ) {
      JProfile jp = new JProfile(5);
      jp.execImpl();
      Assert.assertEquals(jp.nodes.length,H2O.CLOUD.size());
      for (int j=0; j<H2O.CLOUD.size(); ++j) {
        Assert.assertTrue(jp.nodes[j].profile != null);
      }
    }
  }
}

Add JUnit test for Profiler.

Add JUnit test for Profiler.


package org.tinylog.impl.test;

import org.tinylog.impl.LogEntry;
import org.tinylog.impl.format.Placeholder;

/**
 * Renderer for {@link Placeholder Placeholders}.
 */
public class PlaceholderRenderer {

	private final Placeholder placeholder;

	/**
	 * @param placeholder The placeholder to render
	 */
	public PlaceholderRenderer(Placeholder placeholder) {
		this.placeholder = placeholder;
	}

	/**
	 * Renders the stored placeholder with the passed log entry as input.
	 *
	 * @param logEntry The log entry as input for {@link Placeholder#render(StringBuilder, LogEntry)}
	 * @return The render result
	 */
	public String render(LogEntry logEntry) {
		StringBuilder builder = new StringBuilder();
		placeholder.render(builder, logEntry);
		return builder.toString();
	}

}

Add placeholder renderer for JUnit tests


/*
 * Copyright 2020 MD Sayem Ahmed
 *
 * 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.sayemahmed.example.springboot;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HealthController {

  @GetMapping("/health")
  public String health() {
    return "up";
  }
}

Add simple health check controller

Add simple health check controller


package com.yahoo.searchdefinition.processing;

import com.yahoo.config.model.test.MockApplicationPackage;
import com.yahoo.document.DataType;
import com.yahoo.document.Field;
import com.yahoo.searchdefinition.DocumentReference;
import com.yahoo.searchdefinition.Search;
import com.yahoo.searchdefinition.document.ImportedField;
import com.yahoo.searchdefinition.document.ImportedFields;
import com.yahoo.searchdefinition.document.SDDocumentType;
import com.yahoo.searchdefinition.document.SDField;
import com.yahoo.vespa.documentmodel.DocumentSummary;
import com.yahoo.vespa.documentmodel.SummaryField;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import java.util.Collections;

/**
 * @author bjorncs
 */
public class ValidateFieldTypesTest {

    private static final String IMPORTED_FIELD_NAME = "imported_myfield";
    private static final String DOCUMENT_NAME = "mydoc";

    @Rule
    public final ExpectedException exceptionRule = ExpectedException.none();

    @Test
    public void throws_exception_if_type_of_document_field_does_not_match_summary_field() {
        Search search = createDocumentWithImportedFieldInDocumentSummary();
        ValidateFieldTypes validator = new ValidateFieldTypes(search, null, null, null);
        exceptionRule.expect(IllegalArgumentException.class);
        exceptionRule.expectMessage(
                "For search '" + DOCUMENT_NAME + "', field '" + IMPORTED_FIELD_NAME + "': Incompatible types. " +
                "Expected int for summary field '" + IMPORTED_FIELD_NAME + "', got string.");
        validator.process();
    }

    private static Search createDocumentWithImportedFieldInDocumentSummary() {
        // Create search with a single imported field
        Search search = new Search(DOCUMENT_NAME, MockApplicationPackage.createEmpty());
        SDDocumentType document = new SDDocumentType("mydoc", search);
        search.addDocument(document);
        Search targetDocument = new Search("otherdoc", MockApplicationPackage.createEmpty());
        SDField targetField = new SDField("myfield", DataType.INT);
        DocumentReference documentReference = new DocumentReference(new Field("reference_field"), targetDocument);
        ImportedField importedField = new ImportedField(IMPORTED_FIELD_NAME, documentReference, targetField);
        search.setImportedFields(new ImportedFields(Collections.singletonMap(IMPORTED_FIELD_NAME, importedField)));

        // Create document summary
        DocumentSummary summary = new DocumentSummary("mysummary");
        summary.add(new SummaryField(IMPORTED_FIELD_NAME, DataType.STRING));
        search.addSummary(summary);
        return search;
    }
}

Verify validation of types in summary fields