/**
 * Given a binary tree, return the bottom-up level order traversal of its nodes' values.
 * (ie, from left to right, level by level from leaf to root).
 */
public class Solution {
  public List<List<Integer>> levelOrderBottom(TreeNode root) {
    Queue<TreeNode> q = new LinkedList<TreeNode>();
    List<List<Integer>> list = new ArrayList<List<Integer>>();
    if (root == null) return list;

    List<Integer> temp = new ArrayList<Integer>();
    int cur = 1;
    int next = 0;
    q.add(root);

    while (!q.isEmpty()) {
      TreeNode node = q.poll();
      temp.add(node.val);
      cur --;

      if (cur == 0 && !temp.isEmpty()) {
        list.add(0, temp);
        temp = new ArrayList<Integer>();
      }

      if (node.left != null) {
        q.add(node.left);
        next ++;
      }

      if (node.right != null) {
        q.add(node.right);
        next ++;
      }

      if (cur == 0) {
        cur = next;
        next = 0;
      }
    }

    return list;
  }
}

Add tree level order traversal ii

Add tree level order traversal ii


package org.realityforge.replicant.client;

import java.util.ArrayList;

class RecordingListener
    implements EntityChangeListener
{
  private final ArrayList<EntityChangeEvent> _entityRemovedEvents = new ArrayList<EntityChangeEvent>();
  private final ArrayList<EntityChangeEvent> _attributeChangedEvents = new ArrayList<EntityChangeEvent>();
  private final ArrayList<EntityChangeEvent> _relatedAddedEvents = new ArrayList<EntityChangeEvent>();
  private final ArrayList<EntityChangeEvent> _relatedRemovedEvents = new ArrayList<EntityChangeEvent>();

  public boolean hasRecordedEvents()
  {
    return !hasNoRecordedEvents();
  }

  private boolean hasNoRecordedEvents()
  {
    return 0 == _entityRemovedEvents.size() &&
           0 == _attributeChangedEvents.size() &&
           0 == _relatedAddedEvents.size() &&
           0 == _relatedRemovedEvents.size();
  }

  public void clear()
  {
    _entityRemovedEvents.clear();
    _attributeChangedEvents.clear();
    _relatedAddedEvents.clear();
    _relatedRemovedEvents.clear();
  }

  public void entityRemoved( final EntityChangeEvent event )
  {
    _entityRemovedEvents.add( event );
  }

  public void attributeChanged( final EntityChangeEvent event )
  {
    _attributeChangedEvents.add( event );
  }

  public void relatedAdded( final EntityChangeEvent event )
  {
    _relatedAddedEvents.add( event );
  }

  public void relatedRemoved( final EntityChangeEvent event )
  {
    _relatedRemovedEvents.add( event );
  }

  public ArrayList<EntityChangeEvent> getEntityRemovedEvents()
  {
    return _entityRemovedEvents;
  }

  public ArrayList<EntityChangeEvent> getAttributeChangedEvents()
  {
    return _attributeChangedEvents;
  }

  public ArrayList<EntityChangeEvent> getRelatedAddedEvents()
  {
    return _relatedAddedEvents;
  }

  public ArrayList<EntityChangeEvent> getRelatedRemovedEvents()
  {
    return _relatedRemovedEvents;
  }
}

Add in a listener to record events as part of testing


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

package com.google.sps.servlets;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet("/load-event")
public class LoadEventServlet extends HttpServlet {

  private static final Logger LOGGER = Logger.getLogger(EventServlet.class.getName());

  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // TODO: Implement doGet function.
  }
}

Add basic load event servlet

Add basic load event servlet


[dbgeneric] Fix relations between ColumnStore and PhysicalTypes; implement a ColumnStore based bloom filter (incomplete).


package net.kencochrane.raven;

import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;

public abstract class RavenFactory {
    private static final Logger logger = Logger.getLogger(RavenFactory.class.getCanonicalName());
    private static final ServiceLoader<RavenFactory> RAVEN_FACTORIES = ServiceLoader.load(RavenFactory.class);

    public static Raven ravenInstance(Dsn dsn) {
        for (RavenFactory ravenFactory : RAVEN_FACTORIES) {
            Raven raven = getRavenSafely(dsn, ravenFactory);
            if (raven != null) {
                return raven;
            }
        }

        throw new IllegalStateException("Couldn't create a raven instance for '" + dsn + "'");
    }

    public static Raven ravenInstance(Dsn dsn, String ravenFactoryName) {
        for (RavenFactory ravenFactory : RAVEN_FACTORIES) {
            if (!ravenFactoryName.equals(ravenFactory.getClass().getCanonicalName()))
                continue;

            Raven raven = getRavenSafely(dsn, ravenFactory);
            if (raven != null) {
                return raven;
            }
        }

        throw new IllegalStateException("Couldn't create a raven instance for '" + dsn + "'");
    }

    private static Raven getRavenSafely(Dsn dsn, RavenFactory ravenFactory) {
        Raven raven = null;
        try {
            raven = ravenFactory.createRavenInstance(dsn);
        } catch (Exception e) {
            logger.log(Level.WARNING, "An exception occurred during the creation of a Raven instance with " +
                    "'" + ravenFactory + "' using the DSN '" + dsn + "'", e);
        }
        return raven;
    }

    public abstract Raven createRavenInstance(Dsn dsn);
}

Create a Simple factory to create Raven instances


package org.zeropage.apps.zeropage.utility;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;

public final class UserInfoPreferences {
    private static final String TAG = UserInfoPreferences.class.getSimpleName();
    private static final String KEY_NAME = "name";

    public static void putUserName(@NonNull Context context, @NonNull String userName) {
        Log.i(TAG, "Save to Preferences. name = " + userName);

        getPreferences(context).edit()
                .putString(KEY_NAME, userName)
                .apply();
    }

    private static SharedPreferences getPreferences(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    }

    @Nullable
    public static String getUserName(@NonNull Context context) {
        return getPreferences(context).getString(KEY_NAME, null);
    }
}

Add a new Preferences class for saving user information.


//
// Copyright (c) 2011 Linkeos.
//
// This file is part of Elveos.org.
// Elveos.org is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// Elveos.org is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
// You should have received a copy of the GNU General Public License along
// with Elveos.org. If not, see http://www.gnu.org/licenses/.
//
package com.bloatit.model.right;

import com.bloatit.model.Member;

/**
 * The Class MemberRight store the properties accessor for the {@link Member}
 * class.
 */
public class TeamRight extends RightManager {

    /**
     * The Class Email is a {@link Public} accessor for the Contact property.
     */
    public static class Contact extends Public {
        // nothing this is just a rename.
    }

    /**
     * The Class Email is a {@link Public} accessor for the DisplayName property.
     */
    public static class DisplayName extends Public {
        // nothing this is just a rename.
    }

}

Add a right manager for the team

Add a right manager for the team


package water;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import water.api.UnlockTask;
import water.fvec.Frame;
import water.util.Log;

public class UnlockTest extends TestUtil {
  @BeforeClass
  public static void stall() { stall_till_cloudsize(3); }

  static class DJob extends Job {
    DJob(Key a) { super(a,"DJob",1); }
  }

  @Test
  public void run() {
    // Put chunks into KV store
    Frame f = new TestUtil().parse_test_file("smalldata/junit/syn_2659x1049.csv.gz");
    // Create two lockable frames in KV store
    Frame fr1 = new Frame(Key.make(), f.names(), f.vecs());
    Frame fr2 = new Frame(Key.make(), f.names(), f.vecs());
    DJob dj = new DJob(Key.make());
    // Lock the frames against writes
    fr1.delete_and_lock(dj._key);
    fr2.delete_and_lock(dj._key);
    int i = 0;
    try {
      // try to delete the write-locked frames -> will throw an exception
      fr1.delete();
      fr2.delete(); // won't be reached
    } catch (Throwable t) {
      Log.info("Correctly caught exception: " + t.getClass()); //either AssertionError if local or DistributedException if remote
      i++;
    } finally {
      // second attempt: will unlock and delete properly
      new UnlockTask().doAllNodes(); // without this line, there will be a leak (and assertion won't be shown)
      fr1.delete();
      fr2.delete();
      f.delete();
      Log.info("Able to delete after unlocking.");
    }
    Assert.assertTrue(i == 1);
  }
}

Add JUnit test for UnlockKeys.

Add JUnit test for UnlockKeys.


package leetcode.minimum_path_sum;

public class Solution {
    public int minPathSum(int[][] grid) {
    	if(grid == null) return 0;
    	if(grid.length == 0 || grid[0].length == 0) return 0;
    	int width = grid[0].length;
    	int height = grid.length;
    	for(int i = 0; i < height; i++){
    		for(int j = 0; j < width; j++){
    			int minPath = 0;
    			if(i > 0){
    				if(j == 0){
    					minPath = grid[i - 1][j];
    				}else{
    					minPath = Math.min(grid[i - 1][j], grid[i][j - 1]);
    				}
    			}else{
    				if(j > 0){
    					minPath = grid[i][j - 1];
    				}
    			}
    			grid[i][j] += minPath;
    		}
    	}
    	return grid[height - 1][width - 1];
    }
}

Add java solution for 64. Minimum Path Sum

64. Minimum Path Sum: https://leetcode.com/problems/minimum-path-sum/


package com.tymiller.controller;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@RestController
@RequestMapping("/rest")
public class PhotoResource {

	private String imageName;

	@Autowired
	private PhotoService photoService;

	@RequestMapping(value="/photo/upload", method = RequestMethod.POST)
	public String upload(HttpServletResponse response, HttpServletRequest request) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Iterator<String> it = multipartRequest.getFileNames();
		MultipartFile multipartFile = multipartRequest.getFile(it.next());
		String fileName = multipartFile.getOriginalFilename();
		imageName=fileName;

