package uk.ac.ebi.spot.goci.curation.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import uk.ac.ebi.spot.goci.model.DiseaseTrait;
import uk.ac.ebi.spot.goci.model.projection.DiseaseTraitProjection;
import uk.ac.ebi.spot.goci.repository.DiseaseTraitRepository;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Controller
class ViewController {

    @Autowired
    private DiseaseTraitRepository diseaseTraitRepository;

    @GetMapping("/disease-traits")
    public String masterdetailPage(Model model) {

        List<Map<String, Object>> dataList = new ArrayList<>();
        List<DiseaseTraitProjection> projections =
                diseaseTraitRepository.findAllOrOrderByStudiesLargest(new PageRequest(0, 30));

        projections.forEach(x->{
            Map<String, Object> result = new HashMap<>();
            result.put("country", x.getTrait());
            result.put("visits", x.getStudiesCount());
            dataList.add(result);
        });

        List<Long> ids = new ArrayList<>();
        AtomicInteger count = new AtomicInteger(1);
        projections.forEach(projection -> {
            if (count.get() <= 4){
                ids.add(projection.getId());
                count.getAndIncrement();
            }
        });
        List<DiseaseTrait> diseaseTraits = diseaseTraitRepository.findAllByIdIsIn(ids);
        List<Object> parents = new ArrayList<>();
        diseaseTraits.forEach(diseaseTrait -> {
            String trait = diseaseTrait.getTrait();
            List<Map<String, Object>> children = new ArrayList<>();
            diseaseTrait.getStudies().forEach(study -> {
                Map<String, Object> child = new HashMap<>();
                child.put("name", study.getPublicationId().getPubmedId());
                child.put("value", 40);
                children.add(child);
            });

            Map<String, Object> parent = new LinkedHashMap<>();
            parent.put("name", trait+" ("+children.size()+")");
            parent.put("value", 102);
            parent.put("children", children);
            parents.add(parent);
        });

        List<Object> parents2 = new ArrayList<>();
        Map<String, Object> parenta = new LinkedHashMap<>();

        parenta.put("name", "core");
        parenta.put("value", "10");
        parenta.put("children", parents);
        parents2.add(parenta);

        model.addAttribute("dataList", dataList);
        model.addAttribute("mapData", parents2);
        return "disease-traits";
    }
}

Add New View controller to serve the new diseaseTait Page


/*******************************************************************************
 * Copyright © 2015 EMBL - European Bioinformatics Institute
 *

 * Licensed under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 *

 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific
 * language governing permissions and limitations under the
 * License.
 ******************************************************************************/

package org.mousephenotype.cda.loads.create.releasenotes;

import org.mousephenotype.cda.db.utilities.SqlUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

import javax.sql.DataSource;

@Configuration
@EnableJpaRepositories(basePackages = {"org.mousephenotype.cda.db.repositories"})
@EntityScan("org.mousephenotype.cda.db.pojo")
@ComponentScan(basePackages = {"org.mousephenotype.cda.loads.derived"})
public class ReleaseAnalyticsManagerConfig {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${datasource.cda_derived.jdbc-url}")
    String komp2Url;

    @Value("${datasource.cda_derived.username}")
    String komp2Username;

    @Value("${datasource.cda_derived.password}")
    String komp2Password;

    @Bean(name = "komp2DataSource")
    @Primary
    public DataSource komp2DataSource() {
        return SqlUtils.getConfiguredDatasource(komp2Url, komp2Username, komp2Password);
    }
}

Add configuration for the release analytics job


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

package co.phoenixlab.discord.api.exceptions;

import com.mashape.unirest.http.HttpMethod;

public class RequestDeniedToBotsException extends InvalidApiRequestException {

    public RequestDeniedToBotsException() {
    }

    public RequestDeniedToBotsException(Throwable cause) {
        super(cause);
    }

    public RequestDeniedToBotsException(String endpoint, String message) {
        super(endpoint, message);
    }

    public RequestDeniedToBotsException(String endpoint, String message, Throwable throwable) {
        super(endpoint, message, throwable);
    }

    public RequestDeniedToBotsException(String endpoint, Throwable throwable) {
        super(endpoint, throwable);
    }

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

    public RequestDeniedToBotsException(HttpMethod method, String endpoint) {
        super(method, endpoint);
    }

    public RequestDeniedToBotsException(HttpMethod method, String endpoint, String message) {
        super(method, endpoint, message);
    }

    public RequestDeniedToBotsException(HttpMethod method, String endpoint, String message, Throwable throwable) {
        super(method, endpoint, message, throwable);
    }

    public RequestDeniedToBotsException(HttpMethod method, String endpoint, Throwable throwable) {
        super(method, endpoint, throwable);
    }
}

Add request denied to bots exception

Add request denied to bots exception


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

import com.opengamma.financial.generator.AbstractPortfolioGeneratorTool;
import com.opengamma.financial.generator.FXForwardSecurityGenerator;
import com.opengamma.financial.generator.LeafPortfolioNodeGenerator;
import com.opengamma.financial.generator.PortfolioNodeGenerator;
import com.opengamma.financial.generator.PositionGenerator;
import com.opengamma.financial.generator.SimplePositionGenerator;
import com.opengamma.financial.generator.StaticNameGenerator;
import com.opengamma.financial.security.fx.FXForwardSecurity;

/**
 * Utility for constructing a random FX Forward portfolio.
 */
public class FxForwardPortfolioGeneratorTool extends AbstractPortfolioGeneratorTool {

  @Override
  public PortfolioNodeGenerator createPortfolioNodeGenerator(final int portfolioSize) {
    final FXForwardSecurityGenerator securities = new FXForwardSecurityGenerator();
    configure(securities);
    final PositionGenerator positions = new SimplePositionGenerator<FXForwardSecurity>(securities, getSecurityPersister(), getCounterPartyGenerator());
    return new LeafPortfolioNodeGenerator(new StaticNameGenerator("FX Forwards"), positions, portfolioSize);
  }

}

Add FX Forward generator tool

Add FX Forward generator tool


package edu.northwestern.bioinformatics.studycalendar.security;

import edu.northwestern.bioinformatics.studycalendar.testing.StudyCalendarTestCase;
import edu.northwestern.bioinformatics.studycalendar.domain.Role;
import org.acegisecurity.userdetails.UserDetailsService;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.easymock.classextension.EasyMock;
import static org.easymock.classextension.EasyMock.*;

/**
 * @author Rhett Sutphin
 */
public class WebSSOAuthoritiesPopulatorTest extends StudyCalendarTestCase {
    private WebSSOAuthoritiesPopulator populator;
    private UserDetailsService userDetailsService;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        userDetailsService = registerMockFor(UserDetailsService.class);
        populator = new WebSSOAuthoritiesPopulator();
        populator.setUserDetailsService(userDetailsService);
    }

    public void testPopulation() throws Exception {
        String expectedSsoUserId = "CAGRID_SSO_EMAIL_ID^jo@org.org$CAGRID_SSO_FIRST_NAME^Josephine$CAGRID_SSO_LAST_NAME^Miller$CAGRID_SSO_GRID_IDENTITY^ablablab";
        String expectedAddress = "jo@org.org";
        expect(userDetailsService.loadUserByUsername(expectedAddress)).andReturn(
            new User(expectedAddress, "ignored", true, true, true, true, new Role[] { Role.STUDY_ADMIN }));
        replayMocks();

        UserDetails details = populator.getUserDetails(expectedSsoUserId);
        assertTrue("Returned details not an instance of WebSSOUser", details instanceof WebSSOUser);
        WebSSOUser ssoDetails = (WebSSOUser) details;
        assertEquals("First name not preserved", "Josephine", ssoDetails.getFirstName());
        assertEquals("Last name not preserved", "Miller", ssoDetails.getLastName());
        assertEquals("User has wrong number of authorities", 1, ssoDetails.getAuthorities().length);
        assertEquals("User has wrong authority", Role.STUDY_ADMIN, ssoDetails.getAuthorities()[0]);
    }
}

Add test for WebSSO "username" parser

Add test for WebSSO "username" parser


package net.sectorsoftware.ygo.deck;

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

import java.io.Closeable;
import java.io.IOException;
import java.lang.RuntimeException;
import java.util.List;

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

public class UserTest
{
    static {
        System.loadLibrary("ygodeck-jni");
    }

    static class User_Fixture implements Closeable
    {
        public User_Fixture()
        {
            DB.setPath(System.getenv("CARD_DB_PATH"));
        }

        @Override
        public void close() throws IOException
        {
        }

    }

    private User_Fixture fixture;

    @Before
    public void setup()
    {
        fixture = new User_Fixture();
    }

    @After
    public void tearDown() throws IOException
    {
        fixture.close();
        fixture = null;
    }

    @Test
    public void Create()
    {
        User user = new User("Test", true);
        assertEquals(user.name(), "Test");
        user.delete();
    }

    @Test
    public void Open()
    {
        User user = new User("OpenTest", true);
        user.delete();
        User user2 = new User("OpenTest");
        assertEquals(user2.name(), "OpenTest");
        user.delete();
    }

    @Test
    public void Unknown()
    {
        try {
            User user = new User("NotKnown");
            assertEquals(0, 1);
        } catch (RuntimeException e) {
            assertEquals(1, 1);
        }
    }

