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

/** Critical logging level for items that are not errors but still important. */
public class Level extends org.apache.log4j.Level {

    /** Integer representation of logging level. */
    public static final int CRITICAL_INT = 60000;

    /** Critical logging level. */
    public static final Level CRITICAL = new Level();

    /** Serial version UID. */
    private static final long serialVersionUID = -104586023689772363L;

    /** Constructor. */
    protected Level(){
        super(CRITICAL_INT, "CRITICAL", 0);
    }
}

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

/**
 * Additional logging levels.
 *
 *

 *
CRITIAL - for messages that should always be logged but not be errors

 *
TRAIL - equivalent to TRACE introduced in later versions of Log4j

 *

 */
public class Level extends org.apache.log4j.Level {

    /** Integer representation of CRITICIAL logging level. */
    public static final int CRITICAL_INT = 60000;

    /** Integer representation of TRAIL logging level. */
    public static final int TRAIL_INT = 5000;

    /** Critical logging level. */
    public static final Level CRITICAL = new Level(CRITICAL_INT, "CRITICAL", 0);

    /** Trail logging level. */
    public static final Level TRAIL = new Level(TRAIL_INT, "TRACE", 7);

    /** Serial version UID. */
    private static final long serialVersionUID = -8920329210711643389L;

    /**
     * Constructor.
     *
     * @param level integer representation of the logging level
     * @param name human readable name for the logging level
     * @param sysLogLevel corresponding syslog level
     */
    protected Level(int level, String name, int sysLogLevel){
        super(level, name, sysLogLevel);
    }
}

Add TRACE-equivalent level (that won't conflict with TRACE if people are using newer log4j levels)


class forNameTest {
       public static void main(String argv[]) {
	      try {
		     Class.forName("loadThis");
		     Class c = Class.forName("loadThis", false,
		        new ClassLoader() {
			  public Class loadClass(String n)
				throws ClassNotFoundException {
				return findSystemClass(n);
			  }
		        });
		     System.out.println("constructor not called");
		     c.newInstance();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
       }
}

class loadThis {
      static {
	      try {
		      new loadThis();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
      }

      public loadThis() {
	      System.out.println("constructor called");
      }
}

/* Expected Output:
constructor called
constructor not called
constructor called
*/

class forNameTest {
       public static void main(String argv[]) {
	      try {
		     Class.forName("loadThis");
		     Class c = Class.forName("loadThis", false,
		        new ClassLoader() {
			  public Class loadClass(String n, boolean resolve)
				      throws ClassNotFoundException {
				Class cl = findSystemClass(n);
				if (resolve) {
				      resolveClass(cl);
				}
				return cl;
			  }
		        });
		     System.out.println("constructor not called");
		     c.newInstance();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
       }
}

class loadThis {
      static {
	      try {
		      new loadThis();
	      }
	      catch( Exception e ) {
		      System.out.println(e.getMessage());
		      e.printStackTrace();
	      }
      }

      public loadThis() {
	      System.out.println("constructor called");
      }
}

/* Expected Output:
constructor called
constructor not called
constructor called
*/

Update wrt. new JDK 1.2 ClassLoader scheme.


/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.pnc.rest.utils;

public class Utility {

    @FunctionalInterface
    public interface Action {
        void doIt();
    }

    /**
     * Perform the given action if the object is not null
     *
     * @param obj The object to check for null
     * @param action The action to perform if object is not null
     */
    public static void performIfNotNull(Object obj, Action action) {
        if(obj != null) {
            action.doIt();
        }
    }

}

/**
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jboss.pnc.rest.utils;

public class Utility {

    /**
     * Perform the given action if the object is not null
     *
     * @param obj The object to check for null
     * @param action The action to perform if object is not null
     */
    public static void performIfNotNull(Object obj, Runnable action) {
        if(obj != null) {
            action.run();
        }
    }

}

Use standard jdk functional interface in rest utility method performIfNotNull


package net.optifine.render;

public class ChunkVisibility {

}

package net.optifine.render;

public class ChunkVisibility {
    private static int counter;
    private static int iMaxStatic;

    private static int iMaxStaticFinal;

    //private static World worldLast = null;
    private static int pcxLast;
    private static int pczLast;
}

Fix some mixin warnings aboufields that d don't exist


package org.seqdoop.hadoop_bam;

import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;

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

public class TestVCFFormat {

  @Test
  public void testInferFromFilePath() throws IOException {
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf"));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf.gz"));
    assertNull(VCFFormat.inferFromFilePath("test.sam"));
  }

  @Test
  public void testInferFromData() throws IOException {
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf")));
    assertNull(VCFFormat.inferFromData(stream("test.sam")));
  }

  private InputStream stream(String resource) throws IOException {
    return ClassLoader.getSystemClassLoader().getResource(resource).openStream();
  }
}

package org.seqdoop.hadoop_bam;

import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;

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

public class TestVCFFormat {

  @Test
  public void testInferFromFilePath() throws IOException {
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf"));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf.gz"));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromFilePath("test.vcf.bgzf.gz"));
    assertNull(VCFFormat.inferFromFilePath("test.sam"));
  }

  @Test
  public void testInferFromData() throws IOException {
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf")));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf.gz")));
    assertEquals(VCFFormat.VCF, VCFFormat.inferFromData(stream("test.vcf.bgzf.gz")));
    assertNull(VCFFormat.inferFromData(stream("test.sam")));
  }

  private InputStream stream(String resource) throws IOException {
    return ClassLoader.getSystemClassLoader().getResource(resource).openStream();
  }
}

Add .gz and bgzf.gz files to infer unit tests


package com.google.sps.data;

import java.util.List;

public class GenerateScheduleRequest {
  List<Course> courses;
  InputCriterion criterion;
  BasicInfo basicInfo;

  public GenerateScheduleRequest(){};

  public List<Course> getCourses() {
    return this.courses;
  }

  public List<TimeRange> getTimePreferences() {
    return this.criterion.timePreferences;
  }

  public String getPreferredSubject() {
    return this.criterion.preferredSubject;
  }

  public Invariants getCredits() {
    return this.basicInfo.credits;
  }

  public String getTermStartDate() {
    return this.basicInfo.termDates.startDate;
  }

  public String getTermEndDate() {
    return this.basicInfo.termDates.endDate;
  }
}

class InputCriterion {
  List<TimeRange> timePreferences;
  String preferredSubject;
}

class BasicInfo {
  Invariants credits;
  TermDates termDates;
}

class TermDates {
  String startDate;
  String endDate;
}

package com.google.sps.data;

import java.util.List;
import java.util.HashMap;

public class GenerateScheduleRequest {
  List<Course> courses;
  InputCriterion criterion;
  BasicInfo basicInfo;

  public GenerateScheduleRequest(){};

  public List<Course> getCourses() {
    return this.courses;
  }

  public List<TimeRange> getTimePreferences() {
    return this.criterion.timePreferences;
  }

  public String getPreferredSubject() {
    return this.criterion.preferredSubject;
  }

  public HashMap<String, Integer> getCourseScores() {
    return this.criterion.courseScores;
  }

  public Invariants getCredits() {
    return this.basicInfo.credits;
  }

  public String getTermStartDate() {
    return this.basicInfo.termDates.startDate;
  }

  public String getTermEndDate() {
    return this.basicInfo.termDates.endDate;
  }
}

class InputCriterion {
  List<TimeRange> timePreferences;
  String preferredSubject;
  HashMap<String, Integer> courseScores;
}

class BasicInfo {
  Invariants credits;
  TermDates termDates;
}

class TermDates {
  String startDate;
  String endDate;
}

Add courseScores hashmap for course priority ranking