		String path = new File("target/classes/static/images").getAbsolutePath() + "\\" + fileName;
		try {
			multipartFile.transferTo(new File(path));
			System.out.println(path);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return "Upload Success!";
	}
}

Add rest resource and upload method

Add rest resource and upload method


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

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

import javax.persistence.*;
import java.util.Date;

import static org.junit.Assert.assertNotNull;

/**
 * @author Vlad Mihalcea
 */
public class OneToOneInsertableUpdatableFalseTest extends AbstractTest {

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

    @Test
    public void testLifecycle() {
        doInJPA(entityManager -> {
            Post post = new Post("First post");
            entityManager.persist(post);
        });
        doInJPA(entityManager -> {
            Post post = entityManager.find(Post.class, 1L);
            PostDetails details = new PostDetails("John Doe");
            details.setPost(post);
            entityManager.persist(details);
        });

        doInJPA(entityManager -> {
            Post post = entityManager.find(Post.class, 1L);
            PostDetails details = entityManager.find(PostDetails.class, post.getId());
            assertNotNull(details);

            entityManager.flush();
            details.setPost(null);
        });
    }

    @Entity(name = "Post")
    @Table(name = "post")
    public static class Post {

        @Id
        @GeneratedValue
        private Long id;

        private String title;

        public Post() {}

        public Post(String title) {
            this.title = title;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }
    }

    @Entity(name = "PostDetails")
    @Table(name = "post_details")
    public static class PostDetails {

        @Id
        @Column(name = "post_id")
        private Long id;

        @Column(name = "created_on")
        private Date createdOn;

        @Column(name = "created_by")
        private String createdBy;

        @OneToOne
        @JoinColumn(name = "post_id", insertable = false, updatable = false)
        private Post post;

        public PostDetails() {}

        public PostDetails(String createdBy) {
            createdOn = new Date();
            this.createdBy = createdBy;
        }

        public Long getId() {
            return id;
        }

        public void setId(Long id) {
            this.id = id;
        }

        public Date getCreatedOn() {
            return createdOn;
        }

        public String getCreatedBy() {
            return createdBy;
        }

        public Post getPost() {
            return post;
        }

        public void setPost(Post post) {
            this.post = post;
            if (post != null) {
                this.id = post.getId();
            }
        }
    }
}

Add test showing how to map a one-to-one table relationship without @MapsId


package org.hollowcraft.model;
/*
 * HollowCraft License
 *  Copyright (c) 2010 Caleb Champlin.
 *  All rights reserved
 *  This license must be include in all copied, cloned and derived works
 */
/**
 * Lighting constants
 * @author Caleb champlin
 */
public class LightConstants {
	/**
	 * Default private constructor.
	 */
	private LightConstants() {
		/* empty */
	}
	public static final int DARK = 0;
	public static final int SUBTLELIGHT = 1;
	public static final int MEDIUMSUBTLELIGHT = 2;
	public static final int HIGHSUBTLELIGHT = 3;
	public static final int LOWLIGHT = 4;
	public static final int MEDIUMLOWLIGHT = 5;
	public static final int HIGHLOWLIGHT = 6;
	public static final int SOFTLIGHT = 7;
	public static final int MEDIUMSOFTLIGHT = 8;
	public static final int HIGHSOFTLIGHT = 9;
	public static final int MIDLIGHT = 10;
	public static final int MEDIUMMIDLIGHT = 11;
	public static final int HIGHMIDLIGHT = 12;
	public static final int BRIGHTLIGHT = 13;
	public static final int MEDIUMBRIGHTLIGHT = 14;
	public static final int HIGHBRIGHTLIGHT = 15;
	public static final int TORCHLIGHT = 14;
	public static final int FURNACELIGHT = 14;
	public static final int FIRELIGHT = 15;
	public static final int SUNLIGHT = 15;

}

Add some constants for lighting for future use


package com.vladmihalcea.hibernate.masterclass.laboratory.mapping;

import com.vladmihalcea.hibernate.masterclass.laboratory.util.AbstractTest;
import org.junit.Test;

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

/**
 * ManyToManyWithElementCollectionTest - ManyToMany with ElementCollection Test
 *
 * @author Vlad Mihalcea
 */
public class ManyToManyWithElementCollectionTest extends AbstractTest {

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

    @Test
    public void testAddingEmbeddable() {
        doInTransaction(session -> {
            Clubber clubber = new Clubber();
            Club club = new Club();
            clubber.addClub(club);
        });
    }

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

        @Id
        @GeneratedValue
        @Column(name = "Clubber_Id")
        private Integer id;

        @Temporal(TemporalType.TIMESTAMP)
        @ElementCollection
        @CollectionTable(name="CLUB_ASSIGNMENTS", joinColumns=@JoinColumn(name="Clubber_Id", referencedColumnName="Clubber_Id"))
        @Column(name="CLUB_DATE")
        @MapKeyJoinColumn(name = "Club_ID", referencedColumnName="Club_ID")
        private Map<Club, Date> joinDate = new HashMap<>();

        @ManyToMany(cascade = CascadeType.PERSIST)
        @JoinTable(name = "CLUB_ASSIGNMENTS",
                joinColumns = @JoinColumn(name="Clubber_Id", referencedColumnName="Clubber_Id"),
                inverseJoinColumns = @JoinColumn(name="Club_ID", referencedColumnName="Club_ID"))
        private List<Club> clubs = new ArrayList<>();

        public Integer getId() {
            return id;
        }

        public Map<Club, Date> getJoinDate() {
            return joinDate;
        }

        public List<Club> getClubs() {
            return clubs;
        }

        public void addClub(Club club) {
            joinDate.put(club, new Date());
            clubs.add(club);
            club.getClubbers().add(this);
        }
    }

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

        @Id
        @GeneratedValue
        @Column(name = "Club_ID")
        private Integer id;

        @ManyToMany(cascade = CascadeType.PERSIST, mappedBy = "clubs")
        private List<Clubber> clubbers = new ArrayList<>();

        public Integer getId() {
            return id;
        }

        public List<Clubber> getClubbers() {
            return clubbers;
        }
    }
}

Add @ManyToMany with @ElementCollection test


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

import java.util.Collections;
import java.util.List;

import org.junit.jupiter.api.Test;
import org.xwiki.notifications.CompositeEventStatus;
import org.xwiki.test.junit5.mockito.ComponentTest;
import org.xwiki.test.junit5.mockito.InjectMockComponents;

import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * Unit tests ofr {@link DefaultCompositeEventStatusManager}
 *
 * @version $Id$
 */
@ComponentTest
public class DefaultCompositeEventStatusManagerTest
{
    @InjectMockComponents
    private DefaultCompositeEventStatusManager eventStatusManager;

    @Test
    void getCompositeEventStatusesWhenEmpty() throws Exception
    {
        List<CompositeEventStatus> statuses =
            this.eventStatusManager.getCompositeEventStatuses(Collections.emptyList(), null);
        assertTrue(statuses.isEmpty());
    }
}

[Misc] Fix mutation score (put it back to 8%, was 7% after recent commits)


package org.uma.jmetal.util.pseudorandom;

/**
 * A {@link RandomGenerator} aims to provide a random value of a given type. Any
 * value of this type can be generated.

 *

 * A {@link RandomGenerator} is a {@link FunctionalInterface}. It is not
 * intended to be directly implemented by a class, but instead to request a
 * method for generating random values, usually by using lambda expressions.
 *
 * @author Matthieu Vergne <matthieu.vergne@gmail.com>
 *
 * @param <Value>
 *            The type of value to generate
 */
@FunctionalInterface
public interface RandomGenerator<Value> {
	/**
	 * Generate a random value.
	 *
	 * @return the value generated
	 */
	public Value getRandomValue();
}

Add a functional interface for random generators.


package com.Acrobot.ChestShop.Listeners.Player;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerTeleportEvent;

/**
 * A fix for a CraftBukkit bug.
 * @author Acrobot
 */
public class PlayerTeleport implements Listener {

    @EventHandler
    public static void onPlayerTeleport(PlayerTeleportEvent event) {
        event.getPlayer().closeInventory();
    }
}

Fix a possible duplication bug

Fix a possible duplication bug


/*
 * Yet Another UserAgent Analyzer
 * Copyright (C) 2013-2018 Niels Basjes
 *
 * 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 nl.basjes.parse.useragent;

import nl.basjes.parse.useragent.debug.UserAgentAnalyzerTester;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

import static org.junit.Assert.assertTrue;

public class TestSerializationFast {

    private static final Logger LOG = LoggerFactory.getLogger(TestSerializationFast.class);

    protected static UserAgentAnalyzerTester uaa;

    @BeforeClass
    public static void serializeAndDeserializeUAA() throws IOException, ClassNotFoundException {
        LOG.info("==============================================================");
        LOG.info("Create");
        LOG.info("--------------------------------------------------------------");
        uaa = new UserAgentAnalyzerTester();
        uaa.setShowMatcherStats(false);
        uaa.delayInitialization();
        uaa.initialize();

        LOG.info("--------------------------------------------------------------");
        LOG.info("Serialize");
        byte[] bytes;
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ObjectOutput out = new ObjectOutputStream(bos);
            out.writeObject(uaa);
            out.flush();
            bytes = bos.toByteArray();
        }

        uaa = null;

        LOG.info("The UserAgentAnalyzer was serialized into {} bytes", bytes.length);
        LOG.info("--------------------------------------------------------------");
        LOG.info("Deserialize");
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInput in = null;

        try {
            in = new ObjectInputStream(bis);
            Object o = in.readObject();
            if (!(o instanceof UserAgentAnalyzerTester)) {
                throw new IOException("This shouldn't happen...");
            }
            uaa = (UserAgentAnalyzerTester) o;
        } finally {
            if (in != null) {
                in.close();
            }
        }
        LOG.info("Done");
        LOG.info("==============================================================");
    }

    @Test
    public void validateAllPredefinedBrowsers() {
        LOG.info("==============================================================");
        LOG.info("Validating when getting all fields");
        LOG.info("--------------------------------------------------------------");
        assertTrue(uaa.runTests(false, true));
    }

}

Test serialization with delayed init

Test serialization with delayed init


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

package ij.notebook.converter;

import org.scijava.convert.Converter;
import org.scijava.log.LogService;
import org.scijava.notebook.converter.NotebookConverters;
import org.scijava.notebook.converter.NotebookOutputConverter;
import org.scijava.notebook.converter.output.PNGImageNotebookOutput;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;

import ij.ImagePlus;

/**
 * Converts an {@link ImagePlus} to a PNG.
 *
 * @author Alison Walter
 */