    @Test
    public void Remove()
    {
        User user = new User("RemoveTest", true);
        assertEquals(user.name(), "RemoveTest");
        user.remove();
        user.delete();
        try {
            User user2 = new User("RemoveTest");
            assertEquals(0, 1);
        } catch (RuntimeException e) {
            assertEquals(1, 1);
        }
    }

}

Add unit tests for java User binding

Add unit tests for java User binding


package cz.cuni.mff.d3s.spl.test;

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

import cz.cuni.mff.d3s.spl.core.data.Statistics;

@Ignore
public class TestUtils {

	public static void assertStatisticsEqual(Statistics a, Statistics b, double delta) {
		assertEquals(a.getArithmeticMean(), b.getArithmeticMean(), delta);
		assertEquals(a.getSampleCount(), b.getSampleCount());
	}
}

Add assertStatisticsEqual for easier testing


package fibonacci;

public class Fibonacci
{
  public static int fibonacci(int n)
  {
    if (n < 2)
      return n;

    return fibonacci(n - 1) + fibonacci(n - 2);
  }

  public static void main(String[] args)
  {
    if (args.length > 0)
    {
      try
      {
        int n = Integer.parseInt(args[0]);

        System.out.println(fibonacci(n));
      }
      catch (NumberFormatException e)
      {
        System.err.printf("Given argument (%s) is not a number!", args[0]);
      }
    }
  }
}

Implement simple recursice fibonacci method


package com.dev.namhoai.sort;

public class MergeSort {

    public static void sort(int[] a) {
        int[] helper = new int[a.length];
        sort(a, 0, a.length - 1, helper);

    }

    public static void sort(int[] a, int low, int high, int[] helper) {
        if (low >= high) {
            return;
        }
        int middle = low + (high - low) / 2;
        sort(a, low, middle, helper);
        sort(a, middle + 1, high, helper);
        merge(a, low, middle, high, helper);
    }

    public static void merge(int[] a, int low, int middle, int high, int[] helper) {
        for (int i = low; i <= high; i++) {
            helper[i] = a[i];
        }
        int i = low;
        int j = middle + 1;

        for (int k = low; k <= high; k++) {
            if (i > middle) {
                a[k] = helper[j++];
            } else if (j > high) {
                a[k] = helper[i++];
            } else if (helper[i] <= helper[j]) {
                a[k] = helper[i++];
            } else {
                a[k] = helper[j++];
            }
        }
    }
}

Add Merge Sort in Java

Add Merge Sort in Java


package org.ovirt.engine.core.common.businessentities;

import java.util.HashMap;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "QuotaEnforcmentTypeEnum")
public enum QuotaEnforcmentTypeEnum {
    DISABLED(0),
    SOFT_ENFORCEMENT(1),
    HARD_ENFORCEMENT(2);

    private final int enforcementType;
    private static java.util.HashMap<Integer, QuotaEnforcmentTypeEnum> mappings =
            new HashMap<Integer, QuotaEnforcmentTypeEnum>();

    static {
        for (QuotaEnforcmentTypeEnum component : values()) {
            mappings.put(component.getValue(), component);
        }
    }

    public int getValue() {
        return enforcementType;
    }

    public static QuotaEnforcmentTypeEnum forValue(int value) {
        return mappings.get(value);
    }

    private QuotaEnforcmentTypeEnum(int enforcementType) {
        this.enforcementType = enforcementType;
    }

    public int getQuotaEnforcementType() {
        return this.enforcementType;
    }
}

Add quota enforcement type enum.

ovirt-engine: Add quota enforcement type enum.

In the next patch I added the quota enforcement type enum.
The quota Enforcement type enum, should indicate if the storage pool is
enforcing the quota limitation or not.

Acked by:Omer Frenkel  <ofrenkel@redhat.com>

Change-Id: I39c78f64da8cee2ec8cedb1976aeae73d95276de


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

package com.pushtechnology.adapters.rest.metrics.events;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * Abstract implementation of {@link EventCounter}.
 *
 * @author Matt Champion 28/05/2017
 */
public abstract class AbstractEventCounter implements EventCounter {
    private final AtomicInteger requests = new AtomicInteger(0);
    private final AtomicInteger failures = new AtomicInteger(0);
    private final AtomicInteger successes = new AtomicInteger(0);

    @Override
    public int getRequests() {
        return requests.get();
    }

    @Override
    public int getSuccesses() {
        return successes.get();
    }

    @Override
    public int getFailures() {
        return failures.get();
    }

    /**
     * Increases the count of requests.
     */
    protected void onRequest() {
        requests.incrementAndGet();
    }

    /**
     * Increases the count of successes.
     */
    protected void onSuccess() {
        successes.incrementAndGet();
    }

    /**
     * Increases the count of failures.
     */
    protected void onFailure() {
        failures.incrementAndGet();
    }
}

Add an abstract implementation for counting events.


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

import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceTransformer;
import org.springframework.web.servlet.resource.ResourceTransformerChain;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

/**
 * A {@link org.springframework.web.servlet.resource.ResourceTransformer} that replaces the
 * //BLC-SERVLET-CONTEXT and //BLC-SITE-BASEURL" tokens before serving the BLC.js file.
 *
 * @since 4.0
 */
@Component("blBLCJsTranformer")
public class BLCJSResourceTransformer implements ResourceTransformer {

    @Override
    public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain)
            throws IOException {

        // TODO: Only resolve BLC.js

        return null;
    }

}

Check in template for BLC Js ResourceTransformer.


package net.restlesscoder.sandbox;

import java.util.function.Predicate;

public class EqualsPredicate {

	public static void main(final String... args) {
		// Why do we need Predicate.isEqual anyway?
		// Why not just use obj::equals?
		// Here's why!

		final Object obj = null;

		Predicate<Object> objEqualsSafe = Predicate.isEqual(obj);
		System.out.println(objEqualsSafe.test(null));

		Predicate<Object> objEquals = obj::equals;
		System.out.println(objEquals.test(null));
	}

}

Add illustration where Predicate.isEqual is useful


package jamex.common;

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

/**
 * Annotate a type or method as being an "entry point".
 *
 * Mainly used so that IDEA can identify dynamically accessed classes as
 * entry points and not mark them as unused.
 */
@Retention( RetentionPolicy.CLASS )
@Target( { ElementType.TYPE, ElementType.METHOD } )
public @interface EntryPoint
{
}

Add an annotation to mark types/methods as entry points


package org.monospark.spongematchers.parser.type;

import static org.hamcrest.CoreMatchers.not;
import static org.junit.Assert.assertThat;
import static org.monospark.spongematchers.testutil.HamcrestSpongeMatchers.matches;

import java.util.List;

import org.junit.Test;
import org.monospark.spongematchers.matcher.SpongeMatcher;
import org.monospark.spongematchers.parser.SpongeMatcherParseException;
import org.monospark.spongematchers.parser.element.StringElement;
import org.monospark.spongematchers.parser.element.StringElementParser;
import org.monospark.spongematchers.testutil.ExceptionChecker;

import com.google.common.collect.Lists;

public class ListTypeMatcher {

    @Test
    public void parseMatcher_NonListElement_ThrowsException() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("empty");
        ExceptionChecker.check(SpongeMatcherParseException.class,
                () -> MatcherType.list(MatcherType.BOOLEAN).parseMatcher(element));
    }

    @Test
    public void parseMatcher_ValidListElement_ReturnsCorrectSpongeMatcher() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("[true,false]");

        SpongeMatcher<List<Boolean>> matcher = MatcherType.list(MatcherType.BOOLEAN).parseMatcher(element);

        assertThat(matcher, matches(Lists.newArrayList(true, false)));
        assertThat(matcher, not(matches(Lists.newArrayList(false, true))));
    }

    @Test
    public void parseMatcher_ListMatchAnyElement_ReturnsCorrectSpongeMatcher() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("any:false");

        SpongeMatcher<List<Boolean>> matcher = MatcherType.list(MatcherType.BOOLEAN).parseMatcher(element);

        assertThat(matcher, matches(Lists.newArrayList(true, false)));
        assertThat(matcher, not(matches(Lists.newArrayList(true, true))));
    }

    @Test
    public void parseMatcher_ListMatchAllElement_ReturnsCorrectSpongeMatcher() throws SpongeMatcherParseException {
        StringElement element = StringElementParser.parseStringElement("all:false");

        SpongeMatcher<List<Boolean>> matcher = MatcherType.list(MatcherType.BOOLEAN).parseMatcher(element);

        assertThat(matcher, matches(Lists.newArrayList(false, false)));
        assertThat(matcher, not(matches(Lists.newArrayList(false, true))));
    }
}

Add unit tests for list matcher parsing

Add unit tests for list matcher parsing


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

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.groups.G;
import nom.bdezonia.zorbage.procedure.Ramp;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Group;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.storage.IndexedDataSource;
import nom.bdezonia.zorbage.type.storage.Storage;

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

	@Test
	public void test() {
		long size = 10000;
		Float64Member type = new Float64Member();
		IndexedDataSource<?, Float64Member> data = Storage.allocate(size, type);
		Ramp<Float64Group, Float64Member> rampProc = new Ramp<Float64Group, Float64Member>(G.DBL, new Float64Member(0.5), new Float64Member(3));
		Fill.compute(G.DBL, data, rampProc);
		assertEquals(size, data.size());
		for (long i = 0; i < size; i++) {
			data.get(i, type);
			assertEquals(0.5+3*i, type.v(), 0);
		}
	}
}