package com.vaguehope.onosendai.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class HashHelper {

	private HashHelper () {
		throw new AssertionError();
	}

	public static BigInteger md5String (final String s) {
		final MessageDigest md = MD_MD5_FACTORY.get();
		md.update(getBytes(s), 0, s.length());
		return new BigInteger(1, md.digest());
	}

	private static byte[] getBytes (final String s) {
		try {
			return s.getBytes("UTF-8");
		}
		catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

	/**
	 * MessageDigest.getInstance("MD5") can take up to a second, so using this
	 * to cache it and improve performance.
	 */
	private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() {
		@Override
		protected MessageDigest initialValue () {
			try {
				final MessageDigest md = MessageDigest.getInstance("MD5");
				md.reset();
				return md;
			}
			catch (final NoSuchAlgorithmException e) {
				throw new IllegalStateException("JVM is missing MD5.", e);
			}
		}
	};

}

package com.vaguehope.onosendai.util;

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class HashHelper {

	private HashHelper () {
		throw new AssertionError();
	}

	public static BigInteger md5String (final String s) {
		final MessageDigest md = MD_MD5_FACTORY.get();
		md.update(getBytes(s));
		return new BigInteger(1, md.digest());
	}

	private static byte[] getBytes (final String s) {
		try {
			return s.getBytes("UTF-8");
		}
		catch (UnsupportedEncodingException e) {
			throw new IllegalStateException(e.getMessage(), e);
		}
	}

	/**
	 * MessageDigest.getInstance("MD5") can take up to a second, so using this
	 * to cache it and improve performance.
	 */
	private static final ThreadLocal<MessageDigest> MD_MD5_FACTORY = new ThreadLocal<MessageDigest>() {
		@Override
		protected MessageDigest initialValue () {
			try {
				final MessageDigest md = MessageDigest.getInstance("MD5");
				md.reset();
				return md;
			}
			catch (final NoSuchAlgorithmException e) {
				throw new IllegalStateException("JVM is missing MD5.", e);
			}
		}
	};

}

Fix possible issue when MD5ing multibyte strings.


package net.christophermerrill.FancyFxTree;

import javafx.event.*;
import javafx.scene.control.*;
import javafx.scene.input.*;

/**
 * Intercepts double-click events BEFORE the tree can use it for expand/collapsing of nodes. Provided
 * with a MouseListener, this allows the double-click event to be used for editing the node, rather than
 * expand/collapse.
 *
 * @author Christopher L Merrill (see LICENSE.txt for license details)
 */
class DoubleClickInterceptor implements EventDispatcher
    {
    DoubleClickInterceptor(TreeCell cell, EventHandler<MouseEvent> double_click_listener)
        {
        _original_dispatcher = cell.getEventDispatcher();
        cell.setEventDispatcher(this);
        _double_click_listener = double_click_listener;
        }

    @Override
    public Event dispatchEvent(Event event, EventDispatchChain tail)
        {
        if (event instanceof MouseEvent)
            {
            MouseEvent mouse_event = (MouseEvent) event;
            if (mouse_event.getEventType().equals(MouseEvent.MOUSE_PRESSED)
                && mouse_event.getButton() == MouseButton.PRIMARY
                && mouse_event.getClickCount() >= 2
                && !event.isConsumed())
                {
                _double_click_listener.handle(mouse_event);
                event.consume();
                }
            }
        return _original_dispatcher.dispatchEvent(event, tail);
        }

    private final EventDispatcher _original_dispatcher;
    private final EventHandler<MouseEvent> _double_click_listener;
    }

package net.christophermerrill.FancyFxTree;

import javafx.event.*;
import javafx.scene.control.*;
import javafx.scene.input.*;

/**
 * Intercepts double-click events BEFORE the tree can use it for expand/collapsing of nodes. Provided
 * with a MouseListener, this allows the double-click event to be used for editing the node, rather than
 * expand/collapse.
 *
 * @author Christopher L Merrill (see LICENSE.txt for license details)
 */
class DoubleClickInterceptor
    {
    DoubleClickInterceptor(TreeCell cell, EventHandler<MouseEvent> double_click_listener)
        {
        _double_click_listener = double_click_listener;
        cell.addEventHandler(MouseEvent.ANY, event ->
	        {
	        if (event.getClickCount() == 2 && event.getButton().equals(MouseButton.PRIMARY))
		        {
		        if (event.getEventType().equals(MouseEvent.MOUSE_CLICKED))
		        	_double_click_listener.handle(event);
	            event.consume();
		        }
	        });
        }

    private final EventHandler<MouseEvent> _double_click_listener;
    }

Switch to using a mouse event handler instead of EventDispatcher


import mmcorej.TaggedImage;

import org.json.JSONObject;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.api.TaggedImageStorage;

public class ReadDataSet {

   public static void main(String[] args) {
      //String rootName = "C:/AcqusitionData/Tests/Test-A_1";
      String rootName = "C:/AcqusitionData/20130813 Oxidative Stress Test 3/NIH3T3_1";

      try {
         TaggedImageStorage storage = new TaggedImageStorageDiskDefault(rootName);
         JSONObject summary = storage.getSummaryMetadata();
         System.out.println(summary.toString(3));

         int numChannels = summary.getInt("Channels");
         int numSlices = summary.getInt("Slices");
         int numFrames = summary.getInt("Frames");
         int numPositions = summary.getInt("Positions");

         for (int pos=0; pos < numPositions; pos++) {
            for (int fr=0; fr<numFrames; fr++) {
               TaggedImage img = storage.getImage(0, 0, fr, pos);
               System.out.println(img.tags.toString(3));
            }
         }

      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }

}

import mmcorej.TaggedImage;

import org.json.JSONObject;
import org.micromanager.acquisition.TaggedImageStorageDiskDefault;
import org.micromanager.api.MMTags;
import org.micromanager.api.TaggedImageStorage;

public class ReadDataSet {

   public static void main(String[] args) {
      String rootName = "C:/AcqusitionData/Tests/Test-A_1";

      try {
         TaggedImageStorage storage = new TaggedImageStorageDiskDefault(rootName);
         JSONObject summary = storage.getSummaryMetadata();
         System.out.println(summary.toString(3));

         int numChannels = summary.getInt(MMTags.Summary.CHANNELS);
         int numSlices = summary.getInt(MMTags.Summary.SLICES);
         int numFrames = summary.getInt(MMTags.Summary.FRAMES);
         int numPositions = summary.getInt(MMTags.Summary.POSITIONS);

         for (int pos=0; pos < numPositions; pos++) {
            for (int t=0; t<numFrames; t++) {
               for (int z=0; z<numSlices; z++) {
                  for (int ch=0; ch<numChannels; ch++) {
                     TaggedImage img = storage.getImage(ch, z, t, pos);
                     Object pixels = img.pix;
                     // TODO: do something with pixels

                     System.out.println(img.tags.toString(3));
                  }
               }
            }
         }

      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }

   }

}

Read data set up updated


/*******************************************************************************
 * Copyright (c) 2012-2016 Codenvy, S.A.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package org.eclipse.che.api.core;

/**
 * Error codes that are used in exceptions.
 *
 * @author Igor Vinokur
 */
public class ErrorCodes {
    private ErrorCodes() {
    }

    public static final int NO_COMMITTER_NAME_OR_EMAIL_DEFINED = 15216;
    public static final int UNABLE_GET_PRIVATE_SSH_KEY         = 32068;
    public static final int UNAUTHORIZED_GIT_OPERATION         = 32080;
    public static final int MERGE_CONFLICT                     = 32062;
    public static final int FAILED_CHECKOUT                    = 32063;
    public static final int FAILED_CHECKOUT_WITH_START_POINT   = 32064;
    public static final int INIT_COMMIT_WAS_NOT_PERFORMED      = 32082;
}

/*******************************************************************************
 * Copyright (c) 2012-2016 Codenvy, S.A.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *   Codenvy, S.A. - initial API and implementation
 *******************************************************************************/
package org.eclipse.che.api.core;

/**
 * Error codes that are used in exceptions.
 * Defined error codes MUST BE in range <b>15000-32999</b> inclusive.
 *
 * @author Igor Vinokur
 */
public class ErrorCodes {
    private ErrorCodes() {
    }

    public static final int NO_COMMITTER_NAME_OR_EMAIL_DEFINED = 15216;
    public static final int UNABLE_GET_PRIVATE_SSH_KEY         = 32068;
    public static final int UNAUTHORIZED_GIT_OPERATION         = 32080;
    public static final int MERGE_CONFLICT                     = 32062;
    public static final int FAILED_CHECKOUT                    = 32063;
    public static final int FAILED_CHECKOUT_WITH_START_POINT   = 32064;
    public static final int INIT_COMMIT_WAS_NOT_PERFORMED      = 32082;
}

Add comment which defines error codes range


/** Defines classes and interfaces of the Processor API. */
module processor {
  requires java.compiler;
  requires jdk.javadoc;

  provides com.sun.source.util.Plugin with
      processor.ShowPlugin;
  provides javax.annotation.processing.Processor with
      processor.ShowProcessor;
}

/** Defines classes and interfaces of the Processor API. */
module processor {
  requires jdk.compiler;
  requires jdk.javadoc;

  provides com.sun.source.util.Plugin with
      processor.ShowPlugin;
  provides javax.annotation.processing.Processor with
      processor.ShowProcessor;
}

Read `jdk.compiler` module in processing-code example


package com.alexrnl.commons.io;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Utility methods for IO stuff.

 * @author Alex
 */
public final class IOUtils {
	/** Logger */
	private static Logger	lg	= Logger.getLogger(IOUtils.class.getName());

	/**
	 * Constructor #1.

	 * Default private constructor.
	 */
	private IOUtils () {
		super();
	}

	/**
	 * Read the next line on the buffered reader provided.

	 * @param reader
	 *        the stream to read.
	 * @return the next line in the stream.
	 * @throws IOException
	 *         if there was an issue when reading the stream.
	 * @throws EOFException
	 *         if the line returned is null.
	 */
	public static String readLine (final BufferedReader reader) throws IOException, EOFException {
		Objects.requireNonNull(reader);
		final String line = reader.readLine();
		if (lg.isLoggable(Level.FINE)) {
			lg.fine("Read line: " + line);
		}
		if (line == null) {
			throw new EOFException("End of stream reached");
		}
		return line;
	}
}

package com.alexrnl.commons.io;

import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Utility methods for IO stuff.

 * @author Alex
 */
public final class IOUtils {
	/** Logger */
	private static Logger	lg	= Logger.getLogger(IOUtils.class.getName());

	/** The byte order mark used at the beginning of unicode files */
	public static final Character UNICODE_BYTE_ORDER_MARK = '\ufeff';

	/**
	 * Constructor #1.

	 * Default private constructor.
	 */
	private IOUtils () {
		super();
	}

	/**
	 * Read the next line on the buffered reader provided.

	 * @param reader
	 *        the stream to read.
	 * @return the next line in the stream.
	 * @throws IOException
	 *         if there was an issue when reading the stream.
	 * @throws EOFException
	 *         if the line returned is null.
	 */
	public static String readLine (final BufferedReader reader) throws IOException, EOFException {
		Objects.requireNonNull(reader);
		final String line = reader.readLine();
		if (lg.isLoggable(Level.FINE)) {
			lg.fine("Read line: " + line);
		}
		if (line == null) {
			throw new EOFException("End of stream reached");
		}
		return line;
	}
}

Add constant for unicode byte order mark


package com.uwetrottmann.shopr.settings;

import android.content.Context;
import android.preference.PreferenceManager;

/**
 * Quick access to some app settings.
 */
public class AppSettings {

    private static final String KEY_MAX_RECOMMENDATIONS = "com.uwetrottmann.shopr.maxrecommendations";

    public static int getMaxRecommendations(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context).getInt(
                KEY_MAX_RECOMMENDATIONS, 8);
    }
}

package com.uwetrottmann.shopr.settings;

import android.content.Context;
import android.preference.PreferenceManager;

/**
 * Quick access to some app settings.
 */
public class AppSettings {

    private static final String KEY_MAX_RECOMMENDATIONS = "com.uwetrottmann.shopr.maxrecommendations";

    public static int getMaxRecommendations(Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context).getInt(
                KEY_MAX_RECOMMENDATIONS, 9);
    }
}