@Plugin(type = Converter.class)
public class ImagePlusToPNGNotebookConverter extends
    NotebookOutputConverter<ImagePlus, PNGImageNotebookOutput>
{
    @Parameter
    private LogService log;

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

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

    @Override
    public PNGImageNotebookOutput convert(final Object object) {
        final ImagePlus imgPlus = (ImagePlus) object;
        final String base64Image = NotebookConverters.toPNG(imgPlus.getBufferedImage());
        return new PNGImageNotebookOutput(base64Image);
    }
}

Add converter for ImagePlus to PNG

Add converter for ImagePlus to PNG


package org.svetovid.installer;

import java.util.Set;
import java.util.TreeSet;

public class JavaInstallationSetCollector implements Collector<JavaInstallation> {

    private Set<JavaInstallation> set = new TreeSet<>();

    @Override
    public void collect(JavaInstallation installation) {
        set.add(installation);
    }

    public Set<JavaInstallation> getCollected() {
        return set;
    }
}

Add an implementation of JavaInstallation collector


package study.hard;

import static org.junit.Assert.*;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.junit.Before;
import org.junit.Test;

import study.hard.commons.User;

/**
 * @author SeomGi, Han(iandmyhand@gmail.com)
 */
public class EqualsBuilderTester {

	private class UserOverrideEquals extends User {
		private static final long serialVersionUID = 3964053505870438947L;

		public UserOverrideEquals(String name, Integer age) {
			super(name, age);
		}

		@Override
		public boolean equals(Object obj) {
			return EqualsBuilder.reflectionEquals(this, obj);
		}
	}

	private UserOverrideEquals user1;
	private UserOverrideEquals user2;
	private UserOverrideEquals user3;
	private UserOverrideEquals user4;

	@Before
	public void setUp() {
		user1 = new UserOverrideEquals("Tester1", 20);
		user2 = new UserOverrideEquals("Tester1", 20);
		user3 = new UserOverrideEquals("Tester2", 20);
		user4 = new UserOverrideEquals("Tester3", 25);
	}

	@Test
	public void testEquals() {
		assertTrue(user1.equals(user2));
		assertFalse(user3.equals(user4));
	}
}

Add test code of EqualsBuilder.

Add test code of EqualsBuilder.


package com.example.spring.react.service;

import reactor.core.publisher.Flux;

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ReactiveService {

    public static void main(String[] args) {
        Flux<String> flux = Flux.just("One", "Two", "Three");
        Flux.range(5, 3)
                .subscribe(System.out::println);
        Flux.fromIterable(Stream.of("One", "Two", "Three").collect(Collectors.toList()))
                .subscribe(System.out::println);
        Flux.range(1, 4)
                .map(i -> {
                    if (i <= 3) return i;
                    throw new RuntimeException("Got to 4");
                })
                .subscribe(System.out::println,
                        error -> System.err.println("Error: " + error),
                        () -> System.out.println("Done"));
    }
}

Add examples of flux generation

Add examples of flux generation


package com.lmax.disruptor;

import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.junit.Assert.*;

import java.util.concurrent.TimeUnit;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(JMock.class)
public class LiteTimeoutBlockingWaitStrategyTest
{
    private final Mockery mockery = new Mockery();

    @Test
    public void shouldTimeoutWaitFor() throws Exception
    {
        final SequenceBarrier sequenceBarrier = mockery.mock(SequenceBarrier.class);

        long theTimeout = 500;
        LiteTimeoutBlockingWaitStrategy waitStrategy = new LiteTimeoutBlockingWaitStrategy(theTimeout, TimeUnit.MILLISECONDS);
        Sequence cursor = new Sequence(5);
        Sequence dependent = cursor;

        mockery.checking(
            new Expectations()
            {
                {
                    allowing(sequenceBarrier).checkAlert();
                }
            });

        long t0 = System.currentTimeMillis();

        try
        {
            waitStrategy.waitFor(6, cursor, dependent, sequenceBarrier);
            fail("TimeoutException should have been thrown");
        }
        catch (TimeoutException e)
        {
        }

        long t1 = System.currentTimeMillis();

        long timeWaiting = t1 - t0;

        assertThat(timeWaiting, greaterThanOrEqualTo(theTimeout));
    }
}

Test for the timeout behaviour of the LiteTimeoutBlockingWaitStrategy.


package de.philipphager.disclosure.database.app.mapper;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import de.philipphager.disclosure.database.app.model.App;
import de.philipphager.disclosure.util.Mapper;
import javax.inject.Inject;

public class ToAppMapper implements Mapper<ApplicationInfo, App> {
  private final PackageManager packageManager;

  @Inject public ToAppMapper(PackageManager packageManager) {
    this.packageManager = packageManager;
  }

  @Override public App map(ApplicationInfo from) {
    return App.builder()
        .label(String.valueOf(packageManager.getApplicationLabel(from)))
        .packageName(from.packageName)
        .process(from.processName)
        .sourceDir(from.sourceDir)
        .flags(from.flags)
        .build();
  }
}

Add mapper for android.ApplicationInfo to App model

Used to transition between the Android model
and the app’s model.


package org.forestguardian.View.Fragments;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import org.forestguardian.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class WildfireFragment extends Fragment {

    public WildfireFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.wildfire_details,container,false);

        return view;
    }

}

Add the Wildfire details fragment

Add the Wildfire details fragment


package com.example.profbola.bakingtime.services;

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

import com.example.profbola.bakingtime.models.Ingredient;
import com.example.profbola.bakingtime.models.Recipe;
import com.example.profbola.bakingtime.models.Step;
import com.example.profbola.bakingtime.provider.RecipeContract;
import com.example.profbola.bakingtime.utils.RecipeNetworkUtil;
import com.example.profbola.bakingtime.utils.RecipeParser;

import org.json.JSONArray;

import java.util.List;

import static com.example.profbola.bakingtime.provider.RecipeContract.RecipeEntry.CONTENT_URI;

/**
 * Created by prof.BOLA on 7/5/2017.
 */

public class RecipeTasks {

    synchronized static void writeRecipes(@NonNull Context context) {

        JSONArray jsonArray = RecipeNetworkUtil.getRecipeFromApi();
        List<Recipe> recipeParser = RecipeParser.parse(jsonArray);

        for (Recipe recipe: recipeParser) {
            insertRecipe(context, recipe);
            insertIngredients(context, recipe);
            insertSteps(context, recipe);
        }

    }

    private static void insertSteps(Context context, Recipe recipe) {
        int id = recipe.id;
        for (Step step: recipe.steps) {
            context.getContentResolver().insert(
                    RecipeContract.StepEntry.CONTENT_URI(id),
                    step.toContentValues(id)
            );
        }
    }

    private static void insertIngredients(Context context, Recipe recipe) {
        int id = recipe.id;
        for (Ingredient ingredient: recipe.ingredients) {
            context.getContentResolver().insert(
                    RecipeContract.IngredientEntry.CONTENT_URI(id),
                    ingredient.toContentValues(id)
            );
        }
    }

    private static void insertRecipe(Context context, Recipe recipe) {
        context.getContentResolver().insert(
                CONTENT_URI,
                recipe.toContentValues()
        );
    }
}

Add Recipe DB writer task

Add Recipe DB writer task


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

package dp;

/**
 *

 *     53. Maximum Subarray
 * Difficulty: Medium
 * Find the contiguous subarray within an array
 * (containing at least one number) which has the largest sum.
 *
 * For example, given the array
 *          [−2,1,−3,4,−1,2,1,−5,4],
 *
 * the contiguous subarray [4,−1,2,1]
 * has the largest sum = 6.
 *
 * More practice:
 * If you have figured out the O(n) solution,
 * try coding another solution using the divide and conquer approach, which is more subtle.
 *
 *  Tags
 *          Array
 *          Dynamic Programming
 *          Divide and Conquer
 *
 *   Similar Problems
 *          (E) Best Time to Buy and Sell Stock
 *          (M) Maximum Product Subarray
 *
 *
 *   ===========================================================================
 *
 *   O(n) in time  see {@link KadaneAlgorithm Kadane Algorithm  }
 *
 * @see leetcode
 */
public class Leetcode53MaximumSubarray {
    public int maxSubArray(int[] nums) {
        int n = nums.length;
        int max = nums[0], maxEndingHere = nums[0];
        for (int i = 1; i < n; i++) {
            maxEndingHere = ((maxEndingHere < 0) ? 0 : maxEndingHere) + nums[i];
            max = maxEndingHere > max ? maxEndingHere : max;
        }
        return max;
    }
}

Add Leetcode 53 Maximum Subarray

Add Leetcode 53 Maximum Subarray

Change-Id: I321135589702ea32b69480a4b33f9cf528b89b6a