Define a test for Fill and Ramp

Define a test for Fill and Ramp


package beaform.dao;

import static org.junit.Assert.assertNotNull;

import org.junit.Test;

/**
 * Test for the GraphDbHandler.
 *
 * @author Steven Post
 *
 */
public class GraphDbHandlerTest {

	@Test(expected=IllegalStateException.class)
	public void testClearInstanceException() {
		GraphDbHandler.clearInstance();
	}

	@Test(expected=IllegalStateException.class)
	public void testGetInstanceException() {
		GraphDbHandler.getInstance();
	}

	@Test
	public void testGetInstance() {
		GraphDbHandler.initInstance("test");
		final GraphDbHandler handler = GraphDbHandler.getInstance();

		assertNotNull("The handler is null", handler);

		GraphDbHandler.clearInstance();
	}

}

Add some unit tests for the GraphDBHandler


package arez.component;

import javax.annotation.Nonnull;
import org.testng.annotations.Test;
import static org.testng.Assert.*;

public class IdentifiableTest
  extends AbstractArezComponentTest
{
  static class TestElement
    implements Identifiable<String>
  {
    @Nonnull
    @Override
    public String getArezId()
    {
      return "X";
    }
  }

  @Test
  public void identifiableElement()
  {
    final TestElement element = new TestElement();
    assertEquals( Identifiable.getArezId( element ), "X" );
    assertEquals( Identifiable.<String>asIdentifiable( element ), element );
  }

  @Test
  public void nonIdentifiableElement()
  {
    final Object element = new Object();
    assertNull( Identifiable.getArezId( element ) );
    final IllegalStateException exception =
      expectThrows( IllegalStateException.class, () -> Identifiable.asIdentifiable( element ) );
    assertEquals( exception.getMessage(),
                  "Object passed to asIdentifiable does not implement Identifiable. Object: " + element );
  }
}

Add minimal tests to Identifiable

Add minimal tests to Identifiable


package seedu.taskman.logic.logicmanager;

import org.junit.Test;
import seedu.taskman.logic.commands.CommandResult;
import seedu.taskman.logic.commands.TagsCommand;
import seedu.taskman.model.TaskMan;
import seedu.taskman.model.event.Event;
import seedu.taskman.model.event.Task;
import seedu.taskman.model.tag.Tag;

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

import static org.junit.Assert.assertTrue;

/**
 * Created by jiayee on 11/1/16.
 */
public class TagsTests extends LogicManagerTestBase {
    @Test
    public void execute_tags_emptyArgsFormat() throws Exception {
        // no args
        assertCommandNoStateChange("tags");

        logic.execute("clear");
        CommandResult result = logic.execute("tags");
        assertTrue(result.feedbackToUser.equals(TagsCommand.TAG_STRING_HEADER
                + TagsCommand.TAG_STRING_EMPTY_PLACEHOLDER));
        // this is similar to assertCommandBehaviour, will be bringing it back

        // TODO: Tidy up

        LogicManagerTestBase.TestDataHelper helper = new LogicManagerTestBase.TestDataHelper();
        Task toBeAdded = helper.generateFullTask(1);

        TaskMan expectedTaskMan = new TaskMan();
        expectedTaskMan.addActivity(toBeAdded); // expected

        List<Task> tasks = new ArrayList<>();
        tasks.add(toBeAdded);
        helper.addToModel(model, tasks); // actual

        result = logic.execute("tags");
        StringBuilder tags = new StringBuilder();
        for (Tag tag : toBeAdded.getTags()) {
            tags.append(tag);
            tags.append(" ");
        }
        assertTrue(result.feedbackToUser.equals(TagsCommand.TAG_STRING_HEADER
                + tags.toString().trim()));
    }
}

Add tests for tags command

Add tests for tags command


package io.github.droidkaigi.confsched2017.view.helper;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;

import timber.log.Timber;

public class IntentHelper {

    public static Intent buildActionViewIntent(@NonNull Context context, @NonNull String htmlUrl) {
        Timber.i("buildActionViewIntent: url: %s", htmlUrl);

        Uri uri = Uri.parse(htmlUrl);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);

        if (intent.resolveActivity(context.getPackageManager()) == null) {
            return null;
        }

        return intent;
    }
}

Add build action view intent in intent helper


package cz.scholz.aliaskeymanager;

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

import java.security.Security;

/**
 * Created by schojak on 31.5.16.
 */
public class AliasProviderTest {
    @Test
    public void testSetAlias()
    {
        AliasProvider.setAlias("myAlias");
        Assert.assertEquals(System.getProperty("cz.scholz.aliaskeymanager.alias"), "myAlias", "System property was not properly set");
        AliasProvider.unSetAlias();
        Assert.assertNotEquals(System.getProperty("cz.scholz.aliaskeymanager.alias"), "myAlias", "System property was not properly cleared");
    }

    @Test
    public void testEnableProvider()
    {
        AliasProvider.enable();
        Assert.assertNotNull(Security.getProvider("aliaskm"), "The provide doesn't seem to exist");

        AliasProvider.disable();
        Assert.assertNull(Security.getProvider("aliaskm"), "The provide doesn't seem to be disabled");
    }

    @Test
    public void testSetAsDefaultProvider()
    {
        AliasProvider.setAsDefault();
        Assert.assertEquals(Security.getProperty("ssl.KeyManagerFactory.algorithm"), "aliaskm", "The new key manager has been set as default");

        AliasProvider.unsetAsDefault();
        Assert.assertNotEquals(Security.getProperty("ssl.KeyManagerFactory.algorithm"), "aliaskm", "The new key manager is still the default");
    }
}

Add tests for the AliasProvider

Add tests for the AliasProvider


/*
 * Copyright 2016 Attribyte, 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.attribyte.wp.model;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;

/**
 * A post that represents an image attachment.
 */
public class ImageAttachment extends Post {

   /**
    * Creates an image attachment with unassigned id.
    * @param parent The parent post.
    * @param path The image path.
    * @param slug The image slug.
    * @param mimeType The associated mime type.
    */
   public ImageAttachment(final Post parent, final String path, final String slug, final String mimeType) {
      this(parent, 0L, path, slug, mimeType);
   }

   /**
    * Creates an image attachment with assigned id.
    * @param parent The parent post.
    * @param id The id.
    * @param path The image path.
    * @param slug The image slug.
    * @param mimeType The associated mime type.
    */
   public ImageAttachment(final Post parent, final long id, final String path, final String slug, final String mimeType) {
      super(id, slug, slug, "", "", parent.authorId, parent.author, parent.publishTimestamp, parent.publishTimestamp,
              parent.status, parent.id, path, 0, ImmutableList.of(), Type.ATTACHMENT, mimeType,
              ImmutableMap.of(), ImmutableList.of());
   }
}

Add derived post for image attachment.

Add derived post for image attachment.


package com.novoda.sqlite.impl;

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

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

public class SQLFileTest {
    private final static String STATEMENT_CREATE_TABLE = "CREATE TABLE banana(_id INTEGER);";
    private final static String STATEMENT_ALTER_TABLE = "ALTER TABLE banana ADD COLUMN colour TEXT;";
    private final static String NEW_LINE = "\n";
    private final static String SPACE = " ";
    private final static String LINE_COMMENT = "-- this is a line comment";
    private final static String[] EXPECTED_STATEMENTS = new String[]{STATEMENT_CREATE_TABLE, STATEMENT_ALTER_TABLE};
    private static final String BLOCK_COMMENT = "/* this is a \n block comment \n spanning over \n multiple lines */";

    @Test
    public void givenSQLFile_whenParseAndGetStatements_thenGetCorrectStatements() throws IOException {
        SQLFile file = givenSQLFileParsedFromString(STATEMENT_CREATE_TABLE + NEW_LINE + STATEMENT_ALTER_TABLE);

        String[] actual = getStatementsFromFile(file);

        Assert.assertArrayEquals(actual, EXPECTED_STATEMENTS);
    }

    @Test
    public void givenSQLFileWithSpaces_whenParseAndGetStatements_thenGetCorrectTrimmedStatements() throws IOException {
        SQLFile file = givenSQLFileParsedFromString(SPACE + STATEMENT_CREATE_TABLE + SPACE + NEW_LINE + SPACE + STATEMENT_ALTER_TABLE + SPACE);

        String[] actual = getStatementsFromFile(file);

        Assert.assertArrayEquals(actual, EXPECTED_STATEMENTS);
    }

    @Test
    public void givenSQLFileWithLineComments_whenParseAndGetStatements_thenIgnoreComments() throws IOException {
        SQLFile file = givenSQLFileParsedFromString(
                STATEMENT_CREATE_TABLE + SPACE + LINE_COMMENT + NEW_LINE + STATEMENT_ALTER_TABLE + SPACE + LINE_COMMENT);

        String[] actual = getStatementsFromFile(file);

        Assert.assertArrayEquals(actual, EXPECTED_STATEMENTS);
    }