Set max recs to 9.


package net.darkhax.bookshelf.api.registry;

import net.minecraft.resources.ResourceLocation;

import javax.annotation.Nullable;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public interface IRegistryReader<T> extends Iterable<T> {

    @Nullable
    T get(ResourceLocation id);

    @Nullable
    ResourceLocation getId(T value);

    default Stream<T> streamValues() {

        return StreamSupport.stream(spliterator(), false);
    }

    default Stream<T> parallelStreamValues() {

        return StreamSupport.stream(spliterator(), true);
    }
}

package net.darkhax.bookshelf.api.registry;

import net.minecraft.resources.ResourceLocation;

import javax.annotation.Nullable;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

public interface IRegistryReader<T> extends Iterable<T> {

    @Nullable
    T get(ResourceLocation id);

    @Nullable
    ResourceLocation getId(T value);

    default ResourceLocation getId(T value, ResourceLocation fallback) {

        final ResourceLocation id = this.getId(value);
        return id != null ? id : fallback;
    }

    default Stream<T> streamValues() {

        return StreamSupport.stream(spliterator(), false);
    }

    default Stream<T> parallelStreamValues() {

        return StreamSupport.stream(spliterator(), true);
    }
}

Add a registry reader method that gets an ID with an optional fallback.


package com.codepath.simpletodo;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

package com.codepath.simpletodo;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends ActionBarActivity {
    ArrayList<String> items;
    ArrayAdapter<String> itemsAdapter;
    ListView lvItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lvItems = (ListView) findViewById(R.id.lvItems);
        items = new ArrayList<String>();
        itemsAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, items);

        lvItems.setAdapter(itemsAdapter);
        items.add("First Item");
        items.add("Second Item");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Add static items to the list view


package org.ops4j.pax.jdbc.test.pool;

import javax.inject.Inject;

import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.util.Filter;
import org.ops4j.pax.jdbc.pool.common.PooledDataSourceFactory;
import org.ops4j.pax.jdbc.test.AbstractJdbcTest;

public class PoolAriesTest extends AbstractJdbcTest {

    @Inject @Filter("(pool=aries)(xa=false)")
    PooledDataSourceFactory pool;

    @Configuration
    public Option[] config() {
        return new Option[] { //
                regressionDefaults(), //
                poolDefaults(), //
                mvnBundle("org.apache.geronimo.components", "geronimo-connector"),
                mvnBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.6_spec"),
                mvnBundle("org.ops4j.pax.jdbc", "pax-jdbc-pool-aries"),
                };
    }

    @Test
    public void testPooledDataSourceFactoryServicesPresent() {
    }

}

package org.ops4j.pax.jdbc.test.pool;

import javax.inject.Inject;

import org.junit.Test;
import org.ops4j.pax.exam.Configuration;
import org.ops4j.pax.exam.Option;
import org.ops4j.pax.exam.util.Filter;
import org.ops4j.pax.jdbc.pool.common.PooledDataSourceFactory;
import org.ops4j.pax.jdbc.test.AbstractJdbcTest;

public class PoolAriesTest extends AbstractJdbcTest {

    @Inject @Filter("(pool=aries)(xa=false)")
    PooledDataSourceFactory pool;

    @Configuration
    public Option[] config() {
        return new Option[] { //
                regressionDefaults(), //
                poolDefaults(), //
                mvnBundle("commons-logging", "commons-logging"),
                mvnBundle("org.apache.geronimo.components", "geronimo-connector"),
                mvnBundle("org.apache.geronimo.specs", "geronimo-j2ee-connector_1.6_spec"),
                mvnBundle("org.ops4j.pax.jdbc", "pax-jdbc-pool-aries"),
                };
    }

    @Test
    public void testPooledDataSourceFactoryServicesPresent() {
    }

}

Fix missing itest dependency for aries-pool


package chart_parser;

import java.util.HashMap;

import cat_combination.SuperCategory;

public class CategoryEquivalence {
	/*
	 * keys are triples of (position, span, SuperCategory); value becomes the *last*
	 * SuperCategory in the linked list of equivalents
	 */
	// should refactor into Hashmap<EquivKey, LinkedList<SuperCategory>>!
	private HashMap<EquivKey, SuperCategory> equiv;

	public CategoryEquivalence(int initCapacity) {
		equiv = new HashMap<EquivKey, SuperCategory>(initCapacity);
	}

	/*
	 * returns true if equivalent category not already there, false otherwise
	 */
	public boolean add(int position, int span, SuperCategory superCat) {
		EquivKey equivKey = new EquivKey(position, span, superCat);
		SuperCategory value = equiv.get(equivKey);
		equiv.put(equivKey, superCat);
		// overrides the previous value (if there was one)

		if (value != null) {
			value.next = superCat;
			return false;
		} else {
			return true;
		}
	}

	public void clear() {
		equiv.clear();
	}
}

package chart_parser;

import java.util.HashMap;

import cat_combination.SuperCategory;

public class CategoryEquivalence {
	/*
	 * keys are triples of (position, span, SuperCategory); value becomes the *last*
	 * SuperCategory in the linked list of equivalents
	 */
	// should refactor into Hashmap<EquivKey, LinkedList<SuperCategory>>!
	private HashMap<EquivKey, SuperCategory> equiv;

	public CategoryEquivalence(int initCapacity) {
		equiv = new HashMap<EquivKey, SuperCategory>(initCapacity);
	}

	/*
	 * returns true if equivalent category not already there, false otherwise
	 */
	public boolean add(int position, int span, SuperCategory superCat) {
		EquivKey equivKey = new EquivKey(position, span, superCat);
		SuperCategory previousValue = equiv.put(equivKey, superCat);
		// put() returns the previous value, or null if there was no mapping for the key

		if (previousValue != null) {
			previousValue.next = superCat;
			return false;
		} else {
			return true;
		}
	}

	public void clear() {
		equiv.clear();
	}
}

Modify add() to save one extra get() call to HashMap.


package com.opera.core.systems.scope.stp;

import java.util.logging.Logger;

import com.opera.core.systems.util.SocketMonitor;
import com.opera.core.systems.scope.handlers.IConnectionHandler;

/**
 *
 * @author Jan Vidar Krey
 */
public class StpThread extends Thread {

    private final Logger logger = Logger.getLogger(this.getClass().getName());
    private StpConnectionListener listener;
    private StpConnection stpConnection;
    private boolean running = true;

    public StpThread(int port, IConnectionHandler handler) throws java.io.IOException
    {
        super("StpThread");
        SocketMonitor.instance();
        listener = new StpConnectionListener(port, handler);
        start();
    }

    public void shutdown() {
        running = false;
        SocketMonitor.instance().stop();
    }

    @Override
    public void run() {
        logger.info("Started StpThread.");
        while (running)
        {
            SocketMonitor.poll(50);
        }
        logger.info("Stopping StpThread.");
    }

}

package com.opera.core.systems.scope.stp;

import java.util.logging.Logger;

import com.opera.core.systems.util.SocketMonitor;
import com.opera.core.systems.scope.handlers.IConnectionHandler;

/**
 *
 * @author Jan Vidar Krey
 */
public class StpThread extends Thread {

    private final Logger logger = Logger.getLogger(this.getClass().getName());
    private StpConnectionListener listener;
    private StpConnection stpConnection;
    private boolean running = true;

    public StpThread(int port, IConnectionHandler handler) throws java.io.IOException
    {
        super("StpThread");
        SocketMonitor.instance();
        listener = new StpConnectionListener(port, handler);
        start();
    }

    public void shutdown() {
        running = false;
        listener.stop();
        SocketMonitor.instance().stop();
    }

    @Override
    public void run() {
        logger.info("Started StpThread.");
        while (running)
        {
            SocketMonitor.poll(50);
        }
        logger.info("Stopping StpThread.");
    }

}

Make sure we close the STP connection listener when stopping the STP thread.


/**
 *
 */
package ca.eandb.jmist.framework.geometry.mesh;

import java.util.stream.StreamSupport;

import ca.eandb.jmist.framework.BoundingBoxBuilder3;
import ca.eandb.jmist.math.Box3;
import ca.eandb.jmist.math.Sphere;

/**
 * @author bwkimmel
 *
 */
public final class MeshUtil {

  private MeshUtil() {}