/*
 * Bach - Java Shell Builder
 * Copyright (C) 2020 Christian Stein
 *
 * 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 test.modules;

import static org.junit.jupiter.api.Assertions.assertTrue;

import de.sormuras.bach.Bach;
import de.sormuras.bach.api.Paths;
import de.sormuras.bach.api.Project;
import de.sormuras.bach.api.Realm;
import de.sormuras.bach.api.Source;
import de.sormuras.bach.api.Unit;
import java.lang.module.ModuleDescriptor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import test.base.Log;
import test.base.Tree;

class DocProjectJigsawQuickStartTests {

  @Test
  void build(@TempDir Path temp) {
    var name = "jigsaw.quick.start";
    var base = Path.of("doc", "project", name);

    assertTrue(Files.isDirectory(base), "Directory not found: " + base);

    var module = "com.greetings";
    var source = Source.of(base.resolve(module));
    var unit =
        new Unit(
            source.path().resolve("module-info.java"),
            ModuleDescriptor.newModule(module).mainClass(module + ".Main").build(),
            base,
            List.of(source),
            List.of());
    var realm = new Realm("", 0, Map.of(module, unit), List.of());
    var paths = new Paths(base, temp.resolve("out"), temp.resolve("lib"));
    var project =
        Project.builder()
            .paths(paths)
            .name(name)
            .units(List.of(unit))
            .realms(List.of(realm))
            .build();
    var log = new Log();
    var bach = new Bach(log, true);
    var summary = bach.build(project);

    summary.assertSuccessful();

    Tree.walk(temp, System.out::println);
    summary.toMarkdown().forEach(System.out::println);
  }
}

Introduce build test for documentation project "jigsaw.quick.start"


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

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

import static org.junit.Assert.assertEquals;

/**
 * @author Pedro Vicente Gómez Sánchez.
 */
public class FindTheMissingNumberTest {

  private FindTheMissingNumber findMissingNumber;

  @Before public void setUp() {
    findMissingNumber = new FindTheMissingNumber();
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptNullInstances() {
    findMissingNumber.find(null);
  }

  @Test(expected = IllegalArgumentException.class) public void shouldNotAcceptEmptyArrays() {
    findMissingNumber.find(new int[0]);
  }

  @Test public void shouldFindMissingNumber() {
    int[] numbers = { 0, 1, 2, 4 };

    int missingNumber = findMissingNumber.find(numbers);

    assertEquals(3, missingNumber);
  }
}

Add some test to problem 72

Add some test to problem 72


/*
 * Copyright 2015 Open Networking Laboratory
 *
 * 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.onosproject.net;

import com.google.common.testing.EqualsTester;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * Test for OchSignal.
 */
public class OchSignalTest {

    private final Lambda och1 = Lambda.ochSignal(GridType.DWDM, ChannelSpacing.CHL_100GHZ, 1, 1);
    private final Lambda sameOch1 = Lambda.ochSignal(GridType.DWDM, ChannelSpacing.CHL_100GHZ, 1, 1);
    private final Lambda och2 = Lambda.ochSignal(GridType.CWDM, ChannelSpacing.CHL_6P25GHZ, 4, 1);
    private final Lambda sameOch2 = Lambda.ochSignal(GridType.CWDM, ChannelSpacing.CHL_6P25GHZ, 4, 1);

    @Test
    public void testEquality() {
        new EqualsTester()
                .addEqualityGroup(och1, sameOch1)
                .addEqualityGroup(och2, sameOch2)
                .testEquals();
    }
}

Add missing test class for OchSignal

Add missing test class for OchSignal

Change-Id: I2cbd0365c31e7328bea8f11b8d2dfc7bdeb79f21


/*******************************************************************************
 * Mission Control Technologies, Copyright (c) 2009-2012, United States Government
 * as represented by the Administrator of the National Aeronautics and Space
 * Administration. All rights reserved.
 *
 * The MCT platform is 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.
 *
 * MCT includes source code licensed under additional open source licenses. See
 * the MCT Open Source Licenses file included with this distribution or the About
 * MCT Licenses dialog available at runtime from the MCT Help menu for additional
 * information.
 *******************************************************************************/
package gov.nasa.arc.mct.scenario.actions;

import gov.nasa.arc.mct.components.AbstractComponent;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Collection;

import javax.swing.SwingWorker;

public class CSVExportWorker extends SwingWorker<Boolean, Void> {
	private Collection<AbstractComponent> components;
	private File file;
	private IOException ioe;

	public CSVExportWorker(Collection<AbstractComponent> components, File file) {
		super();
		this.components = components;
		this.file = file;

		if (components == null || file == null || components.isEmpty()) {
			throw new IllegalArgumentException();
		}
	}

	@Override
	protected Boolean doInBackground() throws Exception {
		setProgress(0);

		CSVRenderer r = new CSVRenderer(components);

		int rowCount = r.getRowCount();

		Writer w = null;
		boolean success = true;
		try {
			w = new FileWriter(file);
			w.write(r.renderHeaders());
			for (int i = 0; i < rowCount; i++) {
				setProgress((i * 100) / rowCount);
				w.write(r.renderRow(i));
			}
		} catch (IOException ioe) {
			success = false;
			this.ioe = ioe;
		} finally {
			if (w != null) {
				try {
					w.close();
				} catch (IOException ioe) {
					success = false;
					this.ioe = ioe;
				}
			}
		}

		setProgress(100);

		return success;
	}

	public IOException getException() {
		return ioe;
	}
}

Add worker to export CSV in background

[Scenario] Add worker to export CSV in background


package com.mesosphere.sdk.state;

import com.mesosphere.sdk.storage.MemPersister;
import com.mesosphere.sdk.storage.Persister;
import org.junit.Test;

import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.is;

/**
 * Tests for {@link StateStoreUtils}.
 */
public class StateStoreUtilsTest {

    @Test
    public void emptyStateStoreReturnsEmptyArray () {
        final StateStore stateStore = new DefaultStateStore(new MemPersister());

        byte[] result = StateStoreUtils.fetchPropertyOrEmptyArray(stateStore, "UNDEFINED");

        assertThat(result.length, is(0));
    }

    @Test
    public void unmatchedKeyReturnsEmptyArray() {
        final StateStore stateStore = new DefaultStateStore(new MemPersister());
        stateStore.storeProperty("DEFINED", "VALUE".getBytes());

        byte[] result = StateStoreUtils.fetchPropertyOrEmptyArray(stateStore, "UNDEFINED");

        assertThat(result.length, is(0));
    }

    @Test
    public void matchedKeyReturnsValue() {
        final StateStore stateStore = new DefaultStateStore(new MemPersister());
        stateStore.storeProperty("DEFINED", "VALUE".getBytes());

        byte[] result = StateStoreUtils.fetchPropertyOrEmptyArray(stateStore, "DEFINED");

        assertThat(result, is("VALUE".getBytes()));
    }

}

Add unit tests for fetchPropertyOrEmptyArray


package uk.gov.register.functional;

import io.dropwizard.testing.ConfigOverride;
import org.junit.Rule;
import org.junit.Test;
import uk.gov.register.functional.app.RegisterRule;

import javax.ws.rs.core.Response;

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.junit.Assert.assertThat;
import static uk.gov.register.functional.db.TestDBSupport.testEntryDAO;
import static uk.gov.register.functional.db.TestDBSupport.testItemDAO;

public class DeleteRegisterDataFunctionalTest {
    @Rule
    public final RegisterRule register = new RegisterRule("register",
            ConfigOverride.config("enableRegisterDataDelete", "true"));

    @Test
    public void deleteRegisterData_deletesAllDataFromDb() throws Exception {
        String item1 = "{\"register\":\"register1\",\"text\":\"Register1 Text\", \"phase\":\"alpha\"}";
        String item2 = "{\"register\":\"register2\",\"text\":\"Register2 Text\", \"phase\":\"alpha\"}";

        Response mintResponse = register.mintLines(item1 + "\n" + item2);
        assertThat(mintResponse.getStatus(), equalTo(204));
        assertThat(testItemDAO.getItems(), hasSize(2));
        assertThat(testEntryDAO.getAllEntries(), hasSize(2));

        Response deleteResponse = register.deleteRequest("/delete-register-data");

        assertThat(deleteResponse.getStatus(), equalTo(200));
        assertThat(testItemDAO.getItems(), is(empty()));
        assertThat(testEntryDAO.getAllEntries(), is(empty()));
    }
}

Test if data is really deleted after calling /delete-register-data endpoint


package com.reactnativenavigation.react;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.StrictMode;
import android.support.annotation.NonNull;

import com.reactnativenavigation.NavigationApplication;
import com.reactnativenavigation.utils.ViewUtils;

import java.io.IOException;
import java.net.URL;

public class JsDevImageLoader {

    public static Drawable loadIcon(String iconDevUri) {
        try {
            StrictMode.ThreadPolicy threadPolicy = StrictMode.getThreadPolicy();
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());

            Drawable drawable = tryLoadIcon(iconDevUri);

            StrictMode.setThreadPolicy(threadPolicy);
            return drawable;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @NonNull
    private static Drawable tryLoadIcon(String iconDevUri) throws IOException {
        URL url = new URL(iconDevUri);
        Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
        final int dimensions = (int) ViewUtils.convertDpToPixel(48);
        // TODO: fix hard coded dimensions -add options to decodeStream
        bitmap = Bitmap.createScaledBitmap(bitmap, dimensions, dimensions, false);
        return new BitmapDrawable(NavigationApplication.instance.getResources(), bitmap);
    }

}

package com.reactnativenavigation.react;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.StrictMode;
import android.support.annotation.NonNull;

import com.reactnativenavigation.NavigationApplication;

import java.io.IOException;
import java.net.URL;

public class JsDevImageLoader {