    @Test
    public void givenSQLFileWithBlockComments_whenParseAndGetStatements_thenIgnoreComments() throws IOException {
        SQLFile file = givenSQLFileParsedFromString(
                STATEMENT_CREATE_TABLE + NEW_LINE + BLOCK_COMMENT + NEW_LINE + STATEMENT_ALTER_TABLE);

        String[] actual = getStatementsFromFile(file);

        Assert.assertArrayEquals(actual, EXPECTED_STATEMENTS);
    }

    private SQLFile givenSQLFileParsedFromString(String sql) throws IOException {
        SQLFile file = new SQLFile();
        file.parse(new StringReader(sql));
        return file;
    }

    private String[] getStatementsFromFile(SQLFile file) {
        List<String> statements = file.getStatements();
        return statements.toArray(new String[statements.size()]);
    }
}

Test SQLFile with all the possible (handled) use cases


package org.realityforge.arez;

import java.util.ArrayList;
import javax.annotation.Nonnull;
import static org.testng.Assert.*;

final class TestReaction
  implements Reaction
{
  private final ArrayList<Observer> _observers = new ArrayList<>();

  @Override
  public void react( @Nonnull final Observer observer )
    throws Exception
  {
    observer.getDependencies().forEach( Observable::reportObserved );
    _observers.add( observer );
  }

  void assertObserver( final int index, @Nonnull final Observer observer )
  {
    assertTrue( _observers.size() > index );
    assertEquals( _observers.get( index ), observer );
  }

  int getCallCount()
  {
    return _observers.size();
  }
}

Add reaction useful during testing

Add reaction useful during testing


package leetcode.construct_binary_tree_from_inorder_and_postorder_traversal;

import common.TreeNode;

public class Solution {
	public TreeNode buildTree(int[] inorder, int[] postorder, int in_from, int in_to, int post_from, int post_to){
		if(in_from == in_to || post_from == post_to) return null;
		int rootval = postorder[post_to - 1];
		TreeNode root = new TreeNode(rootval);
		int rootidx;
		for(rootidx = in_from; rootidx < in_to && inorder[rootidx] != rootval; rootidx++);
		root.left = buildTree(inorder, postorder, in_from, rootidx, post_from, post_from + (rootidx - in_from));
		root.right = buildTree(inorder, postorder, rootidx + 1, in_to, post_to - (in_to - rootidx), post_to - 1);
		return root;
	}
    public TreeNode buildTree(int[] inorder, int[] postorder) {
    	if(inorder == null || postorder == null) return null;
    	return buildTree(inorder, postorder, 0, inorder.length, 0, postorder.length);
    }

    public static void inOrder(TreeNode cur){
    	if(cur != null){
    		inOrder(cur.left);
    		System.err.print(cur.val + "->");
    		inOrder(cur.right);
    	}
    }

    public static void postOrder(TreeNode cur){
    	if(cur != null){
    		postOrder(cur.left);
    		postOrder(cur.right);
    		System.err.print(cur.val + "->");
    	}
    }

    public static void main(String[] args){
    	int[] inorder = new int[]{4, 9, 5, 1, 8, 3, 7, 6};
    	int[] postorder = new int[]{9, 4, 5, 8, 7, 6, 3, 1};
    	TreeNode ret = new Solution().buildTree(inorder, postorder);
    	inOrder(ret);
    	System.err.println("");
    	postOrder(ret);
    	System.err.println("");
    }
}

Add java solution for 106. Construct Binary Tree from Inorder and Postorder Traversal

106. Construct Binary Tree from Inorder and Postorder Traversal: https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/


package org.egorlitvinenko.other;

import java.nio.ByteBuffer;

/**
 *
 * https://docs.oracle.com/javase/specs/jls/se11/html/jls-3.html#jls-3.10.1
 * https://docs.oracle.com/javase/specs/jls/se11/html/jls-4.html#jls-4.2.1
 * https://docs.oracle.com/javase/specs/jvms/se11/html/jvms-2.html#jvms-2.11.1
 *
 * **/
public class ByteCoercion {

    public static void main(String[] args) {
        byte a = -83;
        int b = a;
        byte c = (byte) b;
//        int d = 0x800000CD;
        int d = 0x8000004D;
        byte e = (byte) d;
        System.out.println("a = " + a);
        System.out.println("b = " + b);
        System.out.println("c = " + c);
        System.out.println("b as binary: " + Integer.toBinaryString(b));
        System.out.println("b as bytes:"); print(intToByteArray(b));
        System.out.println("b as bytesBB:"); print(intToByteArrayBB(b));
        System.out.println("d = " + d);
        System.out.println("e = " + e);
        System.out.println("d as binary: " + Integer.toBinaryString(d));
        System.out.println("d as bytes:"); print(intToByteArray(d));
        System.out.println("d as bytesBB:"); print(intToByteArrayBB(d));
    }

    private static void print(byte[] array) {
        StringBuilder sb = new StringBuilder();
        sb.append("array=(");
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]).append(",");
        }
        sb.deleteCharAt(sb.length() - 1).append(")");
        System.out.println(sb);
    }

    private static byte[] intToByteArray(int a) {
        byte[] result = new byte[4];
        result[0] = (byte) (a & 0x000000FF);
        result[1] = (byte) ((a & 0x0000FF00) >> 8);
        result[2] = (byte) ((a & 0x00FF0000) >> 16);
        result[3] = (byte) ((a & 0xFF000000) >> 24);
        return result;
    }

    private static byte[] intToByteArrayBB(int a) {
        ByteBuffer bb = ByteBuffer.allocate(4);
        bb.putInt(a);
        return bb.array();
    }
}

Add example with byte int manipulations

Add example with byte int manipulations


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

/**
 * Class model class for Class table.
 *
 * @author Ryan Gilera
 */
public class Class {

    private final int id;
    private final String moduleId;
    private final String moduleName;

    public Class(int id, String moduleId, String moduleName) {
        this.id = id;
        this.moduleId = moduleId;
        this.moduleName = moduleName;
    }

    public int getId() {
        return id;
    }

    public String getModuleId() {
        return moduleId;
    }

    public String getModuleName() {
        return moduleName;
    }

}

Add a model for class table

Add a model for class table


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

/**
 * Given two integers passed as argument, can you implement the subtract operator using just "+" as
 * arithmetic operator?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class SubtractAdding {

}

Add statement to problem 73

Add statement to problem 73


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

/* $Id$ */

package org.apache.fop.render.ps;

import java.util.List;

import org.apache.fop.render.gradient.Function;
import org.apache.fop.render.gradient.Function.SubFunctionRenderer;
import org.apache.fop.render.gradient.GradientMaker.DoubleFormatter;
import org.apache.fop.render.gradient.Pattern;
import org.apache.fop.render.gradient.Shading;

/**
 * Helper class to draw gradients in PostScript.
 */
public final class Gradient {

    private Gradient() { }

    public static String outputPattern(Pattern pattern, DoubleFormatter doubleFormatter) {
        StringBuilder p = new StringBuilder(64);
        p.append("/Pattern setcolorspace\n");
        p.append("<< \n/Type /Pattern \n");

        p.append("/PatternType " + pattern.getPatternType() + " \n");

        if (pattern.getShading() != null) {
            p.append("/Shading ");
            outputShading(p, pattern.getShading(), doubleFormatter);
            p.append(" \n");
        }
        p.append(">> \n");
        List<Double> matrix = pattern.getMatrix();
        if (matrix == null) {
            p.append("matrix ");
        } else {
            p.append("[ ");
            for (double m : pattern.getMatrix()) {
                p.append(doubleFormatter.formatDouble(m));
                p.append(" ");
            }
            p.append("] ");
        }
        p.append("makepattern setcolor\n");

        return p.toString();
    }

    private static void outputShading(StringBuilder out, Shading shading, final DoubleFormatter doubleFormatter) {
        final Function function = shading.getFunction();
        Shading.FunctionRenderer functionRenderer = new Shading.FunctionRenderer() {

            public void outputFunction(StringBuilder out) {
                SubFunctionRenderer subFunctionRenderer = new Function.SubFunctionRenderer() {

                    public void outputFunction(StringBuilder out, int functionIndex) {
                        Function subFunction = function.getFunctions().get(functionIndex);
                        assert subFunction.getFunctions().isEmpty();
                        subFunction.output(out, doubleFormatter, null);
                    }
                };
                function.output(out, doubleFormatter, subFunctionRenderer);
            }
        };
        shading.output(out, doubleFormatter, functionRenderer);
    }

}

Support PDF shading to PS

FOP-2553: Support PDF shading to PS

git-svn-id: 102839466c3b40dd9c7e25c0a1a6d26afc40150a@1724037 13f79535-47bb-0310-9956-ffa450edef68


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

package net.imagej.ops;

/**
 * Interface for objects which can be initialized.
 *
 * @author Curtis Rueden
 */
public interface Initializable {

	/** Initializes the object. */
	void initialize();

}

Add interface for things which can be initialized

In the future, this will move to SciJava Common.


// 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 user data for ranking purposes only
 */
@AutoValue
public abstract class BasicCompetitor {
  public static BasicCompetitor create(long userId, long netWorth, int rankYesterday) {
    return new AutoValue_BasicCompetitor(userId, netWorth, rankYesterday);
  }
  /** The id of the competitor */
  public abstract long userId();
  /** The networth of the competitor */
  public abstract long netWorth();
  /** The user's rank yesterday */
  public abstract int rankYesterday();
}

Add basic object for ranking purposes

Add basic object for ranking purposes