  public static Mesh triangulate(Mesh mesh) {
    return mesh.getMaxFaceVertexCount() == 3
        ? mesh : new TriangulatedMesh(mesh);
  }

  public static Sphere getBoundingSphere(Mesh mesh) {
    return getBoundingSphere(mesh.getVertices());
  }

  public static Sphere getBoundingSphere(Mesh.Face face) {
    return getBoundingSphere(face.getVertices());
  }

  private static Sphere getBoundingSphere(Iterable<Mesh.Vertex> vertices) {
    return Sphere.smallestContaining(() ->
        StreamSupport.stream(vertices.spliterator(), false)
            .map(v -> v.getPosition())
            .iterator());
  }

  public static Box3 getBoundingBox(Mesh mesh) {
    return getBoundingBox(mesh.getVertices());
  }

  public static Box3 getBoundingBox(Mesh.Face face) {
    return getBoundingBox(face.getVertices());
  }

  private static Box3 getBoundingBox(Iterable<Mesh.Vertex> vertices) {
    BoundingBoxBuilder3 builder = new BoundingBoxBuilder3();
    for (Mesh.Vertex vertex : vertices) {
      builder.add(vertex.getPosition());
    }
    return builder.getBoundingBox();
  }

}

/**
 *
 */
package ca.eandb.jmist.framework.geometry.mesh;

import java.util.stream.StreamSupport;

import ca.eandb.jmist.framework.BoundingBoxBuilder3;
import ca.eandb.jmist.math.Box3;
import ca.eandb.jmist.math.Sphere;

/**
 * @author bwkimmel
 *
 */
public final class MeshUtil {

  private MeshUtil() {}

  public static Mesh triangulate(Mesh mesh) {
    return mesh.getMaxFaceVertexCount() == 3
        ? mesh : new TriangulatedMesh(mesh);
  }

  public static Sphere getBoundingSphere(Mesh mesh) {
    return getBoundingSphere(mesh.getVertices());
  }

  public static Sphere getBoundingSphere(Mesh.Face face) {
    return getBoundingSphere(face.getVertices());
  }

  private static Sphere getBoundingSphere(Iterable<Mesh.Vertex> vertices) {
    return Sphere.smallestContaining(() ->
        StreamSupport.stream(vertices.spliterator(), false)
            .map(Mesh.Vertex::getPosition)
            .iterator());
  }

  public static Box3 getBoundingBox(Mesh mesh) {
    return getBoundingBox(mesh.getVertices());
  }

  public static Box3 getBoundingBox(Mesh.Face face) {
    return getBoundingBox(face.getVertices());
  }

  private static Box3 getBoundingBox(Iterable<Mesh.Vertex> vertices) {
    BoundingBoxBuilder3 builder = new BoundingBoxBuilder3();
    for (Mesh.Vertex vertex : vertices) {
      builder.add(vertex.getPosition());
    }
    return builder.getBoundingBox();
  }

}

Use method reference instead of lambda


/*
 * Copyright 2016 kohii
 *
 * 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.smoothcsv.commons.utils;

import java.util.Arrays;
import java.util.Collection;

/**
 * @author kohii
 */
public class CollectionUtils {

  public static <T> void add(Collection<T> c, T t, int size) {
    c.addAll(Arrays.asList(ArrayUtils.createAndFill(size, t)));
  }
}

/*
 * Copyright 2016 kohii
 *
 * 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.smoothcsv.commons.utils;

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

/**
 * @author kohii
 */
public class CollectionUtils {

  public static <T> void add(Collection<T> c, T t, int size) {
    c.addAll(Arrays.asList(ArrayUtils.createAndFill(size, t)));
  }

  public static <T> List<T> unique(List<T> list) {
    List<T> ret = new ArrayList<>();
    for (T t : list) {
      if (!ret.contains(t)) {
        ret.add(t);
      }
    }
    return ret;
  }
}

Modify CsvMetaPanel so that it remembers user selection history


/*
 *
 *
 * Copyright (C) 2007 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2007 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.common;

import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;

/**
 * Triggers system to start up, then find a requested bean, then runs it.
 */
public class SystemTaskRunner {

    @SuppressWarnings("unused")
    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            System.err.println("bean to run is required as first argument");
            System.exit(1);
        }

        new SystemTaskRunner().runMain(args);
    }

    void runMain(String[] args) {
        BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance();
        BeanFactoryReference bfr = bfl.useBeanFactory("servicelayer-context");
        ApplicationContext app = (ApplicationContext) bfr.getFactory();
        SystemTaskEntryPoint task = (SystemTaskEntryPoint) app.getBean(args[0]);
        task.runSystemTask(args);
    }
}

/*
 *
 *
 * Copyright (C) 2007 SIPfoundry Inc.
 * Licensed by SIPfoundry under the LGPL license.
 *
 * Copyright (C) 2007 Pingtel Corp.
 * Licensed to SIPfoundry under a Contributor Agreement.
 *
 * $
 */
package org.sipfoundry.sipxconfig.common;

import org.springframework.beans.factory.access.BeanFactoryLocator;
import org.springframework.beans.factory.access.BeanFactoryReference;
import org.springframework.context.ApplicationContext;
import org.springframework.context.access.ContextSingletonBeanFactoryLocator;

/**
 * Triggers system to start up, then find a requested bean, then runs it.
 */
public class SystemTaskRunner {

    public static void main(String[] args) {
        if (args == null || args.length == 0) {
            throw new IllegalArgumentException("bean to run is required as first argument");
        }

        new SystemTaskRunner().runMain(args);
    }

    void runMain(String[] args) {
        BeanFactoryLocator bfl = ContextSingletonBeanFactoryLocator.getInstance();
        BeanFactoryReference bfr = bfl.useBeanFactory("servicelayer-context");
        ApplicationContext app = (ApplicationContext) bfr.getFactory();
        SystemTaskEntryPoint task = (SystemTaskEntryPoint) app.getBean(args[0]);
        task.runSystemTask(args);
    }
}

Remove checkstyle warning about System.err


package org.jvirtanen.parity.top;

/**
 * MarketListener is the interface for outbound events from the
 * order book reconstruction.
 */
public interface MarketListener {

    /**
     * An event indicating that the best bid and offer (BBO) has changed.
     *
     * @param instrument the instrument
     * @param bidPrice the bid price or zero if there are no bids
     * @param bidSize the bid size or zero if there are no bids
     * @param askPrice the ask price or zero if there are no asks
     * @param askSize the ask size or zero if there are no asks
     */
    void bbo(long instrument, long bidPrice, long bidSize, long askPrice, long askSize);

    /**
     * An event indicating that a trade has taken place.
     *
     * @param instrument the instrument
     * @param side the side of the resting order
     * @param price the trade price
     * @param size the trade size
     */
    void trade(long instrument, Side side, long price, long size);

}

package org.jvirtanen.parity.top;

/**
 * The interface for outbound events from the order book reconstruction.
 */
public interface MarketListener {

    /**
     * An event indicating that the best bid and offer (BBO) has changed.
     *
     * @param instrument the instrument
     * @param bidPrice the bid price or zero if there are no bids
     * @param bidSize the bid size or zero if there are no bids
     * @param askPrice the ask price or zero if there are no asks
     * @param askSize the ask size or zero if there are no asks
     */
    void bbo(long instrument, long bidPrice, long bidSize, long askPrice, long askSize);

    /**
     * An event indicating that a trade has taken place.
     *
     * @param instrument the instrument
     * @param side the side of the resting order
     * @param price the trade price
     * @param size the trade size
     */
    void trade(long instrument, Side side, long price, long size);

}

Tweak documentation for market listener in order book reconstruction


/**
 * Command-line option processing for Java
 *
 *
The Options class:
 *
 *

 *
parses command-line options and sets fields in your program accordingly,
 *
creates usage messages (such as printed by a `--help` option), and
 *
creates documentation suitable for a manual or manpage.
 *

 *
 * Thus, the programmer is freed from writing duplicative, boilerplate code. The user documentation
 * is automatically generated and never gets out of sync with the rest of the program.
 *
 *
The programmer does not have to write any code, only declare and document variables. For each
 * field that you want to set from a command-line argument, you write Javadoc and an {@code @}{@link
 * Option} annotation. Then, the field is automatically set from a command-line option of the same
 * name, and usage messages and printed documentation are generated automatically.
 */
package org.plumelib.options;

/**
 * Command-line option processing for Java.
 *
 *
The Options class:
 *
 *

 *
parses command-line options and sets fields in your program accordingly,
 *
creates usage messages (such as printed by a `--help` option), and
 *
creates documentation suitable for a manual or manpage.
 *

 *
 * Thus, the programmer is freed from writing duplicative, boilerplate code. The user documentation
 * is automatically generated and never gets out of sync with the rest of the program.
 *
 *
The programmer does not have to write any code, only declare and document variables. For each
 * field that you want to set from a command-line argument, you write Javadoc and an {@code @}{@link
 * Option} annotation. Then, the field is automatically set from a command-line option of the same
 * name, and usage messages and printed documentation are generated automatically.
 */
package org.plumelib.options;

Add missing period in Javadoc descriptions


/*
 * Copyright 2016 Martin Kamp Jensen
 *
 * 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.mkjensen.dml.test;

import static org.junit.Assert.assertFalse;

import android.database.Cursor;

/**
 * Helper methods for working with {@link Cursor}.
 */
public final class CursorUtils {

  private CursorUtils() {
  }