    public static Drawable loadIcon(String iconDevUri) {
        try {
            StrictMode.ThreadPolicy threadPolicy = StrictMode.getThreadPolicy();
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().permitNetwork().build());

            Drawable drawable = tryLoadIcon(iconDevUri);

            StrictMode.setThreadPolicy(threadPolicy);
            return drawable;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @NonNull
    private static Drawable tryLoadIcon(String iconDevUri) throws IOException {
        URL url = new URL(iconDevUri);
        Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());
        return new BitmapDrawable(NavigationApplication.instance.getResources(), bitmap);
    }
}

Remove hardcoded TitleBar icon dimensions


/*
 * Copyright 2015 Real Logic 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 uk.co.real_logic.agrona;

/**
 * Grouping of language level utilities to make programming in Java more convenient.
 */
public class LangUtil
{
    /**
     * Rethrow an {@link java.lang.Exception} preserving the stack trace but making it unchecked.
     *
     * @param ex to be rethrown and unchecked.
     */
    public static void rethrowUnchecked(final Exception ex)
    {
        LangUtil.<RuntimeException>rethrow(ex);
    }

    @SuppressWarnings("unchecked")
    private static <T extends Exception> void rethrow(final Exception ex)
        throws T
    {
        throw (T)ex;
    }
}

[Java]: Add availability to rethrow an exception as unchecked and preserving the stack trace without wrapping.


package fi.vincit.multiusertest.runner;

import fi.vincit.multiusertest.test.AbstractUserRoleIT;
import fi.vincit.multiusertest.util.UserIdentifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;

public class BlockMultiUserTestClassRunner extends BlockJUnit4ClassRunner {

    private UserIdentifier creatorIdentifier;
    private UserIdentifier userIdentifier;

    public BlockMultiUserTestClassRunner(Class<?> clazz, UserIdentifier creatorIdentifier, UserIdentifier userIdentifier) throws InitializationError {
        super(clazz);
        this.creatorIdentifier = creatorIdentifier;
        this.userIdentifier = userIdentifier;
    }

    @Override
    protected String testName(FrameworkMethod method) {
        return String.format("%s: %s", method.getName(), getIdentifierDescription());
    }

    @Override
    protected String getName() {
        return String.format("%s: %s", getTestClass().getName(), getIdentifierDescription());
    }

    private String getIdentifierDescription() {
        return String.format("creator = %s; user = %s", creatorIdentifier, userIdentifier);
    }

    @Override
    protected Object createTest() throws Exception {
        Object testInstance = super.createTest();
        if (testInstance instanceof AbstractUserRoleIT) {
            AbstractUserRoleIT roleItInstance = (AbstractUserRoleIT) testInstance;
            roleItInstance.setUsers(creatorIdentifier, userIdentifier);
            return roleItInstance;
        } else {
            throw new IllegalStateException("Test class must be of type " + AbstractUserRoleIT.class.getSimpleName());
        }
    }

}

Add JUnit Block runner support

Add JUnit Block runner support


package net.imagej.ops.views;

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

import net.imagej.ops.Contingent;
import net.imagej.ops.view.ViewOps;
import net.imagej.ops.view.ViewOps.Subsample;
import net.imglib2.RandomAccessible;
import net.imglib2.view.SubsampleView;
import net.imglib2.view.Views;

@Plugin(type = ViewOps.Subsample.class, name = ViewOps.Subsample.NAME)
public class SubsampleStepsForDims<T> extends AbstractView<RandomAccessible<T>, SubsampleView<T>> implements
		Subsample<RandomAccessible<T>, SubsampleView<T>>, Contingent {

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

	@Override
	public SubsampleView<T> compute(RandomAccessible<T> input) {
		return Views.subsample(input, steps);
	}

	@Override
	public boolean conforms() {
		return getInput().numDimensions() <= steps.length;
	}

}

Add implementation of Subsample interface.


package com.github.pedrovgs.problem75;

import com.github.pedrovgs.sortingalgorithm.SortingAlgorithm;

/**
 * Given an array full of integers implement a selection sort algorithm to sort the content inside
 * the array.
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class SelectionSort extends SortingAlgorithm {

  @Override public void sort(int[] numbers) {

  }
}

Add statement to problem 75

Add statement to problem 75


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

/**
 *
 * @author pemi
 */
public class SpeedmentVersion {

    private static final String IMPLEMENTATION_TITLE = "Speedment";
    private static final String IMPLEMENTATION_VENDOR = "Speedment Inc."; // "Speedment, Inc." difficult to enter into POM because of ','
    private static final String IMPLEMENTATION_VERSION = "2.0.0-EA2-SNAPSHOT";

//    private static final String SPECIFICATION_TITLE = "Speedment";
//    private static final String SPECIFICATION_VENDOR = "Speedment, Inc.";
//    private static final String SPECIFICATION_VERSION = "2.0.0";

    private SpeedmentVersion() {
    }

    public static String getImplementationTitle() {
        return IMPLEMENTATION_TITLE;
    }

    public static String getImplementationVendor() {
        return IMPLEMENTATION_VENDOR;

    }

    public static String getImplementationVersion() {
        return IMPLEMENTATION_VERSION;
    }

//    public static String getSpecificationTitle() {
//        return SPECIFICATION_TITLE;
//    }
//
//    public static String getSpecificationVendor() {
//        return SPECIFICATION_VENDOR;
//    }
//
//    public static String getSpecificationVersion() {
//        return SPECIFICATION_VERSION;
//    }

}

Add separate handling of version

Add separate handling of version


package pete.metrics.adaptability.elements;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

class DetectionOnlyElements {

	private final Collection<AdaptableElement> elements;

	public DetectionOnlyElements() {
		elements = new HashSet<>();
	}

	private void addToSet(AdaptableElement element) {
		boolean success = elements.add(element);
		if (!success) {
			throw new IllegalStateException(element.getName()
					+ " was tried to be added twice");
		}
	}

	public List<String> getElementNames() {
		List<String> result = new ArrayList<>(elements.size());
		elements.forEach(element -> result.add(element.getName()));
		return result;
	}

	public List<AdaptableElement> getElements() {
		List<AdaptableElement> result = new ArrayList<>(elements.size());
		elements.forEach(element -> result.add(element));
		return result;
	}

	public Map<String, AdaptableElement> getElementsByName() {
		HashMap<String, AdaptableElement> result = new HashMap<>();
		elements.forEach(element -> result.put(element.getName(), element));
		return result;
	}

}

Add collection of elements that should only be detected


package org.marsik.elshelves.backend.test.unit;

import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doReturn;

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

import org.junit.Before;
import org.junit.Test;
import org.marsik.elshelves.backend.entities.Box;
import org.marsik.elshelves.backend.entities.IdentifiedEntity;
import org.marsik.elshelves.backend.entities.OwnedEntity;
import org.marsik.elshelves.backend.entities.Source;
import org.marsik.elshelves.backend.entities.Type;
import org.marsik.elshelves.backend.entities.User;
import org.marsik.elshelves.backend.repositories.BaseIdentifiedEntityRepository;
import org.marsik.elshelves.backend.repositories.BaseOwnedEntityRepository;
import org.marsik.elshelves.backend.repositories.BoxRepository;
import org.marsik.elshelves.backend.repositories.LotRepository;
import org.marsik.elshelves.backend.repositories.PurchaseRepository;
import org.marsik.elshelves.backend.repositories.SourceRepository;
import org.marsik.elshelves.backend.repositories.TransactionRepository;
import org.marsik.elshelves.backend.repositories.TypeRepository;
import org.marsik.elshelves.backend.services.LotServiceImpl;
import org.marsik.elshelves.backend.services.UuidGenerator;
import org.marsik.elshelves.backend.services.UuidGeneratorImpl;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.springframework.data.repository.Repository;

public class LotDeliveryTest extends BaseUnitTest {
    @InjectMocks
    LotServiceImpl service;

    @Mock
    EntityManager entityManager;

    @Mock
    TypeRepository typeRepository;

    @Mock
    TransactionRepository transactionRepository;

    @Mock
    PurchaseRepository purchaseRepository;

    @Mock
    SourceRepository sourceRepository;

    @Mock
    LotRepository lotRepository;

    @Mock
    BoxRepository boxRepository;

    @Spy
    UuidGenerator uuidGenerator = new UuidGeneratorImpl();

    private User user;

    @Before
    public void setUp() throws Exception {
        user = randomIdObj(User.class);
    }

    @Test
    public void testTypeBasedDelivery() throws Exception {
        Type type = randomIdObj(Type.class);
        Box box = randomIdObj(Box.class);
        Source source = randomIdObj(Source.class);
        source.setName("SOURCE");

        alwaysReturn(typeRepository, type);
        alwaysReturn(boxRepository, box);
        alwaysReturn(sourceRepository, source);

        service.deliverAdHoc(source, type, box, 10L, null, user);
    }

    private <T extends IdentifiedEntity> T randomIdObj(Class<T> cls) throws IllegalAccessException, InstantiationException {
        T o = cls.newInstance();
        o.setId(UUID.randomUUID());
        return o;
    }

    private <T extends OwnedEntity> void alwaysReturn(BaseOwnedEntityRepository<T> repository, T value) {
        doReturn(value).when(repository).findById(any());
        value.setOwner(user);
    }
}

Add basic unit test for ad hoc lot delivery


package com.google.sps.utils;

import com.google.cloud.dialogflow.v2.QueryInput;
import com.google.cloud.dialogflow.v2.QueryResult;
import com.google.cloud.dialogflow.v2.SessionName;
import com.google.cloud.dialogflow.v2.SessionsClient;
import java.io.IOException;
import com.google.cloud.dialogflow.v2.TextInput;
import com.google.cloud.dialogflow.v2.DetectIntentResponse;

/**
 * DialogFlow API Detects Intent with input text.
**/

public class TextUtils {
  public static QueryResult detectIntentStream(String text) {
    QueryResult queryResult = null;

    try (SessionsClient sessionsClient = SessionsClient.create()) {
      // Set the session name using the sessionId (UUID) and projectID (my-project-id)
      SessionName session = SessionName.of("fair-syntax-280601", "1");
        String languageCode = "en-US";

        // Set the text and language code (en-US) for the query
        TextInput.Builder textInput =
            TextInput.newBuilder().setText(text).setLanguageCode(languageCode);

        // Build the query with the TextInput
        QueryInput queryInput = QueryInput.newBuilder().setText(textInput).build();

        // Performs the detect intent request
        DetectIntentResponse response = sessionsClient.detectIntent(session, queryInput);

        // Display the query result
        queryResult = response.getQueryResult();

        System.out.println("====================");
        System.out.format("Query Text: '%s'\n", queryResult.getQueryText());
        System.out.format("Detected Intent: %s (confidence: %f)\n",
            queryResult.getIntent().getDisplayName(), queryResult.getIntentDetectionConfidence());
        System.out.format("Fulfillment Text: '%s'\n", queryResult.getFulfillmentText());

    } catch (IOException e) {
      e.printStackTrace();
    }
    return queryResult;
  }
}

Add TextUtil class to retrieve QueryResult from Dialogflow


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

package org.opendaylight.ovsdb.openstack.netvirt;

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

import org.junit.Test;
import org.opendaylight.ovsdb.openstack.netvirt.api.Constants;

/**
 * Unit test for {@link NodeConfiguration}
 */
public class NodeConfigurationTest {