package com.andreistraut.gaps.datamodel.translator;

import com.andreistraut.gaps.datamodel.genetics.EdgeGene;
import com.andreistraut.gaps.datamodel.genetics.GeneticConfiguration;
import com.andreistraut.gaps.datamodel.genetics.PathChromosome;
import com.andreistraut.gaps.datamodel.graph.DirectedWeightedEdge;
import com.andreistraut.gaps.datamodel.graph.Node;
import java.util.ArrayList;
import org.jgrapht.GraphPath;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;

public class GraphGeneticsTranslatorTest {

    public GraphGeneticsTranslatorTest() {
    }

    @Before
    public void setUp() {
    }

    @Test
    public void testToPathChromosome() throws Exception {
	System.out.println("toPathChromosome");
	GraphPath<Node, DirectedWeightedEdge> path = null;
	GeneticConfiguration configuration = null;
	PathChromosome expResult = null;
	PathChromosome result = GraphGeneticsTranslator.toPathChromosome(path, configuration);
	assertEquals(expResult, result);
	// TODO review the generated test code and remove the default call to fail.
	fail("The test case is a prototype.");
    }

    @Test
    public void testToEdgeGeneList() throws Exception {
	System.out.println("toEdgeGeneList");
	GraphPath<Node, DirectedWeightedEdge> edgeList = null;
	GeneticConfiguration configuration = null;
	ArrayList<EdgeGene> expResult = null;
	ArrayList<EdgeGene> result = GraphGeneticsTranslator.toEdgeGeneList(edgeList, configuration);
	assertEquals(expResult, result);
	// TODO review the generated test code and remove the default call to fail.
	fail("The test case is a prototype.");
    }

}

Add new unit test class stub

Add new unit test class stub


package org.cipres.treebase.domain.nexus;

import junit.framework.Assert;

import org.cipres.treebase.dao.AbstractDAOTest;
import org.cipres.treebase.domain.matrix.CharacterMatrix;
import org.cipres.treebase.domain.nexus.nexml.NexmlMatrixConverter;
import org.cipres.treebase.domain.nexus.NexusDataSet;
import org.cipres.treebase.domain.study.Study;
import org.cipres.treebase.domain.taxon.TaxonLabelHome;
import org.nexml.model.DocumentFactory;
import org.nexml.model.Document;

public class NexmlMatrixConverterTest extends AbstractDAOTest {
	private TaxonLabelHome mTaxonLabelHome;

	/**
	 * Test  for {@link org.cipres.treebase.domain.nexus.nexml.NexmlMatrixConverter#fromTreeBaseToXml(CharacterMatrix)}.
	 */
	public void testNexmlMatrixConverter() {
		String testName = "testNexmlMatrixConverter";
		//signal beginning of test
		if (logger.isInfoEnabled()) {
			logger.info("\n\t\tRunning Test: " + testName);
		}

		long studyId = 1787;
		Study study = (Study)loadObject(Study.class, studyId);
		NexusDataSet nexusDataSet = new NexusDataSet();

		Document doc = DocumentFactory.safeCreateDocument();
		nexusDataSet.setNexmlProject(doc);
		NexmlMatrixConverter nmc = new NexmlMatrixConverter(study,getTaxonLabelHome(),doc);
		for (org.cipres.treebase.domain.matrix.Matrix matrix : nexusDataSet.getMatrices() ) {
			if ( matrix instanceof CharacterMatrix ) {
				//fromTreeBaseToXml(CharacterMatrix) is main method being tested here--it uses populateXmlMatrix() function
				String xml = ((Document) nmc.fromTreeBaseToXml((CharacterMatrix)matrix)).getXmlString();
				System.out.println(xml);
				Assert.assertNotNull(xml);
			}
		}
		//signal that test is over
		if (logger.isInfoEnabled()) {
			logger.info(testName + " - end ");
		}
	}

	/**
	 * Return the TaxonLabelHome field.
	 *
	 * @return TaxonLabelHome mTaxonLabelHome
	 */
	public TaxonLabelHome getTaxonLabelHome() {
		return mTaxonLabelHome;
	}

	/**
	 * Set the TaxonLabelHome field.
	 */
	public void setTaxonLabelHome(TaxonLabelHome pNewTaxonLabelHome) {
		mTaxonLabelHome = pNewTaxonLabelHome;
	}

}

Test for NexmlMatrixConverter class for function fromTreeBaseToXml(CharacterMatrix). This is the function that calls the poplulateXmlMatrix() function


/**
 * Copyright 2013 DuraSpace, 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.fcrepo.jcr;

/**
 * FIXME: This class should be removed once the dependency management function that the pom.xml found in the fcrepo-jcr
 * module serves has been satisfied in some other way.
 * See: https://www.pivotaltracker.com/story/show/68680222
 *
 * @author Andrew Woods
 *         Date: 4/1/14
 */
public class Empty {
}

Add placeholder java class to fcrepo-jcr

Resolves: https://www.pivotaltracker.com/story/show/68682794


// Copyright 2014 Tool Inc.

package com.tool.emailbot.application.command;

import com.tool.emailbot.common.application.command.Command;

import java.util.Date;

/**
 * Command that specifies that a new email request should be created.
 *
 * @author Jovani Rico (jovanimtzrico@gmail.com)
 */
public class RegisterEmailCommand implements Command {

    private String name;
    private String fatherLastName;
    private String motherLastName;
    private Date fechaNacimiento;
    private String homoclave;
    private String numeroTrabajador;
    private String email;
    private String telephone;
    private String username;