  /**
   * Delegates to {@link Cursor#getColumnIndex(String)}. Also asserts that the returned index is not
   * {@code -1}.
   */
  public static int getColumnIndex(Cursor cursor, String columnName) {
    int columnIndex = cursor.getColumnIndex(columnName);
    assertFalse(columnIndex == -1);
    return columnIndex;
  }

  /**
   * Delegates to {@link Cursor#getString(int)}, using {@link #getColumnIndex(Cursor, String)} to
   * get the column index for the specified column name.
   */
  public static String getString(Cursor cursor, String columnName) {
    int columnIndex = getColumnIndex(cursor, columnName);
    return cursor.getString(columnIndex);
  }
}

/*
 * Copyright 2016 Martin Kamp Jensen
 *
 * 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.mkjensen.dml.test;

import static org.junit.Assert.assertFalse;

import android.database.Cursor;

/**
 * Helper methods for working with {@link Cursor}.
 */
public final class CursorUtils {

  private CursorUtils() {
  }

  /**
   * Delegates to {@link Cursor#getString(int)}, using {@link #getColumnIndex(Cursor, String)} to
   * get the column index for the specified column name.
   */
  public static String getString(Cursor cursor, String columnName) {
    int columnIndex = getColumnIndex(cursor, columnName);
    return cursor.getString(columnIndex);
  }

  private static int getColumnIndex(Cursor cursor, String columnName) {
    int columnIndex = cursor.getColumnIndex(columnName);
    assertFalse(columnIndex == -1);
    return columnIndex;
  }
}

Change getColumnIndex method to be private


/*
 *  Copyright 2017, Sascha Häberling
 *
 *  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.retrostore.request;

/**
 * Resolves content types.
 */
final class ContentType {
  /** Return a content type depending on the filename. */
  static Responder.ContentType fromFilename(String filename) {
    filename = filename.toLowerCase();
    if (filename.endsWith(".html")) {
      return Responder.ContentType.HTML;
    } else if (filename.endsWith(".css")) {
      return Responder.ContentType.CSS;
    } else if (filename.endsWith(".js")) {
      return Responder.ContentType.JS;
    } else if (filename.endsWith(".json")) {
      return Responder.ContentType.JSON;
    } else if (filename.endsWith(".jpeg")) {
      return Responder.ContentType.JPEG;
    } else if (filename.endsWith(".png")) {
      return Responder.ContentType.PNG;
    } else {
      return Responder.ContentType.PLAIN;
    }
  }
}

/*
 *  Copyright 2017, Sascha Häberling
 *
 *  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.retrostore.request;

/**
 * Resolves content types.
 */
final class ContentType {
  /** Return a content type depending on the filename. */
  static Responder.ContentType fromFilename(String filename) {
    filename = filename.toLowerCase();
    if (filename.endsWith(".html") || filename.endsWith(".htm")) {
      return Responder.ContentType.HTML;
    } else if (filename.endsWith(".css")) {
      return Responder.ContentType.CSS;
    } else if (filename.endsWith(".js")) {
      return Responder.ContentType.JS;
    } else if (filename.endsWith(".json")) {
      return Responder.ContentType.JSON;
    } else if (filename.endsWith(".jpeg") || filename.endsWith(".jpg")) {
      return Responder.ContentType.JPEG;
    } else if (filename.endsWith(".png")) {
      return Responder.ContentType.PNG;
    } else {
      return Responder.ContentType.PLAIN;
    }
  }
}

Expand content type detection to jpg and htm.


package com.hivedi.statfscompat;

import android.os.Build;
import android.os.StatFs;

import java.io.File;

/**
 * Created by Hivedi2 on 2015-11-24.
 *
 */
public class StatFsCompat {

	@SuppressWarnings("deprecation")
	public static long getStatFsTotal(File f) {
		StatFs statFs = new StatFs(f.getAbsolutePath());
		if (Build.VERSION.SDK_INT >= 18) {
			return statFs.getTotalBytes();
		} else {
			return statFs.getBlockCount() * statFs.getBlockSize();
		}
	}

	@SuppressWarnings("deprecation")
	public static long getStatFsFree(File f) {
		StatFs statFs = new StatFs(f.getAbsolutePath());
		if (Build.VERSION.SDK_INT >= 18) {
			return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
		} else {
			return statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
		}
	}

}

package com.hivedi.statfscompat;

import android.os.Build;
import android.os.StatFs;

import java.io.File;

/**
 * Created by Hivedi2 on 2015-11-24.
 *
 */
public class StatFsCompat {

	public static final long STAT_FS_ERROR = -1L;

	@SuppressWarnings("deprecation")
	public static long getStatFsTotal(File f) {
		try {
			StatFs statFs = new StatFs(f.getAbsolutePath());
			if (Build.VERSION.SDK_INT >= 18) {
				return statFs.getTotalBytes();
			} else {
				return statFs.getBlockCount() * statFs.getBlockSize();
			}
		} catch (IllegalArgumentException e) {
			return STAT_FS_ERROR;
		}
	}

	@SuppressWarnings("deprecation")
	public static long getStatFsFree(File f) {
		try {
			StatFs statFs = new StatFs(f.getAbsolutePath());
			if (Build.VERSION.SDK_INT >= 18) {
				return statFs.getAvailableBlocksLong() * statFs.getBlockSizeLong();
			} else {
				return statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
			}
		} catch (IllegalArgumentException e) {
			return STAT_FS_ERROR;
		}
	}

}

Handle error if file not exists


package com.martindisch.chronoscopy.logic;

import com.orm.SugarRecord;

/**
 * Represents a usage of an activity, with a date and duration.
 */
public class ChrUsage extends SugarRecord {

    private ChrActivity activity;
    private String date;
    private String time;

    /**
     * Default constructor, necessary for SugarRecord.
     */
    public ChrUsage() {}

    /**
     * Instantiate a new activity usage.
     *
     * @param activity Reference to the activity
     * @param date The date in ISO 8601 (YYYY-MM-DD)
     * @param time The duration in minutes or h:mm/hh:mm
     */
    public ChrUsage(ChrActivity activity, String date, String time) {
        this.activity = activity;
        this.date = date;
        this.time = time;
    }

    public ChrActivity getActivity() {
        return activity;
    }