    @Test
    public void testNodeConfiguration() {
        NodeConfiguration nodeConf = new NodeConfiguration();

        assertEquals("Error, did not populate the internal vlan queue correctly", Constants.MAX_VLAN - 1, nodeConf.getInternalVlans().size());
        assertNotNull("Error, tenant vlan map has not been initialized", nodeConf.getTenantVlanMap());
    }
}

Add JUnit testing for NodeConfiguration class.

Change-Id: Iddf2dcfb3c6c24acf473a16ab055751182f66c00
Signed-off-by: Alexis de Talhouët <3f85d13b1d0fb141169e8f22f55d7ee87dcd5f00@inocybe.com>


package com.jshoresdevelopment.conversioncalculator;

import java.text.DecimalFormat;

public class TemperatureConversions {
    private static DecimalFormat decimalFormat;

    /** Returns converted values, by calling appropriate conversions */
    public static String convert(String fromUnit, String fromValue, String toUnit) {
        decimalFormat = new DecimalFormat("#.00#");
        switch (fromUnit) {
            case "Celsius":
                return fromCelsius(fromValue, toUnit);
            case "Kelvin":
                return fromKelvin(fromValue, toUnit);
            case "Fahrenheit":
                return fromFahrenheit(fromValue, toUnit);
            default:
                return fromValue;
        }
    }

    /** Returns a double parsed from string */
    private static double toDouble(String value) {
        return Double.parseDouble(value);
    }

    /** Returns conversions from Celsius to other units */
    private static String fromCelsius(String fromValue, String toUnit) {
        double returnValue;
        switch (toUnit) {
            case "Fahrenheit":
                returnValue = (toDouble(fromValue) * 1.8) + 32;
                return String.valueOf(decimalFormat.format(returnValue));
            case "Kelvin":
                returnValue = toDouble(fromValue) + 273.15;
                return String.valueOf(decimalFormat.format(returnValue));
            default:
                return String.valueOf(decimalFormat.format(toDouble(fromValue)));
        }
    }

    /** Returns conversions from Kelvin to other units */
    private static String fromKelvin(String fromValue, String toUnit) {
        double returnValue;
        switch (toUnit) {
            case "Fahrenheit":
                returnValue = (((toDouble(fromValue) - 273.15) * 1.8) + 32);
                return String.valueOf(decimalFormat.format(returnValue));
            case "Celsius":
                returnValue = toDouble(fromValue) - 273.15;
                return String.valueOf(decimalFormat.format(returnValue));
            default:
                return String.valueOf(decimalFormat.format(toDouble(fromValue)));
        }
    }

    /** Returns conversions from Fahrenheit to other units */
    private static String fromFahrenheit(String fromValue, String toUnit) {
        double returnValue;
        switch (toUnit) {
            case "Kelvin":
                returnValue = ((toDouble(fromValue) - 32) / 1.8) + 273.15;
                return String.valueOf(decimalFormat.format(returnValue));
            case "Celsius":
                returnValue = (toDouble(fromValue) - 32) / 1.8;
                return String.valueOf(decimalFormat.format(returnValue));
            default:
                return String.valueOf(decimalFormat.format(toDouble(fromValue)));
        }
    }
}

Create class to handle temperature conversions.


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

import java.util.Set;

import org.apache.commons.pool2.impl.TestGenericObjectPool.SimpleFactory;
import org.junit.Assert;
import org.junit.Test;

public class TestDefaultPooledObjectInfo {

    @Test
    public void testTiming() throws Exception {
        GenericObjectPool<String> pool =
                new GenericObjectPool<String>(new SimpleFactory());

        long t1 = System.currentTimeMillis();

        Thread.sleep(50);
        String s1 = pool.borrowObject();
        Thread.sleep(50);

        long t2 = System.currentTimeMillis();

        Thread.sleep(50);
        pool.returnObject(s1);
        Thread.sleep(50);

        long t3 = System.currentTimeMillis();

        Thread.sleep(50);
        s1 = pool.borrowObject();
        Thread.sleep(50);

        long t4 = System.currentTimeMillis();

        Set<DefaultPooledObjectInfo> strings = pool.listAllObjects();

        Assert.assertEquals(1, strings.size());

        DefaultPooledObjectInfo s1Info = strings.iterator().next();

        Assert.assertTrue(s1Info.getCreateTime() > t1);
        Assert.assertTrue(s1Info.getCreateTime() < t2);

        Assert.assertTrue(s1Info.getLastReturnTime() > t2);
        Assert.assertTrue(s1Info.getLastReturnTime() < t3);

        Assert.assertTrue(s1Info.getLastBorrowTime() > t3);
        Assert.assertTrue(s1Info.getLastBorrowTime() < t4);
    }

    @Test
    public void testGetPooledObjectType() throws Exception {
        GenericObjectPool<String> pool =
                new GenericObjectPool<String>(new SimpleFactory());

        pool.borrowObject();

        Set<DefaultPooledObjectInfo> strings = pool.listAllObjects();

        Assert.assertEquals(1, strings.size());

        DefaultPooledObjectInfo s1Info = strings.iterator().next();

        Assert.assertEquals(String.class.getName(),
                s1Info.getPooledObjectType());
    }