    public RegisterEmailCommand(String name, String fatherLastName, String motherLastName,
            Date fechaNacimiento, String homoclave, String numeroTrabajador, String email,
            String telephone, String username) {
        this.name = name;
        this.fatherLastName = fatherLastName;
        this.motherLastName = motherLastName;
        this.fechaNacimiento = fechaNacimiento;
        this.homoclave = homoclave;
        this.numeroTrabajador = numeroTrabajador;
        this.email = email;
        this.telephone = telephone;
        this.username = username;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getFatherLastName() {
        return fatherLastName;
    }

    public void setFatherLastName(String fatherLastName) {
        this.fatherLastName = fatherLastName;
    }

    public String getMotherLastName() {
        return motherLastName;
    }

    public void setMotherLastName(String motherLastName) {
        this.motherLastName = motherLastName;
    }

    public Date getFechaNacimiento() {
        return fechaNacimiento;
    }

    public void setFechaNacimiento(Date fechaNacimiento) {
        this.fechaNacimiento = fechaNacimiento;
    }

    public String getHomoclave() {
        return homoclave;
    }

    public void setHomoclave(String homoclave) {
        this.homoclave = homoclave;
    }

    public String getNumeroTrabajador() {
        return numeroTrabajador;
    }

    public void setNumeroTrabajador(String numeroTrabajador) {
        this.numeroTrabajador = numeroTrabajador;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getTelephone() {
        return telephone;
    }

    public void setTelephone(String telephone) {
        this.telephone = telephone;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

Define a new command to register an email request


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

import static java.lang.invoke.MethodHandles.lookup;
import static org.slf4j.LoggerFactory.getLogger;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.slf4j.Logger;

public class TestRuleChain {

    static final Logger log = getLogger(lookup().lookupClass());

    @Rule
    public TestRule chain = RuleChain.outerRule(new BasicRule("outer"))
            .around(new BasicRule("middle")).around(new BasicRule("inner"));

    @BeforeClass
    public static void beforeclass() {
        log.debug("@BeforeClass");
    }

    @Before
    public void before() {
        log.debug("@Before");
    }

    @Test
    public void test() {
        log.debug("@Test");
    }

    @AfterClass
    public static void afterclass() {
        log.debug("@AfterClass");
    }

    @After
    public void after() {
        log.debug("@After");
    }

    private static class BasicRule implements TestRule {

        private String name;

        public BasicRule(String name) {
            this.name = name;
        }

        public Statement apply(final Statement base,
                final Description description) {
            log.debug("Rule {} applied", name);
            return base;
        }

    }

}

Include test using JUnit 4's RuleChain

Include test using JUnit 4's RuleChain


package com.woorea.openstack.examples.compute;

import com.woorea.openstack.examples.ExamplesConfiguration;
import com.woorea.openstack.keystone.Keystone;
import com.woorea.openstack.keystone.model.Access;
import com.woorea.openstack.keystone.model.authentication.UsernamePassword;
import com.woorea.openstack.nova.Nova;
import com.woorea.openstack.nova.api.ServersResource;
import com.woorea.openstack.nova.model.Servers;

public class NovaStopStartServer {
    public static void main(String[] args) throws InterruptedException {
        Keystone keystone = new Keystone(ExamplesConfiguration.KEYSTONE_AUTH_URL);
        Access access = keystone.tokens().authenticate(new UsernamePassword(ExamplesConfiguration.KEYSTONE_USERNAME, ExamplesConfiguration.KEYSTONE_PASSWORD))
                .withTenantName(ExamplesConfiguration.TENANT_NAME)
                .execute();

        //use the token in the following requests
        keystone.token(access.getToken().getId());

        Nova novaClient = new Nova(ExamplesConfiguration.NOVA_ENDPOINT.concat("/").concat(access.getToken().getTenant().getId()));
        novaClient.token(access.getToken().getId());

        Servers servers = novaClient.servers().list(true).execute();
        if(servers.getList().size() > 0) {

            ServersResource.StopServer stopServer = novaClient.servers().stop(servers.getList().get(0).getId());
            stopServer.endpoint(ExamplesConfiguration.NOVA_ENDPOINT);
            stopServer.execute();

            // Wait until server shutdown.
            Thread.sleep(5000);

            ServersResource.StartServer startServer = novaClient.servers().start(servers.getList().get(0).getId());
            startServer.endpoint(ExamplesConfiguration.NOVA_ENDPOINT);
            startServer.execute();
        }
    }
}

Add Stop and Start Nova Compute Server Example. Implemented example code of shutdown and srart nova compute server(instance).


package com.google.sps.authentication;

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

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.FilterOperator;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.sps.firebase.FirebaseAppManager;
import com.google.appengine.api.datastore.Query.FilterPredicate;

public class Authenticator {
  private FirebaseAuth auth;
  private DatastoreService datastore;

  public Authenticator() throws IOException {
    this(FirebaseAuth.getInstance(FirebaseAppManager.getApp()));
  }

  protected Authenticator(FirebaseAuth auth) {
    this.auth = Objects.requireNonNull(auth);
    datastore = DatastoreServiceFactory.getDatastoreService();
  }

  public boolean verifyTaOrOwner(String idToken, Key classKey) {
    try {
      FirebaseToken tok = auth.verifyIdToken(idToken);
      PreparedQuery q = datastore.prepare(new Query("User").setFilter(
        new FilterPredicate("userEmail", FilterOperator.EQUAL, tok.getEmail())
      ));

      if(q.countEntities(FetchOptions.Builder.withLimit(1)) > 0) {
        return ((List<Key>) q.asSingleEntity().getProperty("taClasses")).contains(classKey) ||
               ((List<Key>) q.asSingleEntity().getProperty("ownedClasses")).contains(classKey);
      } else {
        return false;
      }
    } catch (FirebaseAuthException | IllegalArgumentException e) {
      return false;
    }

  }
}

Add authenticator class to handle servlet authentication.


import org.realityforge.arez.annotations.Container;
import org.realityforge.arez.annotations.Observable;

@Container
public class BasicObservableModel
{
  private long _time;

  @Observable
  public long getTime()
  {
    return _time;
  }

  @Observable
  public void setTime( final long time )
  {
    _time = time;
  }
}

Add another future test data point

Add another future test data point


/*
* 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.tomcat.buildutil.translate;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Generates a set of English property files to back-port updates to a previous
 * version. Where a key exists in the source and target versions the value is
 * copied from the source to the target, overwriting the value in the target.
 * The expectation is that the changes will be manually reviewed before
 * committing them.
 */
public class BackportEnglish {

    private static final Map<String,Properties> sourceTranslations = new HashMap<>();
    private static final Map<String,Properties> targetTranslations = new HashMap<>();

    public static void main(String... args) throws IOException {
        if (args.length != 1) {
            throw new IllegalArgumentException("Missing back-port target");
        }
        File targetRoot = new File(args[0]);

        if (!targetRoot.isDirectory()) {
            throw new IllegalArgumentException("Back-port target not a directory");
        }

        File sourceRoot = new File(".");
        for (String dir : Constants.SEARCH_DIRS) {
            File directory = new File(dir);
            Utils.processDirectory(sourceRoot, directory, sourceTranslations);
        }

        for (String dir : Constants.SEARCH_DIRS) {
            File directory = new File(targetRoot, dir);
            Utils.processDirectory(targetRoot, directory, targetTranslations);
        }

        Properties sourceEnglish = sourceTranslations.get("");
        Properties targetEnglish = targetTranslations.get("");

        for (Object key : sourceEnglish.keySet()) {
            if (targetEnglish.containsKey(key)) {
                targetEnglish.put(key, sourceEnglish.get(key));
            }
        }

        File storageDir = new File(targetRoot, Constants.STORAGE_DIR);

        Utils.export("", targetEnglish, storageDir);
    }
}

Add a tool for back-porting English translations


package openmods.liquids;

import javax.annotation.Nullable;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fluids.Fluid;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import net.minecraftforge.fluids.capability.FluidTankProperties;
import net.minecraftforge.fluids.capability.IFluidHandler;
import net.minecraftforge.fluids.capability.IFluidTankProperties;

public class SingleFluidBucketHandler implements IFluidHandler {

	private final ItemStack container;

	private final int volume;

	private final Fluid fluid;

	private final ItemStack emptyContainer;

	private final FluidStack contents;

	private final IFluidTankProperties properties;

	public SingleFluidBucketHandler(ItemStack container, String fluidId, int volume, ItemStack emptyContainer) {
		this.container = container;
		this.fluid = FluidRegistry.getFluid(fluidId);
		this.volume = volume;
		this.emptyContainer = emptyContainer.copy();

		this.contents = new FluidStack(fluid, volume);
		this.properties = new FluidTankProperties(contents, volume);
	}

	@Override
	public IFluidTankProperties[] getTankProperties() {
		return new IFluidTankProperties[] { properties };
	}

	@Override
	public int fill(FluidStack resource, boolean doFill) {
		return 0;
	}

	protected void switchToEmptyBucket() {
		container.deserializeNBT(emptyContainer.serializeNBT());
	}

	@Override
	@Nullable
	public FluidStack drain(FluidStack resource, boolean doDrain) {
		if (container.stackSize != 1 || resource == null || resource.amount < volume)
			return null;

		if (resource.getFluid() == fluid)
			if (doDrain)
				switchToEmptyBucket();

		return contents;
	}

	@Override
	@Nullable
	public FluidStack drain(int maxDrain, boolean doDrain) {
		if (container.stackSize != 1 || maxDrain < Fluid.BUCKET_VOLUME)
			return null;

		if (doDrain)
			switchToEmptyBucket();

		return contents;
	}

}

Add IFluidHandler for simple bucket items


package online.pizzacrust.lukkitplus;

import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;

import online.pizzacrust.lukkitplus.api.LuaPlugin;
import online.pizzacrust.lukkitplus.environment.Environment;

public class CommandPluginList implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) {
        if (command.getName().equals("plugins")) {
            if (!commandSender.hasPermission("lukkitplus.listpl")) {
                commandSender.sendMessage(ChatColor.RED + "Sorry, you don't have permission.");
                return true;
            }
            StringBuilder pluginSentence = new StringBuilder();
            int index = 0;
            for (LuaPlugin plugin : Environment.PLUGINS) {
                if (index != (Environment.PLUGINS.size() - 1)) {
                    pluginSentence.append(plugin.getName() + ", ");
                } else {
                    pluginSentence.append(plugin.getName() + "");
                }
                index++;
            }
            commandSender.sendMessage("Plugins: " + ChatColor.GREEN + pluginSentence.toString());
            return true;
        }
        return false;
    }
}

Make the plugin list command

Make the plugin list command


package de.teiesti.postie;

import org.pmw.tinylog.Logger;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Set;

public class Office {

	private ServerSocket serverSocket;

	private Postman blueprint;

	private Set<Postman> postmen;

	private Thread acceptor;

	public Office bind(ServerSocket socket) {
		// FIXME
		return this;
	}

	public Office spawn(Postman blueprint) {
		// FIXME
		return this;
	}

	public Office start() {
		acceptor = new Acceptor();
		acceptor.start();

		return this;
	}

	public Office stop() {
		// FIXME how to do this?
		return this;
	}

	private class Acceptor extends Thread {

	 	@Override
		public void run() {
			Socket socket;
			Postman postman;
			while (!isInterrupted()) {
				try {
					socket = serverSocket.accept();
					postman = blueprint.clone().bind(socket).start();
					postmen.add(postman);
				} catch (IOException e) {
					Logger.error(e);
					System.exit(1);
				}
			}

		}

	}

}

Revert "Prepare for the 0.2.0 release."

Revert "Prepare for the 0.2.0 release."

This reverts commit d8b8f6edd066bc929b8438ed03703babd856907e.


package guitests;

//@@author A0125221Y
import static org.junit.Assert.assertTrue;

import org.junit.Test;

import seedu.address.testutil.TestTask;
import seedu.address.testutil.TestUtil;

public class UndoCommandTest extends AddressBookGuiTest{

	@Test
	public void undoWithOneModification_Success(){

		TestTask[] currentList = td.getTypicalTasks();

		//Begin by adding one task
		TestTask taskToAdd = td.hoon;
		commandBox.runCommand(taskToAdd.getAddCommand());
		assertListSize(currentList.length + 1);

		//Next undo the previous add command
		commandBox.runCommand("undo");
		assertListSize(currentList.length);
		assertTrue(taskListPanel.isListMatching(currentList));

		//Now test deletion of one single task
		commandBox.runCommand("delete 1");
		assertListSize(currentList.length - 1);
		currentList = TestUtil.removeTaskFromList(currentList, 1);

		//Try to undo the previous delete command
		commandBox.runCommand("undo");
		currentList = TestUtil.addTasksToListAtIndex(currentList, 0, td.alice);
		assertListSize(currentList.length);
		assertTrue(taskListPanel.isListMatching(currentList));

	}

}

Test cases for Undo Command

Test cases for Undo Command


package week_of_code_30;

import java.util.Scanner;

public class FindTheMinimumNumber {

  private static String findMin(int n) {
    return findMin(0, n);
  }

  private static String findMin(int i, int n) {
    StringBuilder builder = new StringBuilder();
    if (i == n - 1) {
      return "int";
    } else {
      builder.append("min(int, ").append(findMin(i + 1, n)).append(")");
      return builder.toString();
    }
  }

  public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    System.out.println(findMin(n));
    in.close();
  }
}

Add solution for another Easy problem week of code 30


package com.nexmo.quickstart.voice;

import com.nexmo.client.NexmoClient;
import com.nexmo.client.auth.AuthMethod;
import com.nexmo.client.auth.JWTAuthMethod;
import com.nexmo.client.voice.Call;
import com.nexmo.client.voice.CallEvent;

import java.nio.file.FileSystems;

import static com.nexmo.quickstart.Util.configureLogging;
import static com.nexmo.quickstart.Util.envVar;

public class SendTalkToCall {
    public static void main(String[] args) throws Exception {
        configureLogging();

        String APPLICATION_ID = envVar("APPLICATION_ID");
        String PRIVATE_KEY = envVar("PRIVATE_KEY");
        String FROM_NUMBER = envVar("FROM_NUMBER");
        String TO_NUMBER = envVar("TO_NUMBER");

        AuthMethod auth = new JWTAuthMethod(
                APPLICATION_ID,
                FileSystems.getDefault().getPath(PRIVATE_KEY)
        );
        NexmoClient client = new NexmoClient(auth);
        CallEvent call = client.getVoiceClient().createCall(new Call(
                TO_NUMBER,
                FROM_NUMBER,
                "https://gist.githubusercontent.com/ChrisGuzman/d6add5b23a8cf913dcdc5a8eabc223ef/raw/a1eb52e0ce2d3cef98bab14d27f3adcdff2af881/long_talk.json"
        ));

        Thread.sleep(20000);

        client.getVoiceClient().startTalk(call.getUuid(), "Hello World! Would you like to know more? I bet you would", 0);
        Thread.sleep(5000);
        client.getVoiceClient().stopTalk(call.getUuid());
    }
}

Add Talk example for Voice API

Add Talk example for Voice API


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

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import nom.bdezonia.zorbage.algebras.G;
import nom.bdezonia.zorbage.type.data.float64.real.Float64Member;
import nom.bdezonia.zorbage.type.storage.array.ArrayStorage;
import nom.bdezonia.zorbage.type.storage.datasource.IndexedDataSource;

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