    public void setActivity(ChrActivity activity) {
        this.activity = activity;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

package com.martindisch.chronoscopy.logic;

import com.orm.SugarRecord;

/**
 * Represents a usage of an activity, with a date and duration.
 */
public class ChrUsage extends SugarRecord {

    private long activityId;
    private String date;
    private String time;

    /**
     * Default constructor, necessary for SugarRecord.
     */
    public ChrUsage() {}

    /**
     * Instantiate a new activity usage.
     *
     * @param activityId Id of the activity
     * @param date The date in ISO 8601 (YYYY-MM-DD)
     * @param time The duration in minutes or h:mm/hh:mm
     */
    public ChrUsage(long activityId, String date, String time) {
        this.activityId = activityId;
        this.date = date;
        this.time = time;
    }

    public long getActivityId() {
        return activityId;
    }

    public void setActivity(long activityId) {
        this.activityId = activityId;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }
}

Store activity id directly to prevent issues


package io.undertow.servlet.api;

/**
 * @author Stuart Douglas
 */
public enum ServletStackTraces {

    NONE,
    LOCAL_ONLY,
    ALL
}

package io.undertow.servlet.api;

/**
 * @author Stuart Douglas
 */
public enum ServletStackTraces {

    NONE("none"),
    LOCAL_ONLY("local-only"),
    ALL("all");

    private final String value;

    private ServletStackTraces(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return value;
    }
}

Add string representation to enum


package tars.commons.util;

import org.junit.Test;

import tars.commons.util.StringUtil;

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

public class StringUtilTest {

    @Test
    public void isUnsignedPositiveInteger() {
        assertFalse(StringUtil.isUnsignedInteger(null));
        assertFalse(StringUtil.isUnsignedInteger(""));
        assertFalse(StringUtil.isUnsignedInteger("a"));
        assertFalse(StringUtil.isUnsignedInteger("aaa"));
        assertFalse(StringUtil.isUnsignedInteger("  "));
        assertFalse(StringUtil.isUnsignedInteger("-1"));
        assertFalse(StringUtil.isUnsignedInteger("0"));
        assertFalse(StringUtil.isUnsignedInteger("+1")); //should be unsigned
        assertFalse(StringUtil.isUnsignedInteger("-1")); //should be unsigned
        assertFalse(StringUtil.isUnsignedInteger(" 10")); //should not contain whitespaces
        assertFalse(StringUtil.isUnsignedInteger("10 ")); //should not contain whitespaces
        assertFalse(StringUtil.isUnsignedInteger("1 0")); //should not contain whitespaces

        assertTrue(StringUtil.isUnsignedInteger("1"));
        assertTrue(StringUtil.isUnsignedInteger("10"));
    }

}

package tars.commons.util;

import org.junit.Test;

import tars.commons.util.StringUtil;

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

public class StringUtilTest {

    @Test
    public void isUnsignedPositiveInteger() {
        assertFalse(StringUtil.isUnsignedInteger(null));
        assertFalse(StringUtil.isUnsignedInteger(""));
        assertFalse(StringUtil.isUnsignedInteger("a"));
        assertFalse(StringUtil.isUnsignedInteger("aaa"));
        assertFalse(StringUtil.isUnsignedInteger("  "));
        assertFalse(StringUtil.isUnsignedInteger("-1"));
        assertFalse(StringUtil.isUnsignedInteger("0"));
        assertFalse(StringUtil.isUnsignedInteger("+1")); //should be unsigned
        assertFalse(StringUtil.isUnsignedInteger("-1")); //should be unsigned
        assertFalse(StringUtil.isUnsignedInteger(" 10")); //should not contain whitespaces
        assertFalse(StringUtil.isUnsignedInteger("10 ")); //should not contain whitespaces
        assertFalse(StringUtil.isUnsignedInteger("1 0")); //should not contain whitespaces

        assertTrue(StringUtil.isUnsignedInteger("1"));
        assertTrue(StringUtil.isUnsignedInteger("10"));
    }

    @Test
    public void containsIgnoreCase() {
        String upperCaseString = "TASK ABC";
        String lowerCaseString = "task";

        assertTrue(StringUtil.containsIgnoreCase(upperCaseString, lowerCaseString));
    }

}

Increase test coverage for StringUtil


package com.zenika.cudf.parser.model;

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

/**
 * @author Antoine Rouaze <antoine.rouaze@zenika.com>
 */
public class CUDFParsedDescriptor {

    public static final String PREAMBLE_START_LINE = "preamble:";
    public static final String PACKAGE_START_LINE = "package: ";
    public static final String REQUEST_START_LINE = "request:";

    private ParsedPreamble preamble;
    private ParsedRequest request;
    private Set<ParsedBinary> packages = new HashSet<ParsedBinary>();

    public ParsedPreamble getPreamble() {
        return preamble;
    }

    public void setPreamble(ParsedPreamble preamble) {
        this.preamble = preamble;
    }

    public ParsedRequest getRequest() {
        return request;
    }

    public void setRequest(ParsedRequest request) {
        this.request = request;
    }

    public Set<ParsedBinary> getPackages() {
        return packages;
    }

    public void setPackages(Set<ParsedBinary> packages) {
        this.packages = packages;
    }
}

package com.zenika.cudf.parser.model;

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

/**
 * @author Antoine Rouaze <antoine.rouaze@zenika.com>
 */
public class CUDFParsedDescriptor {

    public static final String PREAMBLE_START_LINE = "preamble: ";
    public static final String PACKAGE_START_LINE = "package: ";
    public static final String REQUEST_START_LINE = "request: ";

    private ParsedPreamble preamble;
    private ParsedRequest request;
    private Set<ParsedBinary> packages = new HashSet<ParsedBinary>();

    public ParsedPreamble getPreamble() {
        return preamble;
    }

    public void setPreamble(ParsedPreamble preamble) {
        this.preamble = preamble;
    }

    public ParsedRequest getRequest() {
        return request;
    }

    public void setRequest(ParsedRequest request) {
        this.request = request;
    }

    public Set<ParsedBinary> getPackages() {
        return packages;
    }

    public void setPackages(Set<ParsedBinary> packages) {
        this.packages = packages;
    }
}

Add a space into the end of preamble and request lines to respect the CUDF specification.


package com.sleekbyte.tailor.output;

public class ViolationMessage implements Comparable<ViolationMessage> {
    private final String filePath;
    private final int lineNumber;
    private final int columnNumber;
    private final String classification;
    private final String violationMessage;

    public ViolationMessage(String filePath, int lineNumber, int columnNumber, String classification, String violationMessage) {
        this.filePath = filePath;
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber;
        this.classification = classification;
        this.violationMessage = violationMessage;
    }

    @Override
    public int compareTo(final ViolationMessage message) {
        int ret = this.lineNumber - message.lineNumber;
        return ret;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ViolationMessage)) {
            return false;
        }
        ViolationMessage message;
        message = (ViolationMessage)o;
        return this.filePath == message.filePath
                && this.lineNumber == message.lineNumber
                && this.columnNumber == message.columnNumber
                && this.classification == message.classification
                && this.violationMessage == message.violationMessage;
    }

    public String toString() {
        if (columnNumber == 0) {
            return String.format("%s:%d: %s: %s", this.filePath, this.lineNumber, this.classification, this.violationMessage);
        }
        return String.format("%s:%d:%d: %s: %s", this.filePath, this.lineNumber, this.columnNumber, this.classification, this.violationMessage);
    }
}

package com.sleekbyte.tailor.output;

public class ViolationMessage implements Comparable<ViolationMessage> {
    private final String filePath;
    private final int lineNumber;
    private final int columnNumber;
    private final String classification;
    private final String violationMessage;

    public ViolationMessage(String filePath, int lineNumber, int columnNumber, String classification, String violationMessage) {
        this.filePath = filePath;
        this.lineNumber = lineNumber;
        this.columnNumber = columnNumber;
        this.classification = classification;
        this.violationMessage = violationMessage;
    }

    @Override
    public int compareTo(final ViolationMessage message) {
        int ret = this.lineNumber - message.lineNumber;
        if (ret == 0) {
            ret = this.columnNumber - message.columnNumber;
        }
        return ret;
    }

    @Override
    public boolean equals(Object o) {
        if (!(o instanceof ViolationMessage)) {
            return false;
        }
        ViolationMessage message;
        message = (ViolationMessage)o;
        return this.filePath == message.filePath
                && this.lineNumber == message.lineNumber
                && this.columnNumber == message.columnNumber
                && this.classification == message.classification
                && this.violationMessage == message.violationMessage;
    }

    public String toString() {
        if (columnNumber == 0) {
            return String.format("%s:%d: %s: %s", this.filePath, this.lineNumber, this.classification, this.violationMessage);
        }
        return String.format("%s:%d:%d: %s: %s", this.filePath, this.lineNumber, this.columnNumber, this.classification, this.violationMessage);
    }
}

Sort on col num if line num are equal


package com.annimon.hotarufx.bundles;

import com.annimon.hotarufx.lib.Context;
import com.annimon.hotarufx.lib.InterpolatorValue;
import java.util.HashMap;
import java.util.Map;
import javafx.animation.Interpolator;

public class InterpolatorsBundle implements Bundle {

    private static final Map<String, FunctionInfo> FUNCTIONS;
    static {
        FUNCTIONS = new HashMap<>();
    }

    @Override
    public Map<String, FunctionInfo> functionsInfo() {
        return FUNCTIONS;
    }

    @Override
    public void load(Context context) {
        Bundle.super.load(context);
        context.variables().put("linear", new InterpolatorValue(Interpolator.LINEAR));
        context.variables().put("discrete", new InterpolatorValue(Interpolator.DISCRETE));
        context.variables().put("easeIn", new InterpolatorValue(Interpolator.EASE_IN));
        context.variables().put("easeOut", new InterpolatorValue(Interpolator.EASE_OUT));
        context.variables().put("ease", new InterpolatorValue(Interpolator.EASE_BOTH));
        context.variables().put("easeBoth", new InterpolatorValue(Interpolator.EASE_BOTH));
    }
}

package com.annimon.hotarufx.bundles;

import com.annimon.hotarufx.lib.Context;
import com.annimon.hotarufx.lib.InterpolatorValue;
import java.util.HashMap;
import java.util.Map;
import javafx.animation.Interpolator;

public class InterpolatorsBundle implements Bundle {

    private static final Map<String, FunctionInfo> FUNCTIONS;
    static {
        FUNCTIONS = new HashMap<>();
    }

    @Override
    public Map<String, FunctionInfo> functionsInfo() {
        return FUNCTIONS;
    }

    @Override
    public void load(Context context) {
        Bundle.super.load(context);
        context.variables().put("linear", new InterpolatorValue(Interpolator.LINEAR));
        context.variables().put("hold", new InterpolatorValue(Interpolator.DISCRETE));
        context.variables().put("discrete", new InterpolatorValue(Interpolator.DISCRETE));
        context.variables().put("easeIn", new InterpolatorValue(Interpolator.EASE_IN));
        context.variables().put("easeOut", new InterpolatorValue(Interpolator.EASE_OUT));
        context.variables().put("ease", new InterpolatorValue(Interpolator.EASE_BOTH));
        context.variables().put("easeBoth", new InterpolatorValue(Interpolator.EASE_BOTH));
    }
}

Add alias for discrete interpolator


package mb.nabl2.util;

import java.util.Map.Entry;

import org.metaborg.util.functions.Function2;

import io.usethesource.capsule.Map;

public final class CapsuleUtil {

    private CapsuleUtil() {
    }

    public static <K, V> void replace(Map.Transient<K, V> map, Function2<K, V, V> mapper) {
        for(Entry<K, V> entry : map.entrySet()) {
            final K key = entry.getKey();
            final V val = mapper.apply(key, entry.getValue());
            if(val != null) {
                map.__put(key, val);
            } else {
                map.__remove(key);
            }
        }
    }

    public static <K, V> Map.Immutable<K, V> replace(Map.Immutable<K, V> map, Function2<K, V, V> mapper) {
        final Map.Transient<K, V> newMap = Map.Transient.of();
        for(Entry<K, V> entry : map.entrySet()) {
            final K key = entry.getKey();
            final V val = mapper.apply(key, entry.getValue());
            if(val != null) {
                newMap.__put(key, val);
            }
        }
        return newMap.freeze();
    }

}

package mb.nabl2.util;

import java.util.Map.Entry;

import org.metaborg.util.functions.Function2;

import io.usethesource.capsule.Map;
import io.usethesource.capsule.Set;

public final class CapsuleUtil {

    private CapsuleUtil() {
    }