    @Test
    public void testGetPooledObjectToString() throws Exception {
        GenericObjectPool<String> pool =
                new GenericObjectPool<String>(new SimpleFactory());

        String s1 = pool.borrowObject();

        Set<DefaultPooledObjectInfo> strings = pool.listAllObjects();

        Assert.assertEquals(1, strings.size());

        DefaultPooledObjectInfo s1Info = strings.iterator().next();

        Assert.assertEquals(s1, s1Info.getPooledObjectToString());
    }
}

Add some tests for DefaultPooledObjectInfo that currently has zero coverage.

git-svn-id: a66ef3f0e6c00b14098e182847b4bd646263fa09@1538412 13f79535-47bb-0310-9956-ffa450edef68


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

public @interface ExternalHandler {
}

Fix FELIX-3461 - Issue with collected metadata and manipulation metadata on re-manipulation

* Fix the constructor argument shift by not moving the annotations
* Fix the method name when it is a manipulated method
* Cleanup the manipulation metadata

(forgot to add files in my first AND second commits)

git-svn-id: e057f57e93a604d3b43d277ae69bde5ebf332112@1327155 13f79535-47bb-0310-9956-ffa450edef68


/**
 *
 * Copyright © 2018 Paul Schaub
 *
 * 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.jivesoftware.smack.test.util;

import java.io.File;

public class FileTestUtil {

    /**
     * Returns a {@link File} pointing to a temporary directory. On unix like systems this might be {@code /tmp}
     * for example.
     * If {@code suffix} is not null, the returned file points to {@code <temp>/suffix}.
     *
     * @param suffix optional path suffix
     * @return temp directory
     */
    public static File getTempDir(String suffix) {
        String temp = System.getProperty("java.io.tmpdir");
        if (temp == null) {
            temp = "tmp";
        }

        if (suffix == null) {
            return new File(temp);
        } else {
            return new File(temp, suffix);
        }
    }
}

Add utility method to get temp directory


/*
  $Id$

  Copyright (C) 2009 Virginia Tech.
  All rights reserved.

  SEE LICENSE FOR MORE INFORMATION

  Author:  Middleware
  Email:   middleware@vt.edu
  Version: $Revision$
  Updated: $Date$
*/
package edu.vt.middleware.servlet.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * Sets the request and/or response character encoding based on the presence
 * of either or both of the following init params, {@link #REQUEST_CHARSET_NAME}
 * {@link #RESPONSE_CHARSET_NAME}.
 *

 * NOTE: this filter should be as close to the beginning of
 * the filter chain as possible.  Any filters that obtain request parameters,
 * e.g. request.getParameter(...), prior to setting the character
 * set via this filter will use the platform default character set.
 *
 * @author Middleware
 * @version $Revision$
 *
 */
public class CharacterEncodingFilter implements Filter
{
  /**
   * Name of init param for setting request character encoding.
   * The value should be a valid Java character set name, e.g. UTF-8.
   */
  public static final String REQUEST_CHARSET_NAME = "requestCharsetName";

  /**
   * Name of init param for setting response character encoding.
   * The value should be a valid Java character set name, e.g. UTF-8.
   */
  public static final String RESPONSE_CHARSET_NAME = "responseCharsetName";

  /** Request character set name */
  private String requestCharsetName;

  /** Response character set name */
  private String responseCharsetName;

  /** {@inheritDoc} */
  public void init(final FilterConfig filterConfig) throws ServletException
  {
    if (filterConfig.getInitParameter(REQUEST_CHARSET_NAME) != null) {
      requestCharsetName = filterConfig.getInitParameter(REQUEST_CHARSET_NAME);
    }
    if (filterConfig.getInitParameter(RESPONSE_CHARSET_NAME) != null) {
      responseCharsetName =
        filterConfig.getInitParameter(RESPONSE_CHARSET_NAME);
    }
  }

  /** {@inheritDoc} */
  public void doFilter(
      final ServletRequest request,
      final ServletResponse response,
      final FilterChain chain) throws IOException, ServletException
  {
    if (requestCharsetName != null) {
      request.setCharacterEncoding(requestCharsetName);
    }
    if (responseCharsetName != null) {
      response.setCharacterEncoding(responseCharsetName);
    }
    chain.doFilter(request, response);
  }

  /** {@inheritDoc} */
  public void destroy() {}
}

Add filter to allow changing character encoding of HTTP request/response.


package info.u_team.u_team_core.data;

import java.io.IOException;
import java.util.*;
import java.util.function.Supplier;
import java.util.stream.Collectors;

import com.google.gson.JsonObject;

import info.u_team.u_team_core.util.TriConsumer;
import net.minecraft.data.DirectoryCache;
import net.minecraft.util.*;
import net.minecraftforge.common.loot.*;

public abstract class CommonGlobalLootModifiersProvider extends CommonProvider {

	protected boolean replace;

	public CommonGlobalLootModifiersProvider(GenerationData data) {
		super(data);
	}

	@Override
	public void act(DirectoryCache cache) throws IOException {
		final Map<String, Tuple<GlobalLootModifierSerializer<?>, JsonObject>> serializers = new TreeMap<>();

		registerGlobalLootModifiers((modifier, serializerSupplier, instance) -> {
			final GlobalLootModifierSerializer<IGlobalLootModifier> serializer = serializerSupplier.get();
			serializers.put(modifier, new Tuple<>(serializer, serializer.write(instance)));
		});

		final List<String> entries = serializers.entrySet().stream().map(entry -> {
			final String name = entry.getKey();
			final Tuple<GlobalLootModifierSerializer<?>, JsonObject> tuple = entry.getValue();
			final JsonObject json = tuple.getB();

			json.addProperty("type", tuple.getA().getRegistryName().toString());

			try {
				write(cache, json, resolveModData().resolve("loot_modifiers").resolve(name + ".json"));
			} catch (final IOException ex) {
				LOGGER.error(marker, "Could not write data.", ex);
			}
			return new ResourceLocation(modid, name);
		}).map(ResourceLocation::toString).collect(Collectors.toList());

		final JsonObject json = new JsonObject();
		json.addProperty("replace", replace);
		json.add("entries", GSON.toJsonTree(entries));

		try {
			write(cache, json, path.resolve("data").resolve("forge").resolve("loot_modifiers").resolve("global_loot_modifiers.json"));
		} catch (final IOException ex) {
			LOGGER.error(marker, "Could not write data.", ex);
		}
	}

	protected void replacing() {
		replace = true;
	}

	protected abstract <T extends IGlobalLootModifier> void registerGlobalLootModifiers(TriConsumer<String, Supplier<GlobalLootModifierSerializer<T>>, T> consumer);

	@Override
	public String getName() {
		return "Global-Loot-Modifiers";
	}

}

Implement common global loot modifier provider


package com.suse.saltstack.netapi.utils;

import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

import static org.junit.Assert.assertEquals;

/**
 * SaltStackClientUtils class unit-tests.
 */
public class SaltStackClientUtilsTest {

    @Test
    public void testCloseQuietly() throws IOException {
        // Mocked InputStream that throws IOException when closed more than once.
        InputStream is = new InputStream() {
            private boolean closed = false;

            @Override
            public int read() throws IOException {
                return 0;
            }

            @Override
            public void close() throws IOException {
                if (closed) {
                    throw new IOException("Stream already closed");
                }
                closed = true;
            }
        };

        // Close valid stream
        SaltStackClientUtils.closeQuietly(is);

        // Close already closed stream, don't throw exception
        SaltStackClientUtils.closeQuietly(is);

        // Close null stream, don't throw exception
        SaltStackClientUtils.closeQuietly(null);
    }

    @Test
    public void testStringToStream() {
        final String TEST_STRING = "SUSE";
        InputStream is = SaltStackClientUtils.stringToStream(TEST_STRING);
        Scanner scanner = new Scanner(is);
        String result = scanner.nextLine();
        assertEquals("Result doesn't match test string", result, TEST_STRING);
    }

    @Test
    public void testStreamToString() {
        final String TEST_STRING = "SUSE";
        String result = SaltStackClientUtils.streamToString(
                new ByteArrayInputStream(TEST_STRING.getBytes()));
        assertEquals("Result doesn't match test string", result, TEST_STRING);
    }
}

Add testcases for SaltStackClientUtils class


package org.jvirtanen.philadelphia.fixt11;

/**
 * Message types for FIXT 1.1.
 */
public class FIXT11MsgTypes {

    public static final char Heartbeat     = '0';
    public static final char TestRequest   = '1';
    public static final char ResendRequest = '2';
    public static final char Reject        = '3';
    public static final char SequenceReset = '4';
    public static final char Logout        = '5';
    public static final char Logon         = 'A';
    public static final char XMLnonFIX     = 'n';

    private FIXT11MsgTypes() {
    }

}

Add message types for FIXT 1.1

Add message types for FIXT 1.1


public class RemoveDuplicatesFromString {
	public static void main(String[] args) {
		RemoveDuplicatesFromString rsd = new RemoveDuplicatesFromString();
		String input = "Tree Traversal";
		System.out.println(rsd.getUniqueString(input));
	}

	public String getUniqueString(String input) {
		boolean[] isUsed = new boolean[256];
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < input.length(); i++) {
			int position = input.charAt(i);
			if (!isUsed[position]) {
				sb.append(input.charAt(i));
				isUsed[position] = true;
			}
		}
		return sb.toString();
	}
}

Remove duplicates from string Java.

Remove duplicates from string Java.


package org.sakaiproject.entity.api;

/**
 * Services which implement ContentExistsAware declare that they are able to determine if they contain content for the site they are in.
 * Note that services must also be registered EntityProducers.
 *
 * @since 11.0
 * @author Steve Swinsburg (steve.swinsburg@gmail.com)
 */
public interface ContentExistsAware {

	/**
	 * Does this tool contain content in this site?
	 *
	 * @param siteId the siteId to use when checking if content exists
	 */
	public boolean hasContent(String siteId);

}

Add marker interface that tools can implement to show that they know if they have content or not

Issue: SAK-29159


package com.box.l10n.mojito.security;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * Contains the configuration related to Active directory authentication.
 *
 * @author jaurambault
 */
@Component
@ConfigurationProperties(prefix = "l10n.security.ad")
public class ActiveDirectoryConfig {

    String url;
    String domain;
    String rootDn;

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getDomain() {
        return domain;
    }

    public void setDomain(String domain) {
        this.domain = domain;
    }

    public String getRootDn() {
        return rootDn;
    }

    public void setRootDn(String rootDn) {
        this.rootDn = rootDn;
    }

}

Add class to read ActiveDirectory config from properties


/*
 * JsonGeneratorVisitor.java
 *
 */

package de.uni_stuttgart.vis.vowl.owl2vowl.export;

import de.uni_stuttgart.vis.vowl.owl2vowl.model.BaseEntity;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.edges.BaseEdge;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.edges.properties.*;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.BaseNode;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.classes.*;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes.BaseDatatype;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes.RdfsDatatype;
import de.uni_stuttgart.vis.vowl.owl2vowl.model.nodes.datatypes.RdfsLiteral;

import java.util.Map;

/**
 *
 */
public interface JsonGeneratorVisitor {
	public Map<String, Object> getEntityJson();

	public Map<String, Object> getEntityAttributes();

	public boolean isFailure();

	public void visit(BaseEntity entity);

	public void visit(BaseEdge entity);

	public void visit(BaseProperty entity);

	public void visit(DisjointProperty entity);

	public void visit(OwlDatatypeProperty entity);

	public void visit(OwlObjectProperty entity);

	public void visit(SubClassProperty entity);

	public void visit(BaseNode entity);

	public void visit(BaseClass entity);

	public void visit(ExternalClass entity);

	public void visit(OwlClass entity);

	public void visit(OwlComplementOf entity);

	public void visit(OwlDeprecatedClass entity);

	public void visit(OwlEquivalentClass entity);

	public void visit(OwlIntersectionOf entity);

	public void visit(OwlThing entity);

	public void visit(OwlUnionOf entity);

	public void visit(RdfsClass entity);

	public void visit(RdfsResource entity);

	public void visit(SpecialClass entity);

	public void visit(BaseDatatype entity);

	public void visit(RdfsDatatype entity);

	public void visit(RdfsLiteral entity);
}

Add visitor interface for json generator.


import java.util.Scanner;

public class Main {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);

        double a, b, c, s = 0.0;

        while (sc.hasNextDouble()) {
            a = sc.nextDouble();
            b = sc.nextDouble();
            c = sc.nextDouble();

            s += b * c;
        }

        System.out.printf("VALOR A PAGAR: R$ %.2f\n", s);

        sc.close();
    }
}

Solve Simple Calculate in java

Solve Simple Calculate in java


package org.hive2hive.core.tomp2p;

import java.util.Arrays;

import net.tomp2p.peers.Number160;

import org.hive2hive.core.H2HJUnitTest;
import org.hive2hive.core.network.NetworkTestUtil;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

public class Number160Test extends H2HJUnitTest {

	@BeforeClass
	public static void initTest() throws Exception {
		testClass = Number160Test.class;
		beforeClass();
	}