	@Test
	public void test1() {

		Float64Member value = G.DBL.construct();

		IndexedDataSource<Float64Member> nums = ArrayStorage.allocateDoubles(
				new double[] {1,Double.NaN, 2, 3, Double.NaN, Double.NaN, 4, Double.NaN, Double.NaN, Double.NaN});

		IndexedDataSource<Float64Member> nonnan = NonNanValues.compute(G.DBL, nums);

		assertEquals(10, nums.size());
		assertEquals(4, nonnan.size());
		nonnan.get(0, value);
		assertEquals(1, value.v(), 0);
		nonnan.get(1, value);
		assertEquals(2, value.v(), 0);
		nonnan.get(2, value);
		assertEquals(3, value.v(), 0);
		nonnan.get(3, value);
		assertEquals(4, value.v(), 0);
	}
}

Define a test for the NonNanValues algorithm


/*
 * 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.harmony.text.tests.java.text;

import java.text.DateFormat;
import java.text.ParseException;

@SuppressWarnings("nls")
public class ParseExceptionTest extends junit.framework.TestCase {

    /**
     * @tests java.text.ParseException#ParseException(java.lang.String, int)
     */
    public void test_ConstructorLjava_lang_StringI() {
        try {
            DateFormat df = DateFormat.getInstance();
            df.parse("HelloWorld");
            fail("ParseException not created/thrown.");
        } catch (ParseException e) {
            // expected
        }
    }

    /**
     * @tests java.text.ParseException#getErrorOffset()
     */
    public void test_getErrorOffset() {
        try {
            DateFormat df = DateFormat.getInstance();
            df.parse("1999HelloWorld");
        } catch (ParseException e) {
            assertEquals("getErrorOffsetFailed.", 4, e.getErrorOffset());
        }
    }
}

Test case tidy-up, no functional changes.

svn path=/harmony/; revision=810963


package com.genymobile.pr.bus;

import com.genymobile.pr.model.Issue;

public class IssueRetrievedEvent {

    public IssueRetrievedEvent(Issue issue) {
        this.issue = issue;
    }

    private Issue issue;

    public Issue getIssue() {
        return issue;
    }
}

Add the event for the IssueRetrieved

Add the event for the IssueRetrieved


package net.craftstars.general.money;

import net.craftstars.general.General;

import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

public class iConomyEconomyHandler implements EconomyBase {
	EconomyBase actualEconomy;
	boolean wasLoaded;

	public iConomyEconomyHandler() {
		Plugin test = General.plugin.getServer().getPluginManager().getPlugin("iConomy");

		if(test != null) {
			String versionString = test.getDescription().getVersion();
			String majorRev = versionString.substring(0, versionString.indexOf('.'));
			int version = Integer.valueOf(majorRev);
			if(version < 5) {
				actualEconomy = new iConomy4EconomyHandler();
				wasLoaded = actualEconomy.wasLoaded();
			} else if(version < 6) {
				actualEconomy = new iConomy5EconomyHandler();
				wasLoaded = actualEconomy.wasLoaded();
			}
		} else wasLoaded = false;
	}

	@Override
	public boolean wasLoaded() {
		return wasLoaded;
	}

	@Override
	public String getVersion() {
		return actualEconomy.getVersion();
	}

	@Override
	public String getName() {
		return actualEconomy.getName();
	}

	@Override
	public double getBalance(Player who) {
		return actualEconomy.getBalance(who);
	}

	@Override
	public String getBalanceForDisplay(Player who) {
		return actualEconomy.getBalanceForDisplay(who);
	}

	@Override
	public String formatCost(double amount) {
		return actualEconomy.formatCost(amount);
	}

	@Override
	public boolean takePayment(Player fromWhom, double amount) {
		return actualEconomy.takePayment(fromWhom, amount);
	}

	@Override
	public void givePayment(Player toWhom, double amount) {
		actualEconomy.givePayment(toWhom, amount);
	}

	@Override
	public String getCurrency() {
		return actualEconomy.getCurrency();
	}

}

Add an iConomy handler that automatically detects the version. More intuitive, no?


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

package io.github.bonigarcia.wdm.test;

import static java.lang.Thread.sleep;
import static java.util.concurrent.TimeUnit.SECONDS;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

import io.github.bonigarcia.wdm.ChromeDriverManager;

/**
 * WebRTC test with Chrome.
 *
 * @author Boni Garcia (boni.gg@gmail.com)
 * @since 1.0.0
 */
public class WebRtcTest {

    private WebDriver driver;

    @BeforeClass
    public static void setupClass() {
        ChromeDriverManager.getInstance().setup();
    }

    @Before
    public void setupTest() {
        ChromeOptions options = new ChromeOptions();
        // This flag avoids to grant the user media
        options.addArguments("--use-fake-ui-for-media-stream");

        // This flag fakes user media with synthetic video (green with spinner
        // and timer)
        options.addArguments("--use-fake-device-for-media-stream");
        driver = new ChromeDriver(options);
    }

    @After
    public void teardown() {
        if (driver != null) {
            driver.quit();
        }
    }

    @Test
    public void test() throws InterruptedException {
        // Test data
        int timeout = 30;
        String sutUrl = "http://localhost:8080";

        // Implicit timeout
        driver.manage().timeouts().implicitlyWait(timeout, SECONDS);
        driver.manage().timeouts().implicitlyWait(timeout, SECONDS);

        // Open page
        driver.get(sutUrl);

        // Wait 5 seconds
        sleep(5000);
    }

}

Add example test for WebRTC and Chrome

Add example test for WebRTC and Chrome


package tools.vitruv.framework.correspondence;

/**
 * Generic interface for factories generating {@link CorrespondenceModelView}s
 * for special correspondence types.
 *
 * @author Heiko Klare
 *
 */
public interface CorrespondenceModelViewFactory<T extends CorrespondenceModelView<?>> {
	public T createCorrespondenceModelView(InternalCorrespondenceModel correspondenceModel);
	public T createEditableCorrespondenceModelView(InternalCorrespondenceModel correspondenceModel);
}

Add factory for creating specific correspondence model views


package io.github.classgraph.issues.issue350;

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

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

import org.junit.Test;

import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;

/**
 * Unit test.
 */
public class Issue350 {
    /** */
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface SuperclassAnnotation {
    }

    /** */
    public static class Pub {
        /** */
        @SuperclassAnnotation
        public int annotatedPublicField;

        /** */
        @SuperclassAnnotation
        public void annotatedPublicMethod() {
        }
    }

    /** */
    public static class Priv {
        /** */
        @SuperclassAnnotation
        private int annotatedPrivateField;

        /** */
        @SuperclassAnnotation
        private void annotatedPrivateMethod() {
        }
    }

    /** */
    public static class PubSub extends Pub {
    }

    /** */
    public static class PrivSub extends Priv {
    }