    public static <K, V> void replace(Map.Transient<K, V> map, Function2<K, V, V> mapper) {
        for(Entry<K, V> entry : map.entrySet()) {
            final K key = entry.getKey();
            final V val = mapper.apply(key, entry.getValue());
            if(val != null) {
                map.__put(key, val);
            } else {
                map.__remove(key);
            }
        }
    }

    public static <K, V> Map.Immutable<K, V> replace(Map.Immutable<K, V> map, Function2<K, V, V> mapper) {
        final Map.Transient<K, V> newMap = Map.Transient.of();
        for(Entry<K, V> entry : map.entrySet()) {
            final K key = entry.getKey();
            final V val = mapper.apply(key, entry.getValue());
            if(val != null) {
                newMap.__put(key, val);
            }
        }
        return newMap.freeze();
    }

    @SuppressWarnings("unchecked") public static <V> Set.Immutable<V> toSet(Iterable<? extends V> values) {
        if(values instanceof Set.Immutable) {
            return (Set.Immutable<V>) values;
        }
        Set.Transient<V> set = Set.Transient.of();
        for(V value : values) {
            set.__insert(value);
        }
        return set.freeze();
    }

}

Add method to construct Capsule set from Iterable.


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

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.jmeter.threads.JMeterVariables;

/**
 * @version $Revision$
 */
public class VariablesCollection implements Serializable {
    private Map varMap = new HashMap();

    public void addJMeterVariables(JMeterVariables jmVars) {
        varMap.put(Thread.currentThread().getName(), jmVars);
    }

    public JMeterVariables getVariables() {
        return (JMeterVariables) varMap.get(Thread.currentThread().getName());
    }

}

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

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import org.apache.jmeter.threads.JMeterVariables;

/**
 * @version $Revision$
 */
public class VariablesCollection implements Serializable {

    private static final long serialVersionUID = 240L;

    private Map<String, JMeterVariables> varMap = new HashMap<String, JMeterVariables>();

    public void addJMeterVariables(JMeterVariables jmVars) {
        varMap.put(Thread.currentThread().getName(), jmVars);
    }

    public JMeterVariables getVariables() {
        return varMap.get(Thread.currentThread().getName());
    }

}

Fix up some raw types


/*
 * Copyright 2000-2013 JetBrains s.r.o.
 * Copyright 2014-2014 AS3Boyan
 * Copyright 2014-2014 Elias Ku
 *
 * 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.plugins.haxe.lang.psi.impl;

import com.intellij.lang.ASTFactory;
import com.intellij.lang.ASTNode;
import com.intellij.psi.TokenType;
import com.intellij.psi.impl.source.tree.LazyParseableElement;
import com.intellij.psi.tree.ILazyParseableElementType;

/**
 * Created by ebishton on 9/22/14.
 */
public class HaxeDummyASTNode  extends LazyParseableElement {
  HaxeDummyASTNode(String text) {
    super(TokenType.DUMMY_HOLDER, "DUMMY");
  }

}

/*
 * Copyright 2000-2013 JetBrains s.r.o.
 * Copyright 2014-2014 AS3Boyan
 * Copyright 2014-2014 Elias Ku
 *
 * 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.plugins.haxe.lang.psi.impl;

import com.intellij.lang.ASTFactory;
import com.intellij.lang.ASTNode;
import com.intellij.psi.TokenType;
import com.intellij.psi.impl.source.tree.LazyParseableElement;
import com.intellij.psi.tree.ILazyParseableElementType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Created by ebishton on 9/22/14.
 */
public class HaxeDummyASTNode  extends LazyParseableElement {
  HaxeDummyASTNode(String text) {
    super(TokenType.DUMMY_HOLDER, text);
  }

  public static boolean isDummyNode(@NotNull ASTNode node) {
    return ! (node instanceof HaxeDummyASTNode);
  }

  public static boolean isUsableNode(@Nullable ASTNode node) {
    return null != node && !isDummyNode(node);
  }
}

Add two utility functions to HaxeDummyNode to detect whether a node is a dummy node.


package com.carpentersblocks.util.protection;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;

public class ProtectedObject {

    public EntityPlayer entityPlayer;

    public ProtectedObject(EntityPlayer entityPlayer)
    {
        this.entityPlayer = entityPlayer;
    }

    @Override
    public String toString()
    {
        if (FMLCommonHandler.instance().getSide() == Side.SERVER) {
            boolean onlineMode = ((EntityPlayerMP)entityPlayer).mcServer.isServerInOnlineMode();
            if (onlineMode) {
                return entityPlayer.getUniqueID().toString();
            } else {
                return entityPlayer.getDisplayName();
            }
        } else {
            return "";
        }
    }

}

package com.carpentersblocks.util.protection;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;

public class ProtectedObject {

    public EntityPlayer entityPlayer;

    public ProtectedObject(EntityPlayer entityPlayer)
    {
        this.entityPlayer = entityPlayer;
    }

    @Override
    public String toString()
    {
        if (FMLCommonHandler.instance().getSide() == Side.SERVER) {
            boolean onlineMode = ((EntityPlayerMP)entityPlayer).mcServer.isServerInOnlineMode();
            if (onlineMode) {
                return entityPlayer.getUniqueID().toString();
            } else {
                return entityPlayer.getDisplayName();
            }
        } else {
            return entityPlayer.getDisplayName();
        }
    }

}

Store player name as owner by default. Should further help singleplayer ownership issues.


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

import org.springframework.stereotype.Service;

import ch.ralscha.extdirectspring.annotation.ExtDirectMethod;

@Service
public class TestAction {

	@ExtDirectMethod(group = "example")
	public long multiply(Long num) {
		if (num != null) {
			return num * 8;
		}
		return 0;
	}

	@ExtDirectMethod(group = "example")
	public String doEcho(String message) {
		return message;
	}

}

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

import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Service;

import ch.ralscha.extdirectspring.annotation.ExtDirectMethod;

@Service
public class TestAction {

	@ExtDirectMethod(group = "example")
	public long multiply(Long num) {
		if (num != null) {
			return num * 8;
		}
		return 0;
	}

	@ExtDirectMethod(group = "example")
	public String doEcho(String message) {
		return message;
	}

	@ExtDirectMethod(group = "example")
	public int oneMinuteRunning(int a) throws InterruptedException {
		TimeUnit.MINUTES.sleep(1);
		return a+1;
	}

}

Add a long running method for testing


package com.hubspot.jinjava.interpret;

import com.fasterxml.jackson.annotation.JsonValue;
import java.util.function.Supplier;

public class LazyExpression implements Supplier {
  private final Supplier supplier;
  private final String image;
  private final boolean memoize;
  private Object jsonValue = null;

  private LazyExpression(Supplier supplier, String image, boolean memoize) {
    this.supplier = supplier;
    this.image = image;
    this.memoize = memoize;
  }

  public static LazyExpression of(Supplier supplier, String image) {
    return new LazyExpression(supplier, image, true);
  }

  public static LazyExpression of(Supplier supplier, String image, boolean memoize) {
    return new LazyExpression(supplier, image, memoize);
  }

  @Override
  public Object get() {
    if (jsonValue == null || !memoize) {
      jsonValue = supplier.get();
    }
    return jsonValue;
  }

  @Override
  public String toString() {
    return image;
  }

  @JsonValue
  public Object getJsonValue() {
    return jsonValue == null ? "" : jsonValue;
  }
}

package com.hubspot.jinjava.interpret;

import com.fasterxml.jackson.annotation.JsonValue;
import java.util.function.Supplier;

public class LazyExpression implements Supplier {
  private final Supplier supplier;
  private final String image;
  private final MEMOIZATION memoization;
  private Object jsonValue = null;

  public enum MEMOIZATION {
    ON,
    OFF
  }

  private LazyExpression(Supplier supplier, String image, MEMOIZATION memoization) {
    this.supplier = supplier;
    this.image = image;
    this.memoization = memoization;
  }

  public static LazyExpression of(Supplier supplier, String image) {
    return new LazyExpression(supplier, image, MEMOIZATION.ON);
  }

  public static LazyExpression of(
    Supplier supplier,
    String image,
    MEMOIZATION memoization
  ) {
    return new LazyExpression(supplier, image, memoization);
  }

  @Override
  public Object get() {
    if (jsonValue == null || memoization == MEMOIZATION.OFF) {
      jsonValue = supplier.get();
    }
    return jsonValue;
  }

  @Override
  public String toString() {
    return image;
  }

  @JsonValue
  public Object getJsonValue() {
    return jsonValue == null ? "" : jsonValue;
  }
}

Switch from boolean to enum for memoization argument


package com.msgilligan.peerlist.config;

import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.net.discovery.DnsDiscovery;
import org.bitcoinj.net.discovery.PeerDiscovery;
import org.bitcoinj.net.discovery.SeedPeers;
import org.bitcoinj.params.MainNetParams;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileNotFoundException;

/**
 * User: sean
 * Date: 2/22/14
 * Time: 7:56 PM
 */
@Configuration
public class BitcoinConfig {
    @Bean
    public NetworkParameters networkParameters() {
        return MainNetParams.get();
    }

    @Bean
    public PeerDiscovery peerDiscovery(NetworkParameters params) throws FileNotFoundException {
        PeerDiscovery pd;
//        pd = new DnsDiscovery(params);
        pd = new SeedPeers(params);
        return pd;
    }
}

package com.msgilligan.peerlist.config;