	@Test
	public void testHashes() {
		// test two random literals
		String unrelated1 = NetworkTestUtil.randomString();
		Number160 num1 = Number160.createHash(unrelated1);
		String unrelated2 = NetworkTestUtil.randomString();
		Number160 num2 = Number160.createHash(unrelated2);

		Assert.assertFalse(Arrays.equals(num1.toByteArray(), num2.toByteArray()));

		// test two close literals
		Number160 ua = Number160.createHash("User A");
		Number160 ub = Number160.createHash("User B");
		Assert.assertFalse(Arrays.equals(ua.toByteArray(), ub.toByteArray()));

	}

	@AfterClass
	public static void cleanAfterClass() {
		afterClass();
	}
}

Add test for Number160 (hashing seemed suspicious)

Signed-off-by: Nico Rutishauser <a8643e0e26d5ead82e73aae64966ca144f152d8a@hotmail.ch>


package com.uwetrottmann.wpdisplay.model;

/**
 * Holder object for heat pump controller status data.
 */
public class StatusData {

    /**
     * Maximum length of data supported. Sent status data is actually 183 bytes long, but we don't
     * care about the rest, yet.
     */
    public final static int LENGTH_BYTES = 80;

    interface Index {
        /**
         * All following are temparature values, factor 10, Celsius.
         */
        int TEMP_OUTGOING = 10;
        int TEMP_RETURN = 11;
        int TEMP_RETURN_SHOULD = 12;
        int TEMP_OUTDOORS = 15;
        int TEMP_WATER = 17;
        int TEMP_WATER_SHOULD = 18;
        int TEMP_SOURCE_IN = 19;
        int TEMP_SOURCE_OUT = 20;

        /**
         * All following are time values, Seconds.
         */
        int TIME_PUMP_ACTIVE = 67;
        int TIME_REST = 71;
        int TIME_COMPRESSOR_NOOP = 73;
        int TIME_RETURN_LOWER = 74;
        int TIME_RETURN_HIGHER = 75;
    }

    private int[] rawData;

    public StatusData(int[] rawData) {
        if (rawData.length != LENGTH_BYTES) {
            throw new IllegalArgumentException(
                    "array is not size " + LENGTH_BYTES + " but was " + rawData.length);
        }
        this.rawData = rawData;
    }

    public double getTemperatureOutdoors() {
        return getTemperature(Index.TEMP_OUTDOORS);
    }

    private double getTemperature(int index) {
        int tempRaw = getValueAt(index);
        return tempRaw / 10.0;
    }

    private int getValueAt(int index) {
        if (index + 1 > rawData.length) {
            throw new IllegalArgumentException(
                    "index must be from 0 to array length " + rawData.length);
        }

        return rawData[index];
    }
}

Add holder class for status data.

Add holder class for status data.


package org.jdesktop.beans.editors;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

/**
 * A demo program to showcase {@link PaintPicker}.
 *
 * @author Karl Schaefer
 */
@SuppressWarnings("all")
public class ImagePickerDemo extends JFrame {
    /**
     * {@inheritDoc}
     */
    @Override
    protected void frameInit() {
        super.frameInit();

        setTitle("ImagePicker Demo");
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        add(new ImagePicker());

        pack();
    }

    /**
     * Demo entry point.
     *
     * @param args
     *            unused
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ImagePickerDemo().setVisible(true);
            }
        });
    }
}

Add a demo for the image picker.

Add a demo for the image picker.


package com.android.volley.toolbox;

import android.test.InstrumentationTestCase;
import android.view.ViewGroup.LayoutParams;

public class NetworkImageViewTest extends InstrumentationTestCase {
    private NetworkImageView mNIV;
    private MockImageLoader mMockImageLoader;

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        mMockImageLoader = new MockImageLoader();
        mNIV = new NetworkImageView(getInstrumentation().getContext());
    }

    public void testSetImageUrl_requestsImage() {
        mNIV.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        mNIV.setImageUrl("http://foo", mMockImageLoader);
        assertEquals("http://foo", mMockImageLoader.lastRequestUrl);
        assertEquals(0, mMockImageLoader.lastMaxWidth);
        assertEquals(0, mMockImageLoader.lastMaxHeight);
    }

    // public void testSetImageUrl_setsMaxSize() {
    // // TODO: Not sure how to make getWidth() return something from an
    // // instrumentation test. Write this test once it's figured out.
    // }

    private class MockImageLoader extends ImageLoader {
        public MockImageLoader() {
            super(null, null);
        }

        public String lastRequestUrl;
        public int lastMaxWidth;
        public int lastMaxHeight;

        public ImageContainer get(String requestUrl, ImageListener imageListener, int maxWidth,
                int maxHeight) {
            lastRequestUrl = requestUrl;
            lastMaxWidth = maxWidth;
            lastMaxHeight = maxHeight;
            return null;
        }
    }
}

Add a basic test for NetworkImageView

Add a basic test for NetworkImageView

Change-Id: I07208cba4c207c3378500fb9e37ac6198ee7dc8d


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

package org.openmhealth.dsu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * A specialisation of the {@link Controller} annotation that controls the version number of the DSU API.
 * @author Emerson Farrugia
 */
@Controller
@RequestMapping("/v2")
public @interface ApiController {

}

Add @Controller specialisation to control the API version.


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

/**
 * Given two integers passed as parameter, can you write a method to multiply it and return the
 * result without use "*" operator?
 *
 * @author Pedro Vicente Gómez Sánchez.
 */
public class MultiplicationWithoutMultiply {
}

Add statement to problem 20

Add statement to problem 20


package org.rundeck.api;

import junit.framework.Assert;
import org.junit.Test;
import org.rundeck.api.query.ExecutionQuery;

import java.util.Arrays;
import java.util.Date;

/**
 * ExecutionQueryParametersTest is ...
 *
 * @author Greg Schueler <greg@simplifyops.com>
 * @since 2014-11-07
 */
public class ExecutionQueryParametersTest {

    @Test
    public void stringParameter() {
        ExecutionQuery.Builder description = ExecutionQuery.builder().description("a description");
        ExecutionQueryParameters executionQueryParameters = new ExecutionQueryParameters(
                description.build()
        );
        ApiPathBuilder param = new ApiPathBuilder("").param(executionQueryParameters);
        Assert.assertEquals("?descFilter=a+description", param.toString());
    }
    @Test
    public void listParameter() {
        ExecutionQuery.Builder description = ExecutionQuery.builder().excludeJobList(
                Arrays.asList(
                        "a",
                        "b"
                )
        );
        ExecutionQueryParameters executionQueryParameters = new ExecutionQueryParameters(
                description.build()
        );
        ApiPathBuilder param = new ApiPathBuilder("").param(executionQueryParameters);
        Assert.assertEquals("?excludeJobListFilter=a&excludeJobListFilter=b", param.toString());
    }
    @Test
    public void dateParameter() {
        ExecutionQuery.Builder description = ExecutionQuery.builder().end(
                new Date(1347581178168L)
        );
        ExecutionQueryParameters executionQueryParameters = new ExecutionQueryParameters(
                description.build()
        );
        ApiPathBuilder param = new ApiPathBuilder("").param(executionQueryParameters);
        //nb: timezone should be GMT
        //2012-09-14T00:06:18Z
        Assert.assertEquals("?end=2012-09-14T00%3A06%3A18Z", param.toString());
    }
}

Test query parameter generation for date strings


package jmetest.util;

import com.jme.scene.Node;
import com.jme.scene.Spatial;
import com.jme.scene.TriMesh;
import com.jme.system.DisplaySystem;

public class Sizeof {
   public static void main(String[] args) throws Exception {
       // Warm up all classes/methods we will use
       runGC();
       usedMemory();

       // Array to keep strong references to allocated objects
       final int count = 100000;
       Object[] objects = new Object[count];

       long heap1 = 0;
       DisplaySystem display = DisplaySystem.getDisplaySystem("LWJGL");
       display.createWindow(800, 600, 32, 60, false);
       // Allocate count+1 objects, discard the first one
       for (int i = -1; i < count; ++i) {
           Object object = null;

           // ### Instantiate your data here and assign it to object
           object = new Node();
           // ###

           if (i >= 0)
               objects[i] = object;
           else {
               object = null; // Discard the warm up object
               runGC();
               heap1 = usedMemory(); // Take a before heap snapshot
           }
       }

       runGC();
       long heap2 = usedMemory(); // Take an after heap snapshot:

       final int size = Math.round(((float)(heap2 - heap1)) / count);
       System.out.println("'before' heap: " + heap1 + ", 'after' heap: " + heap2);
       System.out.println("heap delta: " + (heap2 - heap1) + ", {" + objects[0].getClass()
               + "} size = " + size + " bytes");

       for (int i = 0; i < count; ++i)
           objects[i] = null;
       objects = null;
       display.close();
       System.exit(0);
   }

   private static void runGC() throws Exception {
       // It helps to call Runtime.gc()
       // using several method calls:
       for (int r = 0; r < 4; ++r)
           _runGC();
   }

   private static void _runGC() throws Exception {
       long usedMem1 = usedMemory(), usedMem2 = Long.MAX_VALUE;
       for (int i = 0; (usedMem1 < usedMem2) && (i < 500); ++i) {
           s_runtime.runFinalization();
           s_runtime.gc();
           Thread.yield();

           usedMem2 = usedMem1;
           usedMem1 = usedMemory();
       }
   }

   private static long usedMemory() {
       return s_runtime.totalMemory() - s_runtime.freeMemory();
   }

   private static final Runtime s_runtime = Runtime.getRuntime();

}

Test to determne the size of certain objects.

git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@2249 75d07b2b-3a1a-0410-a2c5-0572b91ccdca


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

import javax.swing.*;

/**
 * @deprecated Will be removed in 2018.1. Use {@link RunDashboardTreeAction} instead.
 */
@Deprecated
public abstract class DashboardTreeAction<T, C extends TreeContent> extends RunDashboardTreeAction<T, C> {
  protected DashboardTreeAction(String text, String description, Icon icon) {
    super(text, description, icon);
  }
}

Fix incompatibility after class rename

Fix incompatibility after class rename