    /** Test finding subclasses of classes with annotated methods or fields. */
    @Test
    public void test() {
        try (ScanResult scanResult = new ClassGraph().whitelistPackages(Issue350.class.getPackage().getName())
                .enableClassInfo().enableFieldInfo().enableMethodInfo().enableAnnotationInfo().scan()) {
            assertThat(scanResult.getClassesWithFieldAnnotation(SuperclassAnnotation.class.getName()).getNames())
                    .containsExactlyInAnyOrder(Pub.class.getName(), PubSub.class.getName());
            assertThat(scanResult.getClassesWithMethodAnnotation(SuperclassAnnotation.class.getName()).getNames())
                    .containsExactlyInAnyOrder(Pub.class.getName(), PubSub.class.getName());
        }
        try (ScanResult scanResult = new ClassGraph().whitelistPackages(Issue350.class.getPackage().getName())
                .enableClassInfo().enableFieldInfo().enableMethodInfo().enableAnnotationInfo()
                .ignoreFieldVisibility().ignoreMethodVisibility().scan()) {
            assertThat(scanResult.getClassesWithFieldAnnotation(SuperclassAnnotation.class.getName()).getNames())
                    .containsExactlyInAnyOrder(Pub.class.getName(), PubSub.class.getName(), Priv.class.getName());
            assertThat(scanResult.getClassesWithMethodAnnotation(SuperclassAnnotation.class.getName()).getNames())
                    .containsExactlyInAnyOrder(Pub.class.getName(), PubSub.class.getName(), Priv.class.getName());
        }
    }
}

Add unit test for 350

Add unit test for 350


/*
 * Copyright 2014 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 net.kuujo.vertigo.util;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vertx.core.json.JsonObject;
import net.kuujo.vertigo.VertigoException;

import java.io.IOException;

/**
 * JSON utilities.
 *
 * @author Jordan Halterman
 */
public final class Json {
  private static final ObjectMapper mapper = new ObjectMapper();

  /**
   * JSON serializable interface.
   */
  @JsonIgnoreProperties(ignoreUnknown=true)
  @JsonInclude(JsonInclude.Include.ALWAYS)
  @JsonAutoDetect(
    creatorVisibility= JsonAutoDetect.Visibility.NONE,
    fieldVisibility=JsonAutoDetect.Visibility.ANY,
    getterVisibility=JsonAutoDetect.Visibility.NONE,
    isGetterVisibility=JsonAutoDetect.Visibility.NONE,
    setterVisibility=JsonAutoDetect.Visibility.NONE
  )
  public static interface Serializable {
  }

  /**
   * Serializes an object to JSON.
   *
   * @param object The object to serialize.
   * @param <T> The serializable type.
   * @return The serialized object.
   */
  public static <T extends Json.Serializable> JsonObject serialize(T object) {
    try {
      return new JsonObject(mapper.writeValueAsString(object));
    } catch (IOException e) {
      throw new VertigoException(e);
    }
  }

  /**
   * Deserializes an object from JSON.
   *
   * @param json The JSON from which to deserialize the object.
   * @param type The object type to deserialize.
   * @param <T> The deserialized object type.
   * @return The deserialized object.
   */
  public static <T extends Json.Serializable> T deserialize(JsonObject json, Class<T> type) {
    try {
      return mapper.readValue(json.encode(), type);
    } catch (IOException e) {
      throw new VertigoException(e);
    }
  }

}

Add JSON serializion support for definitions and contexts.


package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceConfig;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthException;
import com.google.firebase.auth.FirebaseToken;
import com.google.gson.Gson;
import com.google.sps.firebase.FirebaseAppManager;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/check-student")
public class CheckStudentStatus extends HttpServlet {
  FirebaseAuth authInstance;
  DatastoreService datastore;

  @Override
  public void init(ServletConfig config) throws ServletException {
    try {
      authInstance = FirebaseAuth.getInstance(FirebaseAppManager.getApp());

      datastore = DatastoreServiceFactory.getDatastoreService();
      System.setProperty(
          DatastoreServiceConfig.DATASTORE_EMPTY_LIST_SUPPORT, Boolean.TRUE.toString());
    } catch (IOException e) {
      throw new ServletException(e);
    }
  }

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
      // Find user ID
      String idToken = request.getParameter("userToken");
      FirebaseToken decodedToken = authInstance.verifyIdToken(idToken);
      String uID = decodedToken.getUid();

      // Retrive entity
      String classCode = request.getParameter("classCode").trim();
      Key classKey = KeyFactory.stringToKey(classCode);
      Entity classEntity = datastore.get(classKey);

      // Find position in queue
      ArrayList<String> queue = (ArrayList) classEntity.getProperty("studentQueue");
      String pos = Integer.toString(queue.indexOf(uID));

      Gson gson = new Gson();
      response.setContentType("application/json;");
      response.getWriter().println(gson.toJson(pos));

    } catch (EntityNotFoundException e) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND);
    } catch (IllegalArgumentException e) {
      response.sendError(HttpServletResponse.SC_BAD_REQUEST);
    } catch (FirebaseAuthException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    }
  }
}

Create servlet that returns student position on queue


package com.minelittlepony.settings;

import com.minelittlepony.common.client.gui.IField.IChangeCallback;

/**
 * A sensible config container that actually lets us programmatically index values by a key.
 *
 * Reflection because Mumfrey pls.
 *
 */
// Mumfrey pls.
public abstract class SensibleConfig {

    private static SensibleConfig instance;

    public SensibleConfig() {
        instance = this;
    }

    public abstract void save();

    public interface Setting extends IChangeCallback<Boolean> {
        String name();

        /**
         * Gets the config value associated with this entry.
         */
        default boolean get() {
            return instance.getValue(this);
        }

        /**
         * Sets the config value associated with this entry.
         */
        default void set(boolean value) {
            instance.setValue(this, value);
        }

        @Override
        default Boolean perform(Boolean v) {
            set(v);
            return v;
        }
    }

    public boolean getValue(Setting key) {
        try {
            return getClass().getField(key.name().toLowerCase()).getBoolean(this);
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ignored) {
            return true;
        }
    }

    public boolean setValue(Setting key, boolean value) {
        try {
            getClass().getField(key.name().toLowerCase()).setBoolean(this, value);
        } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException ignored) {
        }
        return value;
    }
}

Move sensibleConfig back into MineLP. This was a mistake. The static makes it less useful to other projects


package io.sigpipe.sing.stat;

import io.sigpipe.sing.serialization.ByteSerializable;
import io.sigpipe.sing.serialization.SerializationInputStream;
import io.sigpipe.sing.serialization.SerializationOutputStream;

public class SerializableReservoir<T extends ByteSerializable>
extends Reservoir<T> implements ByteSerializable {

    @Deserialize
    public SerializableReservoir(SerializationInputStream in) {
        super(0);
    }

    @Override
    public void serialize(SerializationOutputStream out) {

    }
}

Add stub for serializable reservoir

Add stub for serializable reservoir


package com.jmb.springfactory.model.bo;

import java.util.Date;

import com.jmb.springfactory.model.enumeration.TaskStatusEnum;

import lombok.Builder;
import lombok.Data;

@Data
@Builder
public class QueryTaskObject {

  private String name;
  private TaskStatusEnum status;
  private Date startDate;
  private Date finishDate;
  private String priority;
  private String creator;
}

Create a class to pass all parameter to search tasks


/*
 * Copyright 2010 Ning, Inc.
 *
 * Ning 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.ning.http.client.async;

import com.ning.http.client.AsyncHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.HttpResponseBodyPart;
import com.ning.http.client.HttpResponseHeaders;
import com.ning.http.client.HttpResponseStatus;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeoutException;

/**
 * Simple stress test for exercising the follow redirect.
 */
public class FollowingThreadTest extends AbstractBasicTest {

    private final static int COUNT = 10;

    @Test(timeOut = 30 * 1000, groups = "scalability")
    public void testFollowRedirect() throws IOException, ExecutionException, TimeoutException, InterruptedException {

        final CountDownLatch countDown = new CountDownLatch(COUNT);
        ExecutorService pool = Executors.newCachedThreadPool();
        for (int i = 0; i < COUNT; i++) {
            pool.submit(new Runnable() {

                private int status;

                public void run() {
                    final CountDownLatch l = new CountDownLatch(1);
                    AsyncHttpClient ahc = new AsyncHttpClient(
                            new AsyncHttpClientConfig.Builder().setFollowRedirects(true).build());
                    try {
                        ahc.prepareGet("http://www.google.com/").execute(new AsyncHandler<Integer>() {

                            public void onThrowable(Throwable t) {
                                t.printStackTrace();
                            }

                            public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception {
                                System.out.println(new String(bodyPart.getBodyPartBytes()));
                                return STATE.CONTINUE;
                            }

                            public STATE onStatusReceived(HttpResponseStatus responseStatus) throws Exception {
                                status = responseStatus.getStatusCode();
                                System.out.println(responseStatus.getStatusText());
                                return STATE.CONTINUE;
                            }

                            public STATE onHeadersReceived(HttpResponseHeaders headers) throws Exception {
                                return STATE.CONTINUE;
                            }

                            public Integer onCompleted() throws Exception {
                                l.countDown();
                                return status;
                            }
                        });

                        l.await();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        ahc.close();
                        countDown.countDown();
                    }
                }
            });
        }
        countDown.await();
    }

}

Add a unit test trying to reproduce the issue related on the mailling list