import org.bitcoinj.core.NetworkParameters;
import org.bitcoinj.net.discovery.DnsDiscovery;
import org.bitcoinj.net.discovery.PeerDiscovery;
import org.bitcoinj.net.discovery.SeedPeers;
import org.bitcoinj.params.MainNetParams;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.FileNotFoundException;

/**
 * User: sean
 * Date: 2/22/14
 * Time: 7:56 PM
 */
@Configuration
public class BitcoinConfig {
    @Bean
    public NetworkParameters networkParameters() {
        return MainNetParams.get();
    }

    @Bean
    public PeerDiscovery peerDiscovery(NetworkParameters params) throws FileNotFoundException {
        PeerDiscovery pd;
        pd = new DnsDiscovery(params);
//        pd = new SeedPeers(params);
        return pd;
    }
}

Switch to DNS peer discovery.


package com.dottydingo.hyperion.service.marshall;

import com.dottydingo.hyperion.exception.BadRequestException;
import com.dottydingo.hyperion.exception.InternalException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.InputStream;
import java.io.OutputStream;

/**
 */
public class EndpointMarshaller
{
    private ObjectMapper objectMapper;

    public EndpointMarshaller()
    {
        try
        {
            objectMapper = new ObjectMapperBuilder().getObject();
        }
        catch (Exception ignore){}
    }

    public void setObjectMapper(ObjectMapper objectMapper)
    {
        this.objectMapper = objectMapper;
    }

    public <T> T unmarshall(InputStream inputStream, Class<T> type)
    {
        try
        {
            return objectMapper.readValue(inputStream,type);
        }
        catch (Exception e)
        {
            throw new BadRequestException("Error unmarshalling request.",e);
        }
    }

    public <T> void marshall(OutputStream outputStream, T value)
    {
        try
        {
            objectMapper.writeValue(outputStream,value);
        }
        catch(Exception e)
        {
            throw new InternalException("Error marhsalling response.",e);
        }

    }
}

package com.dottydingo.hyperion.service.marshall;

import com.dottydingo.hyperion.exception.BadRequestException;
import com.dottydingo.hyperion.exception.InternalException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.InputStream;
import java.io.OutputStream;

/**
 */
public class EndpointMarshaller
{
    private ObjectMapper objectMapper;

    public EndpointMarshaller()
    {
        try
        {
            objectMapper = new ObjectMapperBuilder().getObject();
        }
        catch (Exception ignore){}
    }

    public void setObjectMapper(ObjectMapper objectMapper)
    {
        this.objectMapper = objectMapper;
    }

    public <T> T unmarshall(InputStream inputStream, Class<T> type)
    {
        try
        {
            return objectMapper.readValue(inputStream,type);
        }
        catch (Exception e)
        {
            throw new BadRequestException(String.format("Error unmarshalling request: %s",e.getMessage()),e);
        }
    }

    public <T> void marshall(OutputStream outputStream, T value)
    {
        try
        {
            objectMapper.writeValue(outputStream,value);
        }
        catch(Exception e)
        {
            throw new InternalException("Error marhsalling response.",e);
        }

    }
}

Add more detail to unmarshalling errors


package de.fh_bielefeld.newsboard.model;

import java.util.OptionalDouble;
import java.util.OptionalInt;

/**
 * Domain class representing a classification of a document or sentence.
 *
 * @author Felix Meyer, Lukas Taake
 */
public class Classification {
    private OptionalInt sentenceId = OptionalInt.empty();
    private OptionalInt documentId = OptionalInt.empty();
    private ExternModule externModule;
    private double value;
    private OptionalDouble confidence = OptionalDouble.empty();

    public OptionalInt getSentenceId() {
        return sentenceId;
    }

    public void setSentenceId(int sentenceId) {
        this.sentenceId = OptionalInt.of(sentenceId);
    }

    public OptionalInt getDocumentId() {
        return documentId;
    }

    public void setDocumentId(int documentId) {
        this.documentId = OptionalInt.of(documentId);
    }

    public ExternModule getExternModule() {
        return externModule;
    }

    public void setExternModule(ExternModule externModule) {
        this.externModule = externModule;
    }

    public double getValue() {
        return value;
    }

    public void setValue(double value) {
        this.value = value;
    }

    public OptionalDouble getConfidence() {
        return confidence;
    }

    public void setConfidence(double confidence) {
        this.confidence = OptionalDouble.of(confidence);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof Classification)) {
            return false;
        }
        Classification that = (Classification) obj;
        return this.documentId.equals(that.documentId)
                && this.sentenceId.equals(that.sentenceId)
                && this.externModule.equals(that.externModule);
    }
}

package de.fh_bielefeld.newsboard.model;

import java.util.OptionalDouble;
import java.util.OptionalInt;

/**
 * Domain class representing a classification of a document or sentence.
 *
 * @author Felix Meyer, Lukas Taake
 */
public class Classification {
    private OptionalInt sentenceId = OptionalInt.empty();
    private ExternModule externModule;
    private double value;
    private OptionalDouble confidence = OptionalDouble.empty();

    public OptionalInt getSentenceId() {
        return sentenceId;
    }

    public void setSentenceId(int sentenceId) {
        this.sentenceId = OptionalInt.of(sentenceId);
    }

    public ExternModule getExternModule() {
        return externModule;
    }

    public void setExternModule(ExternModule externModule) {
        this.externModule = externModule;
    }

    public double getValue() {
        return value;
    }

    public void setValue(double value) {
        this.value = value;
    }

    public OptionalDouble getConfidence() {
        return confidence;
    }

    public void setConfidence(double confidence) {
        this.confidence = OptionalDouble.of(confidence);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof Classification)) {
            return false;
        }
        Classification that = (Classification) obj;
        return this.sentenceId.equals(that.sentenceId)
                && this.externModule.equals(that.externModule);
    }
}

Document class changed for recent model changes.


package info.u_team.u_team_core.util.world;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.*;

public class WorldUtil {

	public static RayTraceResult rayTraceServerSide(EntityPlayer player, double range) {
		return rayTraceServerSide(player, range, RayTraceFluidMode.NEVER, false, true);
	}

	public static RayTraceResult rayTraceServerSide(EntityPlayer player, double range, RayTraceFluidMode liquidMode, boolean ignoreBlockWithoutBoundingBox, boolean returnLastUncollidableBlock) {
		Vec3d playerVector = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ);
		Vec3d lookVector = player.getLookVec();
		Vec3d locationVector = playerVector.add(lookVector.x * range, lookVector.y * range, lookVector.z * range);
		return player.world.rayTraceBlocks(playerVector, locationVector, liquidMode, ignoreBlockWithoutBoundingBox, returnLastUncollidableBlock);
	}
}

package info.u_team.u_team_core.util.world;

import java.util.function.Function;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.*;
import net.minecraft.world.World;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.storage.WorldSavedData;

public class WorldUtil {

	public static RayTraceResult rayTraceServerSide(EntityPlayer player, double range) {
		return rayTraceServerSide(player, range, RayTraceFluidMode.NEVER, false, true);
	}

	public static RayTraceResult rayTraceServerSide(EntityPlayer player, double range, RayTraceFluidMode liquidMode, boolean ignoreBlockWithoutBoundingBox, boolean returnLastUncollidableBlock) {
		Vec3d playerVector = new Vec3d(player.posX, player.posY + player.getEyeHeight(), player.posZ);
		Vec3d lookVector = player.getLookVec();
		Vec3d locationVector = playerVector.add(lookVector.x * range, lookVector.y * range, lookVector.z * range);
		return player.world.rayTraceBlocks(playerVector, locationVector, liquidMode, ignoreBlockWithoutBoundingBox, returnLastUncollidableBlock);
	}

	public static <T extends WorldSavedData> T getSaveData(World world, String name, Function<String, T> function) {
		final DimensionType type = world.getDimension().getType();
		T instance = world.getSavedData(type, function, name);
		if (instance == null) {
			instance = function.apply(name);
			world.setSavedData(type, name, instance);
		}
		return instance;
	}
}

Add a method to get savedata from the world quit easy


//@@author A0121621Y
package jfdi.storage.exceptions;

import jfdi.storage.apis.TaskAttributes;

@SuppressWarnings("serial")
public class DuplicateTaskException extends Exception {

    private TaskAttributes duplicateTaskAttributes = null;

    public DuplicateTaskException(TaskAttributes taskAttributes) {
        duplicateTaskAttributes = taskAttributes;
    }

    /**
     * @return the duplicate task attributes
     */
    public TaskAttributes getDuplicateTaskAttributes() {
        return duplicateTaskAttributes;
    }

}

Add newline after collate comment


/*
 * JBoss, Home of Professional Open Source
 * Copyright 2010, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.remoting3.test;

import java.io.Serializable;

public final class InvocationTestObject implements Serializable {
    private static final long serialVersionUID = 7228470862155215008L;
}

/*
 * JBoss, Home of Professional Open Source
 * Copyright 2010, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

package org.jboss.remoting3.test;

import java.io.Serializable;

public final class InvocationTestObject implements Serializable {
    private static final long serialVersionUID = 7228470862155215008L;

    private final int frob = 12345;

    public int getFrob() {
        return frob;
    }

    public boolean equals(final Object obj) {
        return obj instanceof InvocationTestObject && equals((InvocationTestObject) obj);
    }

    public boolean equals(final InvocationTestObject obj) {
        return obj != null && obj.frob == frob;
    }

    public int hashCode() {
        return frob;
    }
}

Implement equals/hashCode on test object so equals assertions work across remote connections