package com.orientechnologies.orient.core.db.tool.importer;

import com.orientechnologies.orient.core.db.record.OIdentifiable;

/** Created by tglman on 28/07/17. */
public abstract class OAbstractCollectionConverter<T> implements OValuesConverter<T> {
  private final OConverterData converterData;

  protected OAbstractCollectionConverter(OConverterData converterData) {
    this.converterData = converterData;
  }

  public interface ResultCallback {
    void add(Object item);
  }

  protected boolean convertSingleValue(final Object item, ResultCallback result, boolean updated) {
    if (item == null) return false;

    if (item instanceof OIdentifiable) {
      final OValuesConverter<OIdentifiable> converter =
          (OValuesConverter<OIdentifiable>)
              OImportConvertersFactory.INSTANCE.getConverter(item, converterData);

      final OIdentifiable newValue = converter.convert((OIdentifiable) item);

      // this code intentionally uses == instead of equals, in such case we may distinguish rids
      // which already contained in
      // document and RID which is used to indicate broken record
      if (newValue != OImportConvertersFactory.BROKEN_LINK) result.add(newValue);

      if (!newValue.equals(item)) updated = true;
    } else {
      final OValuesConverter valuesConverter =
          OImportConvertersFactory.INSTANCE.getConverter(item.getClass(), converterData);
      if (valuesConverter == null) result.add(item);
      else {
        final Object newValue = valuesConverter.convert(item);
        if (newValue != item) updated = true;

        result.add(newValue);
      }
    }

    return updated;
  }
}

package com.orientechnologies.orient.core.db.tool.importer;

import com.orientechnologies.orient.core.db.record.OIdentifiable;

/** Created by tglman on 28/07/17. */
public abstract class OAbstractCollectionConverter<T> implements OValuesConverter<T> {
  private final OConverterData converterData;

  protected OAbstractCollectionConverter(OConverterData converterData) {
    this.converterData = converterData;
  }

  public interface ResultCallback {
    void add(Object item);
  }

  protected boolean convertSingleValue(final Object item, ResultCallback result, boolean updated) {
    if (item == null) return false;

    if (item instanceof OIdentifiable) {
      final OValuesConverter<OIdentifiable> converter =
          (OValuesConverter<OIdentifiable>)
              OImportConvertersFactory.INSTANCE.getConverter(item, converterData);

      final OIdentifiable newValue = converter.convert((OIdentifiable) item);

      // this code intentionally uses == instead of equals, in such case we may distinguish rids
      // which already contained in
      // document and RID which is used to indicate broken record
      if (newValue != OImportConvertersFactory.BROKEN_LINK) result.add(newValue);

      if (!newValue.equals(item)) updated = true;
    } else {
      final OValuesConverter valuesConverter =
          OImportConvertersFactory.INSTANCE.getConverter(item, converterData);
      if (valuesConverter == null) result.add(item);
      else {
        final Object newValue = valuesConverter.convert(item);
        if (newValue != item) updated = true;

        result.add(newValue);
      }
    }

    return updated;
  }
}

Fix import with links in embedded collections of maps


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

package com.google.crypto.tink;

import java.security.GeneralSecurityException;

/**
 * Interface for public key signing.
 *
 *
Digital Signatures provide functionality of signing data and verification of the signatures.
 *
 *
Security guarantees

 *
 *
The functionality of Digital Signatures is represented a pair of primitives (interfaces)
 * {@link PublicKeySign} for signing of data, and {@link PublicKeyVerify} for verification of
 * signatures. Implementations of these interfaces are secure against adaptive chosen-message
 * attacks. Signing data ensures the authenticity and the integrity of that data, but not its
 * secrecy.
 *
 * @since 1.0.0
 */
public interface PublicKeySign {
  /**
   * Computes the signature for {@code data}.
   *
   * @return the signature of {$code data}
   */
  byte[] sign(final byte[] data) throws GeneralSecurityException;
}

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

package com.google.crypto.tink;

import java.security.GeneralSecurityException;

/**
 * Interface for public key signing.
 *
 *
Digital Signatures provide functionality of signing data and verification of the signatures.
 *
 *
Security guarantees

 *
 *
The functionality of Digital Signatures is represented a pair of primitives (interfaces)
 * {@link PublicKeySign} for signing of data, and {@link PublicKeyVerify} for verification of
 * signatures. Implementations of these interfaces are secure against adaptive chosen-message
 * attacks. Signing data ensures the authenticity and the integrity of that data, but not its
 * secrecy.
 *
 * @since 1.0.0
 */
public interface PublicKeySign {
  /**
   * Computes the signature for {@code data}.
   *
   * @return the signature of {@code data}
   */
  byte[] sign(final byte[] data) throws GeneralSecurityException;
}

Fix typo in Javadoc tag for sign() return description.


package pt.up.fe.comp.utils;

import java.util.Stack;

public class SymbolTable<T> {

    public SymbolTable(boolean lazy) {
        _lazy = lazy;
        beginScope();
    }

    public void beginScope() {
        _scopes.add(new Scope<T>(_lazy));
    }

    public void endScope() {
        // do not delete "global" scope
        if (_scopes.size() > 1)
            _scopes.pop();
    }

    public void setLazy(boolean value) {
        _lazy = value;
        for (Scope<T> scp : _scopes) {
            scp.setLazy(value);
        }
    }

    public void addSymbol(String name, Class type, Producer<T> init) {
        _scopes.peek().addSymbol(name, type, init);
    }

    public boolean contains(String name) {
        return get(name) != null;
    }

    public T get(String name) {
        T value;
        for (Scope<T> scp : _scopes) {
            value = scp.getSymbol(name);
            if (value != null) return value;
        }
        return null;
    }

    public Class getType(String name) {
        Class type;
        for (Scope<T> scp : _scopes) {
            type = scp.getSymbolType(name);
            if (type != null) return type;
        }
        return null;
    }

    private Stack<Scope<T>> _scopes = new Stack<>();
    private boolean _lazy;
}

package pt.up.fe.comp.utils;

import java.util.Stack;

public class SymbolTable<T> {

    public SymbolTable(boolean lazy) {
        _lazy = lazy;
        beginScope();
    }

    public void beginScope() {
        _scopes.add(new Scope<T>(_lazy));
    }

    public void endScope() {
        // do not delete "global" scope
        if (_scopes.size() > 1)
            _scopes.pop();
    }

    public void setLazy(boolean value) {
        _lazy = value;
        for (Scope<T> scp : _scopes) {
            scp.setLazy(value);
        }
    }

    public void addSymbol(String name, Class type, Producer<T> init) {
        if (!contains(name))
            _scopes.peek().addSymbol(name, type, init);
        else throw new Error(name + " is already declared.");
    }

    public boolean contains(String name) {
        return get(name) != null;
    }

    public T get(String name) {
        T value;
        for (Scope<T> scp : _scopes) {
            value = scp.getSymbol(name);
            if (value != null) return value;
        }
        return null;
    }

    public Class getType(String name) {
        Class type;
        for (Scope<T> scp : _scopes) {
            type = scp.getSymbolType(name);
            if (type != null) return type;
        }
        return null;
    }

    private Stack<Scope<T>> _scopes = new Stack<>();
    private boolean _lazy;
}

Add check for redeclared symbols.


package com.woopra;

import java.util.Properties;
/**
 * @author Woopra on 1/26/2013
 *
 */
public class WoopraEvent {
	private String eventName = null;
	private Properties properties = null;

	public WoopraEvent(String eventName) {
		super(eventName, new Properties();
	}

	public WoopraEvent(String eventName, Properties properties) {
		this.properties = properties;
		this.properties.setProperty("name", eventName);
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public void addEventProperties(Properties newProperties) {
		properties.putAll(newProperties);
	}

	public void addEventProperty(String key, String value) {
		properties.setProperty(key, value);
	}
}

package com.woopra;

import java.util.Properties;
/**
 * @author Woopra on 1/26/2013
 *
 */
public class WoopraEvent {
	private String eventName = null;
	private Properties properties = null;

	public WoopraEvent(String eventName) {
		super(eventName, new Properties();
	}

	public WoopraEvent(String eventName, Properties properties) {
		this.properties = properties;
		if (this.properties == null) {
			this.properties = new Properties();
		}
		this.properties.setProperty("name", eventName);
	}

	public Properties getProperties() {
		return properties;
	}

	public void setProperties(Properties properties) {
		this.properties = properties;
	}

	public void addEventProperties(Properties newProperties) {
		properties.putAll(newProperties);
	}

	public void addEventProperty(String key, String value) {
		properties.setProperty(key, value);
	}
}

Fix event name not being added in constructor.


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

package io.fabric8.spring.cloud.discovery;

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

@ConfigurationProperties("spring.cloud.kubernetes.discovery")
public class KubernetesDiscoveryProperties {

    private boolean enabled = true;
    private String serviceName = "unknown";

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getServiceName() {
        return serviceName;
    }
}

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

package io.fabric8.spring.cloud.discovery;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties("spring.cloud.kubernetes.discovery")
public class KubernetesDiscoveryProperties {

    private boolean enabled = true;

    @Value("${spring.application.name:unknown}")
    private String serviceName = "unknown";

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public String getServiceName() {
        return serviceName;
    }
}

Use the application name as the default local service id in KubernetesDiscovery.


import datastructures.PriorityQueue;
import java.util.*;

public class PriorityQueueTest {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 5; i ++) {
            testRandomSort(10000 + ((int) (Math.random() * 10000)));
        }
    }

    private static void testRandomSort(int count) throws Exception {
        System.out.printf("\tRandomSort (n = %d)\n", count);
        PriorityQueue<Integer> q = new PriorityQueue<>();
        for (int i = 0; i < count; i ++) {
            q.add((int) (Math.random() * Integer.MAX_VALUE));
        }

        if (q.isEmpty()) {
            throw new Exception("Queue is empty");
        }

        if (q.size() != count) {
            throw new Exception("Queue size is incorrect");
        }

        int prev = q.poll();

        while (!q.isEmpty()) {
            int curr = q.poll();

            if (curr < prev) {
                throw new Exception("Incorrect poll order");
            }
            prev = curr;
        }
    }
}

import datastructures.PriorityQueue;
import java.util.*;

public class PriorityQueueTest {
    public static void main(String[] args) throws Exception {
        for (int i = 0; i < 5; i ++) {
            testRandomSort(10000 + ((int) (Math.random() * 10000)));
            testRandomSortAndInsert(10000 + ((int) (Math.random() * 10000)));
        }
    }

    private static void testRandomSort(int count) throws Exception {
        System.out.printf("\tRandomSort (n = %d)\n", count);
        PriorityQueue<Integer> q = new PriorityQueue<>();
        for (int i = 0; i < count; i ++) {
            q.add((int) (Math.random() * Integer.MAX_VALUE));
        }

        if (q.isEmpty()) {
            throw new Exception("Queue is empty");
        }

        if (q.size() != count) {
            throw new Exception("Queue size is incorrect");
        }

        int prev = q.poll();

        while (!q.isEmpty()) {
            int curr = q.poll();

            if (curr < prev) throw new Exception("Incorrect poll order");
            prev = curr;
        }
    }

    private static void testRandomSortAndInsert(int count) throws Exception {
        System.out.printf("\tRandomSortAndInsert (n = %d)\n", count);
        PriorityQueue<Integer> q = new PriorityQueue<>();
        for (int i = 0; i < count; i ++) {
            q.add((int) (Math.random() * Integer.MAX_VALUE));
        }

        if (q.isEmpty()) {
            throw new Exception("Queue is empty");
        }

        if (q.size() != count) {
            throw new Exception("Queue size is incorrect");
        }

        while (!q.isEmpty()) {
            int curr = q.poll();
            if (q.isEmpty()) break;
            int next = q.poll();

            if (curr > next) throw new Exception("Incorrect poll order");

            if (Math.random() < 0.5) {
                q.add((int) (Math.random() * Integer.MAX_VALUE));
            }
        }
    }
}

Add sort and insert heap test


package bean;

import java.net.URI;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;

import org.eclipse.microprofile.rest.client.RestClientBuilder;

import bean.MarkdownBean.SyntaxHighlighter;
import lombok.SneakyThrows;

@ApplicationScoped
public class HiliteMeHighlighter implements SyntaxHighlighter {

	interface HiliteMeService {
		@POST
		String highlight(
			@FormParam("code") String code,
			@FormParam("lexer") String lexer,
			@FormParam("linenos") boolean lineNos,
			@FormParam("style") String style
		);
	}

	@Override
	@SneakyThrows
	public String highlight(String text, String language) {
		// TODO use embedded Python interpreter?
		URI apiUri = new URI("http://hilite.me/api"); //$NON-NLS-1$
		HiliteMeService hiliteMe = RestClientBuilder.newBuilder()
			.baseUri(apiUri)
			.build(HiliteMeService.class);
		return hiliteMe.highlight(text, language, true, "colorful"); //$NON-NLS-1$
	}

}

package bean;

import java.net.URI;

import javax.enterprise.context.ApplicationScoped;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;

import org.eclipse.microprofile.rest.client.RestClientBuilder;

import bean.MarkdownBean.SyntaxHighlighter;
import lombok.SneakyThrows;

@ApplicationScoped
public class HiliteMeHighlighter implements SyntaxHighlighter {

	public interface HiliteMeService {
		@POST
		String highlight(
			@FormParam("code") String code,
			@FormParam("lexer") String lexer,
			@FormParam("linenos") boolean lineNos,
			@FormParam("style") String style
		);
	}

	@Override
	@SneakyThrows
	public String highlight(String text, String language) {
		// TODO use embedded Python interpreter?
		URI apiUri = new URI("http://hilite.me/api"); //$NON-NLS-1$
		HiliteMeService hiliteMe = RestClientBuilder.newBuilder()
			.baseUri(apiUri)
			.build(HiliteMeService.class);
		return hiliteMe.highlight(text, language, true, "colorful"); //$NON-NLS-1$
	}

}

Make HiliteMeService public for CDI


package data.trainnetwork;

import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;

/**
 * A class representing a Seat within section
 * @author Balazs Pete
 *
 */
public class Seat implements Serializable {

	private String id, sectionId = null;

	/**
	 * Create a new Seat
	 * @param id
	 */
	public Seat() {
		this.id = new BigInteger(130, new SecureRandom()).toString(32);
	}

	/**
	 * Get the ID of the Seat
	 * @return
	 */
	public String getId() {
		return id;
	}

	/**
	 * Add the corresponding {@link Section} (will be stored as an ID reference)
	 * @param section The section the seat belongs to
	 */
	public void addSection(Section section) {
		sectionId = section.getID();
	}

	/**
	 * Get the ID of the corresponding {@link Section}
	 * @return The id of the section
	 */
	public String getSectionId() {
		return sectionId;
	}

	/**
	 * Compare another seat with this one
	 * @param seat The other seat to compare with
	 * @return True if the two seats are identical
	 */
	public boolean equals(Seat seat) {
		return id.equals(seat.getId());
	}
}

package data.trainnetwork;

import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;

/**
 * A class representing a Seat within section
 * @author Balazs Pete
 *
 */
public class Seat implements Serializable {

	/**
	 *
	 */
	private static final long serialVersionUID = 3197202742981022435L;

	private String id, sectionId = null;

	/**
	 * Create a new Seat
	 * @param id
	 */
	public Seat() {
		this.id = new BigInteger(130, new SecureRandom()).toString(32);
	}

	/**
	 * Get the ID of the Seat
	 * @return
	 */
	public String getId() {
		return id;
	}

	/**
	 * Add the corresponding {@link Section} (will be stored as an ID reference)
	 * @param section The section the seat belongs to
	 */
	public void addSection(Section section) {
		sectionId = section.getID();
	}

	/**
	 * Get the ID of the corresponding {@link Section}
	 * @return The id of the section
	 */
	public String getSectionId() {
		return sectionId;
	}

	/**
	 * Compare another seat with this one
	 * @param seat The other seat to compare with
	 * @return True if the two seats are identical
	 */
	public boolean equals(Seat seat) {
		return id.equals(seat.getId());
	}
}

Add serial id to seat


package com.rollbar.jvmti;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * CacheFrame is a frame generated from the native interface to hold a method and a list of local
 * variables for later use.
 */
public final class CacheFrame {
  private Method method;
  private final LocalVariable[] locals;

  /**
   * Constructor with the method and list of local variables.
   */
  public CacheFrame(Method method, LocalVariable[] locals) {
    this.method = method;
    this.locals = locals;
  }

  /**
   * Getter.
   *
   * @return the method that generated this frame.
   */
  public Method getMethod() {
    return method;
  }

  /**
   * Getter.
   *
   * @return the local variables for this frame.
   */
  public Map<String, Object> getLocals() {
    if (locals == null || locals.length == 0) {
      return Collections.emptyMap();
    }

    Map<String, Object> localsMap = new HashMap<>();
    for (LocalVariable localVariable : locals) {
      if (localVariable != null) {
        localsMap.put(localVariable.getName(), localVariable.getValue());
      }
    }

    return localsMap;
  }

  @Override
  public String toString() {
    return "CacheFrame{"
      + ", locals=" + Arrays.toString(locals)
      + '}';
  }
}

package com.rollbar.jvmti;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * CacheFrame is a frame generated from the native interface to hold a method and a list of local
 * variables for later use.
 */
public final class CacheFrame {
  private Method method;
  private final LocalVariable[] locals;

  /**
   * Constructor with the method and list of local variables.
   */
  public CacheFrame(Method method, LocalVariable[] locals) {
    this.method = method;
    this.locals = Arrays.copyOf(locals, locals.length);
  }

  /**
   * Getter.
   *
   * @return the method that generated this frame.
   */
  public Method getMethod() {
    return method;
  }

  /**
   * Getter.
   *
   * @return the local variables for this frame.
   */
  public Map<String, Object> getLocals() {
    if (locals == null || locals.length == 0) {
      return Collections.emptyMap();
    }

    Map<String, Object> localsMap = new HashMap<>();
    for (LocalVariable localVariable : locals) {
      if (localVariable != null) {
        localsMap.put(localVariable.getName(), localVariable.getValue());
      }
    }

    return localsMap;
  }

  @Override
  public String toString() {
    return "CacheFrame{"
      + ", locals=" + Arrays.toString(locals)
      + '}';
  }
}

Make the findbugs checker happy


package tetris.game;

import java.awt.*;
import javax.swing.*;

public class MainConsole{

    private JFrame frame;
    private Canvas canvas;

    public MainConsole(){
        frame = new JFrame("Tetris");
        frame.setSize((Canvas.WIDTH + 7) * Canvas.SIDE_OF_SQUARE,
            (Canvas.HEIGHT + 1) * Canvas.SIDE_OF_SQUARE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);

        canvas = new Canvas();
        frame.addKeyListener(canvas.getKeyListener());
        frame.add(canvas,BorderLayout.CENTER);
    }

    public static void main(String [] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
                new MainConsole();
            }
        });
    }
}

package tetris.game;

import java.awt.*;
import javax.swing.*;

public class MainConsole{

    private JFrame frame;
    private Canvas canvas;

    public MainConsole(){
        frame = new JFrame("Tetris");
        frame.setSize((Canvas.WIDTH + 7) * Canvas.SIDE_OF_SQUARE,
            (Canvas.HEIGHT + 1) * Canvas.SIDE_OF_SQUARE);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setResizable(false);
	frame.setLocationRelativeTo(null);

        canvas = new Canvas();
        frame.addKeyListener(canvas.getKeyListener());
        frame.add(canvas,BorderLayout.CENTER);
    }

    public static void main(String [] args){
        SwingUtilities.invokeLater(new Runnable(){
            @Override
            public void run(){
		JOptionPane.showMessageDialog(null, 	"Press [up] key to rotate the blocks\n" +
							"Press [down] key to move the blocks down\n" +
							"Press [left] key to move the blocks to the left\n" +
							"Press [right] key to move the blocks to the right\n" +
							"Press [space] key to move the blocks all the way down\n" +
							"Press [P] key to pause the game\n" +
							"Press [R] key to resume the game\n");
                new MainConsole();
            }
        });
    }
}

Update description with Canvas class


/*
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      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 quantize;

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

/** Creates a dictionary with keys of colors, and values of count of the color */
public final class QuantizerMap implements Quantizer {
  Map<Integer, Integer> colorToCount;

  @Override
  public QuantizerResult quantize(int[] pixels, int colorCount) {
    final HashMap<Integer, Integer> pixelByCount = new HashMap<>();
    for (int pixel : pixels) {
      pixelByCount.merge(pixel, 1, (Integer count, Integer newValue) -> count + newValue);
    }
    colorToCount = pixelByCount;
    return new QuantizerResult(pixelByCount);
  }

  public Map<Integer, Integer> getColorToCount() {
    return colorToCount;
  }
}

/*
 * Copyright 2021 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      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 quantize;

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

/** Creates a dictionary with keys of colors, and values of count of the color */
public final class QuantizerMap implements Quantizer {
  Map<Integer, Integer> colorToCount;

  @Override
  public QuantizerResult quantize(int[] pixels, int colorCount) {
    final HashMap<Integer, Integer> pixelByCount = new HashMap<>();
    for (int pixel : pixels) {
      final Integer currentPixelCount = pixelByCount.get(pixel);
      final int newPixelCount = currentPixelCount == null ? 1 : currentPixelCount + 1;
      pixelByCount.put(pixel, newPixelCount);
    }
    colorToCount = pixelByCount;
    return new QuantizerResult(pixelByCount);
  }

  public Map<Integer, Integer> getColorToCount() {
    return colorToCount;
  }
}

Remove `HashMap.merge`, which is absent in Java7.


package it.gov.aifa.invoice_processor.service.persistence;
import org.springframework.data.repository.PagingAndSortingRepository;

import it.gov.aifa.invoice_processor.entity.invoice.InvoiceVersion;

public interface InvoiceVersionRepository extends PagingAndSortingRepository<InvoiceVersion, String> {
}

package it.gov.aifa.invoice_processor.service.persistence;
import org.springframework.data.repository.CrudRepository;

import it.gov.aifa.invoice_processor.entity.invoice.InvoiceVersion;

public interface InvoiceVersionRepository extends CrudRepository<InvoiceVersion, String> {
}

Use a CrudRepository instead of a PagingAndSortingRepository


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

package org.junit.gen5.commons.util;

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

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

public class FindClassesInPackageTest {

	@Test
	public void findAllClassesInThisPackage() throws IOException, ClassNotFoundException {
		List<Class<?>> classes = Arrays.asList(ReflectionUtils.findAllClassesInPackage("org.junit.gen5.commons"));
		System.out.println("Number of classes found: " + classes.size());
		for (Class<?> clazz : classes) {
			System.out.println(clazz.getName());
		}
		Assert.assertTrue("Should be at least 20 classes", classes.size() >= 20);
		Assert.assertTrue(classes.contains(NestedClassToBeFound.class));
		Assert.assertTrue(classes.contains(MemberClassToBeFound.class));
	}

	class MemberClassToBeFound {
	}

	static class NestedClassToBeFound {
	}

}

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

package org.junit.gen5.commons.util;

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

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

public class FindClassesInPackageTest {

	@Test
	public void findAllClassesInThisPackage() throws IOException, ClassNotFoundException {
		List<Class<?>> classes = Arrays.asList(ReflectionUtils.findAllClassesInPackage("org.junit.gen5.commons"));
		Assert.assertTrue("Should be at least 20 classes", classes.size() >= 20);
		Assert.assertTrue(classes.contains(NestedClassToBeFound.class));
		Assert.assertTrue(classes.contains(MemberClassToBeFound.class));
	}

	class MemberClassToBeFound {
	}

	static class NestedClassToBeFound {
	}

}

Remove printing to System.out in test


package junit.runner;

/**
 * This class defines the current version of JUnit
 */
public class Version {
	private Version() {
		// don't instantiate
	}

	public static String id() {
		return "3.7";
	}
}

package junit.runner;

/**
 * This class defines the current version of JUnit
 */
public class Version {
	private Version() {
		// don't instantiate
	}

	public static String id() {
		return "@version@";
	}
}

Put back abstract version number


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

package com.google.sps.data;

public final class Trend {

  private final long id;
  private final String title;
  private final long frequency;
  private final long timestamp;

  public Trend(long id, String title, long frequency, long timestamp) {
    this.id = id;
    this.title = title;
    this.frequency = frequency;
    this.timestamp = timestamp;
  }
}

Implement parser for trends and their frequencies and store those trends in datastore


package org.yeastrc.proxl.proxl_gen_import_xml_kojak.kojak_and_percolator.constants;

import java.math.BigDecimal;

public class KojakPercolatorDefaultFilterValueConstants {

	public static final BigDecimal PERCOLATOR_PEPTIDE_Q_VALUE_DEFAULT = new BigDecimal( "0.01" );

	public static final BigDecimal PERCOLATOR_PSM_Q_VALUE_DEFAULT = new BigDecimal( "0.01" );
}

package org.yeastrc.proxl.proxl_gen_import_xml_kojak.kojak_and_percolator.constants;

import java.math.BigDecimal;

public class KojakPercolatorDefaultFilterValueConstants {

	public static final BigDecimal PERCOLATOR_PEPTIDE_Q_VALUE_DEFAULT = new BigDecimal( "0.05" );

	public static final BigDecimal PERCOLATOR_PSM_Q_VALUE_DEFAULT = new BigDecimal( "0.05" );
}

Change q-value default cutoff to 0.05 for both peptide and PSM


package de.digitalcollections.iiif.presentation.model.impl.v2;

public class PhysicalDimensionsServiceImpl extends ServiceImpl {
  private double physicalScale;
  private String physicalUnits;

  public PhysicalDimensionsServiceImpl() {}

  public PhysicalDimensionsServiceImpl(double physicalScale, String physicalUnits) {
    this.physicalScale = physicalScale;
    this.physicalUnits = physicalUnits;
  }

  @Override
  public String getContext() {
    return "http://iiiif.io/api/annex/services/physdim/1/context.json";
  }

  @Override
  public String getProfile() {
    return "http://iiiif.io/api/annex/services/physdim";
  }

  public Double getPhysicalScale() {
    return physicalScale;
  }

  public String getPhysicalUnits() {
    return physicalUnits;
  }

  public void setPhysicalScale(double physicalScale) {
    this.physicalScale = physicalScale;
  }

  public void setPhysicalUnits(String physicalUnits) {
    this.physicalUnits = physicalUnits;
  }
}

package de.digitalcollections.iiif.presentation.model.impl.v2;

public class PhysicalDimensionsServiceImpl extends ServiceImpl {
  private double physicalScale;
  private String physicalUnits;

  public PhysicalDimensionsServiceImpl() {}

  public PhysicalDimensionsServiceImpl(double physicalScale, String physicalUnits) {
    this.physicalScale = physicalScale;
    this.physicalUnits = physicalUnits;
  }

  @Override
  public String getContext() {
    return "http://iiif.io/api/annex/services/physdim/1/context.json";
  }

  @Override
  public String getProfile() {
    return "http://iiif.io/api/annex/services/physdim";
  }

  public Double getPhysicalScale() {
    return physicalScale;
  }

  public String getPhysicalUnits() {
    return physicalUnits;
  }

  public void setPhysicalScale(double physicalScale) {
    this.physicalScale = physicalScale;
  }

  public void setPhysicalUnits(String physicalUnits) {
    this.physicalUnits = physicalUnits;
  }
}

Fix typo in physical dimensions profile and @context


package beaform.events;

import static org.junit.Assert.assertEquals;

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

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

import beaform.utilities.SystemTime;
import beaform.utilities.TimeSource;

public class StoreEventTest {

	@Before
	public void setup() {
		SystemTime.setTimeSource(new TimeSource() {
			private final long timeInMillis = 0;

			@Override
			public long getSystemTime() {
				return this.timeInMillis;
			}
		});
	}

	@After
	public void destroy() {
		SystemTime.reset();
	}

	@Test
	public void testEventString() {
		// Create a 'create' event for a new formula
		String name = "TestFormula";
		Event createEvent = new FormulaCreatedEvent(name);

		Date timestamp = SystemTime.getAsDate();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String expectedResult = "[" + df.format(timestamp) + "] FormulaCreated " + name;
		// Check if the event converts to a string correctly
		// [timestamp] action properties
		String assertMessageOnFail = "Event format doesn't match with the expected one";
		assertEquals(assertMessageOnFail, expectedResult, createEvent.toEventString());
	}

}

package beaform.events;

import static org.junit.Assert.assertEquals;

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

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

import beaform.utilities.SystemTime;

public class StoreEventTest {

	@Before
	public void setup() {
		SystemTime.setTimeSource(() -> 0);
	}

	@After
	public void destroy() {
		SystemTime.reset();
	}

	@Test
	public void testEventString() {
		// Create a 'create' event for a new formula
		String name = "TestFormula";
		Event createEvent = new FormulaCreatedEvent(name);

		Date timestamp = SystemTime.getAsDate();
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		String expectedResult = "[" + df.format(timestamp) + "] FormulaCreated " + name;
		// Check if the event converts to a string correctly
		// [timestamp] action properties
		String assertMessageOnFail = "Event format doesn't match with the expected one";
		assertEquals(assertMessageOnFail, expectedResult, createEvent.toEventString());
	}

}

Use a lambda as it is a lot shorter


package collections;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;

import binarytrees.TreeNode;

public class PreorderIterator<T> implements Iterator<T> {
	private T nextItem;
	private final Stack<TreeNode<T>> stack;

	public PreorderIterator(TreeNode<T> rootNode) {
		this.nextItem = null;
		this.stack = new Stack<TreeNode<T>>();
		stack.push(rootNode);
	}

	@Override
	public boolean hasNext() {
		if (nextItem != null) {
			return true;
		}

		if (stack.empty()) {
			return false;
		}

		TreeNode<T> node = stack.peek();
		nextItem = node.getValue();
		if (node.hasLeft()) {
			stack.push(node.getLeft());
		} else {
			while (!stack.empty()) {
				TreeNode<T> current = stack.pop();
				if (current.hasRight()) {
					stack.push(current.getRight());
					break;
				}
			}
		}

		return true;
	}

	@Override
	public T next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}

		T toReturn = nextItem;
		nextItem = null;
		return toReturn;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
}

package collections;

import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Stack;

import binarytrees.TreeNode;

/**
 * An iterator that iterates through a binary tree in pre-order.
 */
public class PreorderIterator<T> implements Iterator<T> {
	private T nextItem;
	private final Stack<TreeNode<T>> stack;

	public PreorderIterator(TreeNode<T> rootNode) {
		this.nextItem = null;
		this.stack = new Stack<TreeNode<T>>();
		stack.push(rootNode);
	}

	@Override
	public boolean hasNext() {
		if (nextItem != null) {
			return true;
		}

		if (stack.empty()) {
			return false;
		}

		TreeNode<T> node = stack.peek();
		nextItem = node.getValue();
		if (node.hasLeft()) {
			stack.push(node.getLeft());
		} else {
			while (!stack.empty()) {
				TreeNode<T> current = stack.pop();
				if (current.hasRight()) {
					stack.push(current.getRight());
					break;
				}
			}
		}

		return true;
	}

	@Override
	public T next() {
		if (!hasNext()) {
			throw new NoSuchElementException();
		}

		T toReturn = nextItem;
		nextItem = null;
		return toReturn;
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}
}

Add comment for pre-order iteration.


package org.commacq;

import java.io.PrintWriter;
import java.io.Writer;

/**
 * Contains a large buffer. Reuse these objects.
 */
public class CsvLineCallbackWriter extends CsvLineCallbackAbstractSimple {

	private final PrintWriter printWriter;

	public CsvLineCallbackWriter(Writer writer) {
		printWriter = new PrintWriter(writer);
	}

	@Override
	public void processUpdate(String columnNamesCsv, CsvLine csvLine) throws CsvUpdateBlockException {
		printWriter.println(csvLine.getCsvLine());
	}

	@Override
	public void processRemove(String id) throws CsvUpdateBlockException {
		printWriter.println(id);
	}
}

package org.commacq;

import java.io.PrintWriter;
import java.io.Writer;

/**
 * Contains a large buffer. Reuse these objects.
 */
public class CsvLineCallbackWriter implements CsvLineCallback {

	private final PrintWriter printWriter;

	public CsvLineCallbackWriter(Writer writer) {
		printWriter = new PrintWriter(writer);
	}

	@Override
	public void processUpdate(String columnNamesCsv, CsvLine csvLine) throws CsvUpdateBlockException {
		printWriter.println(csvLine.getCsvLine());
	}

	@Override
	public void processRemove(String id) throws CsvUpdateBlockException {
		printWriter.println(id);
	}

	/**
	 * Add csv header
	 */
	@Override
	public void startUpdateBlock(String columnNamesCsv) throws CsvUpdateBlockException {
		printWriter.println(columnNamesCsv);
	}

	@Override
	public final void finishUpdateBlock() throws CsvUpdateBlockException {
		//No behaviour defined.
	}

	@Override
	public final void startBulkUpdate(String columnNamesCsv) throws CsvUpdateBlockException {
		//No behaviour defined.
	}

	@Override
	public final void startBulkUpdateForGroup(String group, String idWithinGroup) throws CsvUpdateBlockException {
		//No behaviour defined.
	}

	@Override
	public void cancel() {
		//No behaviour defined.
	}
}

Correct Http Csv output so that it contains the csv column headings.


package org.keycloak.connections.jpa.updater;

import org.keycloak.models.KeycloakSession;
import org.keycloak.provider.Provider;

import java.sql.Connection;

/**
 * @author Stian Thorgersen
 */
public interface JpaUpdaterProvider extends Provider {

    public String FIRST_VERSION = "1.0.0.Final";

    public String LAST_VERSION = "1.5.0";

    public String getCurrentVersionSql(String defaultSchema);

    public void update(KeycloakSession session, Connection connection, String defaultSchema);

    public void validate(Connection connection, String defaultSchema);

}

package org.keycloak.connections.jpa.updater;

import org.keycloak.models.KeycloakSession;
import org.keycloak.provider.Provider;

import java.sql.Connection;

/**
 * @author Stian Thorgersen
 */
public interface JpaUpdaterProvider extends Provider {

    public String FIRST_VERSION = "1.0.0.Final";

    public String LAST_VERSION = "1.6.0";

    public String getCurrentVersionSql(String defaultSchema);

    public void update(KeycloakSession session, Connection connection, String defaultSchema);

    public void validate(Connection connection, String defaultSchema);

}

Fix db migration not running as latest jpa version wasn't updated


/*
 UVCServiceInformationProfile.java
 Copyright (c) 2015 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */
package org.deviceconnect.android.deviceplugin.uvc.profile;

import org.deviceconnect.android.profile.DConnectProfileProvider;
import org.deviceconnect.android.profile.ServiceInformationProfile;

/**
 * UVC ServiceInformation Profile.
 *
 * @author NTT DOCOMO, INC.
 */
public class UVCServiceInformationProfile extends ServiceInformationProfile{

    public UVCServiceInformationProfile(final DConnectProfileProvider provider) {
        super(provider);
    }
}

/*
 UVCServiceInformationProfile.java
 Copyright (c) 2015 NTT DOCOMO,INC.
 Released under the MIT license
 http://opensource.org/licenses/mit-license.php
 */
package org.deviceconnect.android.deviceplugin.uvc.profile;

import android.content.Intent;
import android.os.Bundle;

import org.deviceconnect.android.deviceplugin.uvc.UVCDeviceManager;
import org.deviceconnect.android.deviceplugin.uvc.UVCDeviceService;
import org.deviceconnect.android.profile.DConnectProfileProvider;
import org.deviceconnect.android.profile.ServiceInformationProfile;

/**
 * UVC ServiceInformation Profile.
 *
 * @author NTT DOCOMO, INC.
 */
public class UVCServiceInformationProfile extends ServiceInformationProfile{

    private static final String PARAM_USB = "usb";

    private final UVCDeviceManager mDeviceMgr;

    public UVCServiceInformationProfile(final DConnectProfileProvider provider) {
        super(provider);
        mDeviceMgr = ((UVCDeviceService) provider).getDeviceManager();
    }

    @Override
    protected boolean onGetInformation(final Intent request, final Intent response,
                                       final String serviceId) {
        super.onGetInformation(request, response, serviceId);
        Bundle connect = response.getBundleExtra(PARAM_CONNECT);
        connect.putBoolean(PARAM_USB, mDeviceMgr.getDevice(serviceId) != null);
        return true;
    }
}

Implement Service Information API of UVC Device Plug-in.


package org.synyx.urlaubsverwaltung.user;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Locale;

class UserSettingsAwareSessionLocaleResolver extends SessionLocaleResolver {

    private final UserSettingsService userSettingsService;

    UserSettingsAwareSessionLocaleResolver(UserSettingsService userSettingsService) {
        this.userSettingsService = userSettingsService;
    }

    @Override
    protected Locale determineDefaultLocale(HttpServletRequest request) {

        final Principal userPrincipal = request.getUserPrincipal();
        if (userPrincipal == null) {
            return request.getLocale();
        }

        final Locale locale = userSettingsService.findLocaleForUsername(userPrincipal.getName())
            .orElseGet(request::getLocale);

        setLocaleContext(request, null, () -> locale);

        return locale;
    }
}

package org.synyx.urlaubsverwaltung.user;

import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.annotation.Nonnull;
import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Locale;

class UserSettingsAwareSessionLocaleResolver extends SessionLocaleResolver {

    private final UserSettingsService userSettingsService;

    UserSettingsAwareSessionLocaleResolver(UserSettingsService userSettingsService) {
        this.userSettingsService = userSettingsService;
    }

    @Nonnull
    @Override
    protected Locale determineDefaultLocale(HttpServletRequest request) {

        final Principal userPrincipal = request.getUserPrincipal();
        if (userPrincipal == null) {
            return request.getLocale();
        }

        final Locale locale = userSettingsService.findLocaleForUsername(userPrincipal.getName())
            .orElseGet(request::getLocale);

        setLocaleContext(request, null, () -> locale);

        return locale;
    }
}

Add @Nonnull annotation to determineDefaultLocale


package com.ivanph.webintent;

import android.content.Intent;
import android.net.Uri;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.common.MapBuilder;

/**
 * {@link NativeModule} that allows JS to open the default browser
    for an url.
 */
public class RNWebIntentModule extends ReactContextBaseJavaModule {

  ReactApplicationContext reactContext;

  public RNWebIntentModule(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
  }

  @Override
  public String getName() {
    return "WebIntent";
  }

  @ReactMethod
  public void open(String url) {
    if (Uri.parse(url).getScheme() == null) {
      //if URL is missing scheme default to http
      Uri.Builder builder = new Uri.Builder();
      url = builder.scheme("http").authority(url).build().toString();
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    this.reactContext.startActivity(intent);
  }
}

package com.ivanph.webintent;

import android.content.Intent;
import android.net.Uri;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.common.MapBuilder;

/**
 * {@link NativeModule} that allows JS to open the default browser
    for an url.
 */
public class RNWebIntentModule extends ReactContextBaseJavaModule {

  ReactApplicationContext reactContext;

  public RNWebIntentModule(ReactApplicationContext reactContext) {
    super(reactContext);
    this.reactContext = reactContext;
  }

  @Override
  public String getName() {
    return "WebIntent";
  }

  @ReactMethod
  public void open(String url) {
    if (Uri.parse(url).getScheme() == null) {
      //if URL is missing scheme default to http
      Uri.Builder builder = new Uri.Builder();
      url = builder.scheme("http").authority(url).build().toString();
    }
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setData(Uri.parse(url));
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    //Check that an app exists to receive the intent
    if (intent.resolveActivity(this.reactContext.getPackageManager()) != null) {
      this.reactContext.startActivity(intent);
    }
  }
}

Check that an app able to handle the Intent exists


package eu.rekawek.coffeegb.timer;

import eu.rekawek.coffeegb.Gameboy;
import eu.rekawek.coffeegb.cpu.SpeedMode;

public class Counter {

    private final int frequency;

    private final SpeedMode speedMode;

    private int clocks;

    private int counter;

    public Counter(int frequency, SpeedMode speedMode) {
        this.frequency = frequency;
        this.speedMode = speedMode;
    }

    public boolean tick() {
        int divider = Gameboy.TICKS_PER_SEC / frequency;
        if (speedMode != null) {
            divider /= speedMode.getSpeedMode();
        }
        if (++clocks >= divider) {
            clocks = 0;
            counter = (counter + 1) & 0xff;
            return true;
        } else {
            return false;
        }
    }

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
    }
}

package eu.rekawek.coffeegb.timer;

import eu.rekawek.coffeegb.Gameboy;
import eu.rekawek.coffeegb.cpu.SpeedMode;

public class Counter {

    private final int frequency;

    private final SpeedMode speedMode;

    private int clocks;

    private int counter;

    public Counter(int frequency, SpeedMode speedMode) {
        this.frequency = frequency;
        this.speedMode = speedMode;
    }

    public boolean tick() {
        int divider = Gameboy.TICKS_PER_SEC / frequency;
        if (speedMode != null) {
            divider /= speedMode.getSpeedMode();
        }
        if (++clocks >= divider) {
            clocks = 0;
            counter = (counter + 1) & 0xff;
            return true;
        } else {
            return false;
        }
    }

    public int getCounter() {
        return counter;
    }

    public void setCounter(int counter) {
        this.counter = counter;
        this.clocks = 0;
    }
}

Reset internal DIV clock on resetting the counter.


package org.gameon.map.filter;

import java.io.IOException;

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

@WebFilter(
        filterName = "corsFilter",
        urlPatterns = {"/*"}
          )
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        String id = request.getParameter("id");

        // TODO: a bunch of verification...
        if ( id == null )
            id = "game-on.org-provisional";

        request.setAttribute("player.id", id);

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}

package org.gameon.map.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

@WebFilter(
        filterName = "corsFilter",
        urlPatterns = {"/*"}
          )
public class AuthFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        String id = request.getParameter("id");

        // TODO: a bunch of verification...
        if ( id == null )
            id = ((HttpServletRequest)request).getHeader("gameon-id");
            if ( id == null ) {
                id = "game-on.org-provisional";
            }
        request.setAttribute("player.id", id);
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }

}

Support gameon-id header while we transition to new auth..


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.isi.karma.imp;

import java.io.IOException;

import org.json.JSONException;

import edu.isi.karma.rep.RepFactory;
import edu.isi.karma.rep.Worksheet;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.webserver.KarmaException;

/**
 *
 * This abstract class in an interface to all classes with import functionality
 *
 * @author mielvandersande
 */
public abstract class Import {

    private final RepFactory factory;
    private Worksheet worksheet;
    protected Workspace workspace;

    public Import(String worksheetName, Workspace workspace, String encoding) {
        this.factory = workspace.getFactory();
        this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding);
        this.workspace = workspace;
    }

    public Import(RepFactory factory, Worksheet worksheet) {
        this.factory = factory;
        this.worksheet = worksheet;
    }

    public RepFactory getFactory() {
        return factory;
    }

    public Worksheet getWorksheet() {
        return worksheet;
    }

    public void createWorksheet(String worksheetName, Workspace workspace, String encoding) {
    	this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding);
    }

    /*
     * Generate worksheet from data
     */
    public abstract Worksheet generateWorksheet() throws JSONException, IOException, KarmaException, ClassNotFoundException;

}

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.isi.karma.imp;

import java.io.IOException;

import org.json.JSONException;

import edu.isi.karma.rep.RepFactory;
import edu.isi.karma.rep.Worksheet;
import edu.isi.karma.rep.Workspace;
import edu.isi.karma.webserver.KarmaException;

/**
 *
 * This abstract class in an interface to all classes with import functionality
 *
 * @author mielvandersande
 */
public abstract class Import {

    private final RepFactory factory;
    private Worksheet worksheet;
    protected Workspace workspace;

    public static int MAX_WORKSHEET_NAME_LEN = 100;

    public Import(String worksheetName, Workspace workspace, String encoding) {
        this.factory = workspace.getFactory();
        if(worksheetName.length() > MAX_WORKSHEET_NAME_LEN)
        	worksheetName = worksheetName.substring(0, MAX_WORKSHEET_NAME_LEN) + "...";
        this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding);
        this.workspace = workspace;
    }

    public Import(RepFactory factory, Worksheet worksheet) {
        this.factory = factory;
        this.worksheet = worksheet;
    }

    public RepFactory getFactory() {
        return factory;
    }

    public Worksheet getWorksheet() {
        return worksheet;
    }

    public void createWorksheet(String worksheetName, Workspace workspace, String encoding) {
    	this.worksheet = factory.createWorksheet(worksheetName, workspace, encoding);
    }

    /*
     * Generate worksheet from data
     */
    public abstract Worksheet generateWorksheet() throws JSONException, IOException, KarmaException, ClassNotFoundException;

}

Set a max length for worksheet name


package gui.sub_controllers;

import gui.GraphDrawer;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ScrollBar;

/**
 * Created by TUDelft SID on 29-5-2017.
 */
public class PanningController {

    private ScrollBar scrollbar;
    private GraphDrawer drawer;

    public PanningController(ScrollBar scrollBar, GraphDrawer drawer) {
        this.scrollbar = scrollBar;
        this.drawer = drawer;
        initialize();
    }

    public void initialize() {
        scrollbar.setMax(drawer.getRadius());
        scrollbar.setVisibleAmount(drawer.getRadius());
        scrollbar.valueProperty().addListener(new ChangeListener<Number>() {
            public void changed(ObservableValue<? extends Number> ov,
                                Number old_val, Number new_val) {
                System.out.println("delta: " + (new_val.doubleValue() - old_val.doubleValue()));
            }
        });
    }

    public void setScrollbarSize(double factor) {
        setScrollbarSize(factor, (int) (scrollbar.getMax() / 2));
    }

    public void setScrollbarSize(double factor, int column) {
        double max = scrollbar.getMax();
        double amount = scrollbar.getVisibleAmount();
        if ((factor < 1 && amount < 1) || (factor > 1 && amount >= max)) {
            return;
        }
        amount = scrollbar.getVisibleAmount() * factor;
        scrollbar.setValue(column);
        scrollbar.setVisibleAmount(amount);
        System.out.println(amount);
    }

}

package gui.sub_controllers;

import gui.GraphDrawer;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.control.ScrollBar;

/**
 * Created by TUDelft SID on 29-5-2017.
 */
public class PanningController {

    private ScrollBar scrollbar;
    private GraphDrawer drawer;

    public PanningController(ScrollBar scrollBar, GraphDrawer drawer) {
        this.scrollbar = scrollBar;
        this.drawer = drawer;
        initialize();
    }

    public void initialize() {
        scrollbar.setMax(drawer.getZoomLevel());
        scrollbar.setVisibleAmount(drawer.getZoomLevel());
        scrollbar.valueProperty().addListener(new ChangeListener<Number>() {
            public void changed(ObservableValue<? extends Number> ov,
                                Number old_val, Number new_val) {
                System.out.println("delta: " + (new_val.doubleValue() - old_val.doubleValue()));
            }
        });
    }

    public void setScrollbarSize(double factor) {
        setScrollbarSize(factor, (int) (scrollbar.getMax() / 2));
    }

    public void setScrollbarSize(double factor, int column) {
        double max = scrollbar.getMax();
        double amount = scrollbar.getVisibleAmount();
        if ((factor < 1 && amount < 1) || (factor > 1 && amount >= max)) {
            return;
        }
        amount = scrollbar.getVisibleAmount() * factor;
        scrollbar.setValue(column);
        scrollbar.setVisibleAmount(amount);
        System.out.println(amount);
    }

}

Fix bug with scrollbar in TB10


package org.monospark.actioncontrol.kind;

import org.monospark.actioncontrol.kind.matcher.KindMatcher;

public abstract class Kind implements KindMatcher {

	private String name;

	private int variant;

	private KindType<?,?> type;

	protected Kind(String name, int variant, KindType<?,?> type) {
		this.name = name;
		this.variant = variant;
		this.type = type;
	}

	public final String getBaseName() {
		return name;
	}

	public final String getName() {
		return name + ":" + (variant != 0 ? variant : "");
	}

	public final int getVariant() {
		return variant;
	}

	public final KindType<?,?> getType() {
		return type;
	}
}

package org.monospark.actioncontrol.kind;

import org.monospark.actioncontrol.kind.matcher.KindMatcher;

public abstract class Kind implements KindMatcher {

	private String name;

	private int variant;

	private KindType<?,?> type;

	protected Kind(String name, int variant, KindType<?,?> type) {
		this.name = name;
		this.variant = variant;
		this.type = type;
	}

	public final String getBaseName() {
		return name;
	}

	public final String getName() {
		return name + (variant != 0 ? ":" + variant : "");
	}

	public final int getVariant() {
		return variant;
	}

	public final KindType<?,?> getType() {
		return type;
	}
}

Fix string representation of kinds


package de.flux.playground.deckcompare;

import java.io.File;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@SpringBootApplication
public class Deckcompare {

    public static String ROOT = "upload-dir";

    @RequestMapping("/")
    @ResponseBody
    String home() {
        return "Hello World!";
    }

    @Bean
    CommandLineRunner init() {
        return (String[] args) -> {
            new File(ROOT).mkdir();
        };
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Deckcompare.class, args);
    }

}

package de.flux.playground.deckcompare;

import java.io.File;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@SpringBootApplication
public class Deckcompare {

    public static String ROOT = "upload-dir";

    @RequestMapping("/")
    @ResponseBody
    public String home() {
        return "Hello World!";
    }

    @Bean
    public CommandLineRunner init() {
        return (String[] args) -> {
            new File(ROOT).mkdir();
        };
    }

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Deckcompare.class, args);
    }

}

Make package private methods public


package com.netflix.zuul.util;

import com.netflix.client.http.HttpResponse;
import com.netflix.zuul.message.http.HttpRequestMessage;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * User: michaels@netflix.com
 * Date: 6/8/15
 * Time: 11:50 AM
 */
public class ProxyUtils
{
    public static boolean isValidRequestHeader(String headerName)
    {
        switch (headerName.toLowerCase()) {
            case "connection":
            case "content-length":
            case "transfer-encoding":
                return false;
            default:
                return true;
        }
    }

    public static boolean isValidResponseHeader(String headerName)
    {
        switch (headerName.toLowerCase()) {
            case "connection":
            case "keep-alive":
            case "content-length":
            case "server":
            case "transfer-encoding":
                return false;
            default:
                return true;
        }
    }

    @RunWith(MockitoJUnitRunner.class)
    public static class TestUnit
    {
        @Mock
        HttpResponse proxyResp;

        @Mock
        HttpRequestMessage request;

        @Test
        public void testIsValidResponseHeader()
        {
            Assert.assertTrue(isValidResponseHeader("test"));
            Assert.assertFalse(isValidResponseHeader("content-length"));
            Assert.assertFalse(isValidResponseHeader("connection"));
        }
    }
}

package com.netflix.zuul.util;

import com.netflix.client.http.HttpResponse;
import com.netflix.zuul.message.http.HttpRequestMessage;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;

/**
 * User: michaels@netflix.com
 * Date: 6/8/15
 * Time: 11:50 AM
 */
public class ProxyUtils
{
    public static boolean isValidRequestHeader(String headerName)
    {
        switch (headerName.toLowerCase()) {
            case "connection":
            case "content-length":
            case "transfer-encoding":
                return false;
            default:
                return true;
        }
    }

    public static boolean isValidResponseHeader(String headerName)
    {
        switch (headerName.toLowerCase()) {
            case "connection":
            case "keep-alive":
            case "content-length":
            case "transfer-encoding":
                return false;
            default:
                return true;
        }
    }

    @RunWith(MockitoJUnitRunner.class)
    public static class TestUnit
    {
        @Mock
        HttpResponse proxyResp;

        @Mock
        HttpRequestMessage request;

        @Test
        public void testIsValidResponseHeader()
        {
            Assert.assertTrue(isValidResponseHeader("test"));
            Assert.assertFalse(isValidResponseHeader("content-length"));
            Assert.assertFalse(isValidResponseHeader("connection"));
        }
    }
}

Stop stripping out the Server header from response from origins. Should overwrite this in a zuul filter if we don't want to use the Server header from origin, rather than removing it by default.


package org.googlecode.lucene.spatial.strategy.prefix;

import com.googlecode.lucene.spatial.base.context.JtsSpatialContext;
import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid;
import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo;
import org.apache.lucene.spatial.strategy.prefix.RecursiveGridStrategy;
import org.apache.lucene.spatial.test.SpatialMatchConcern;
import org.apache.lucene.spatial.test.StrategyTestCase;
import org.junit.Test;

import java.io.IOException;

public class RecursiveGridStrategyWithExtrasTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> {

  @Override
  public void setUp() throws Exception {
    super.setUp();
    int maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible();
    this.ctx = new JtsSpatialContext();
    GeohashSpatialPrefixGrid grid = new GeohashSpatialPrefixGrid(
        ctx, maxLength );
    this.strategy = new RecursiveGridStrategy( grid );
    this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" );
  }

  /**
   * For now, the only difference from the Simple version is that this uses JtsSpatialContext
   */
  @Test
  public void testGeohashStrategy() throws IOException {
    getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS);
    executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox);
  }
}

package org.googlecode.lucene.spatial.strategy.prefix;

import com.googlecode.lucene.spatial.base.context.JtsSpatialContext;
import org.apache.lucene.spatial.base.prefix.GeohashSpatialPrefixGrid;
import org.apache.lucene.spatial.strategy.SimpleSpatialFieldInfo;
import org.apache.lucene.spatial.strategy.prefix.RecursiveGridStrategy;
import org.apache.lucene.spatial.test.SpatialMatchConcern;
import org.apache.lucene.spatial.test.StrategyTestCase;
import org.junit.Test;

import java.io.IOException;

public class RecursiveGridStrategyWithExtrasTestCase extends StrategyTestCase<SimpleSpatialFieldInfo> {

  @Override
  public void setUp() throws Exception {
    super.setUp();
    int maxLength = GeohashSpatialPrefixGrid.getMaxLevelsPossible();
    this.ctx = new JtsSpatialContext();
    GeohashSpatialPrefixGrid grid = new GeohashSpatialPrefixGrid(
        ctx, maxLength );
    this.strategy = new RecursiveGridStrategy( grid );
    this.fieldInfo = new SimpleSpatialFieldInfo( "geohash" );
  }

  /**
   * For now, the only difference from the Simple version is that this uses JtsSpatialContext
   */
  @Test
  public void testWorldCitiesWithinBox() throws IOException {
    getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS);
    executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_IsWithin_BBox);
  }

  @Test
  public void testPolygonIndex() throws IOException {
    getAddAndVerifyIndexedDocuments(DATA_STATES_POLY);
    executeQueries(SpatialMatchConcern.FILTER, QTEST_States_Intersects_BBox);
  }
}

Test polygon indexing using state polys & bbox queries. Fails right now.


/*
 * Copyright 2014 Kevin Quan (kevin.quan@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 com.kevinquan.google.activityrecoginition;

import com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks;
import com.google.android.gms.location.ActivityRecognitionClient;

public abstract class AbstractActivityRecognitionCallback implements ConnectionCallbacks {

    @SuppressWarnings("unused")
    private static final String TAG = AbstractActivityRecognitionCallback.class.getSimpleName();

    protected ActivityRecognitionClient mClient;

    public AbstractActivityRecognitionCallback setClient(ActivityRecognitionClient client) {
        mClient = client;
        return this;
    }

    @Override public void onDisconnected() {}
}

/*
 * Copyright 2014 Kevin Quan (kevin.quan@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 com.kevinquan.google.activityrecoginition;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;

public abstract class AbstractActivityRecognitionCallback implements ConnectionCallbacks {

    @SuppressWarnings("unused")
    private static final String TAG = AbstractActivityRecognitionCallback.class.getSimpleName();

    protected GoogleApiClient mClient;

    @Override public void onConnectionSuspended(int reason) {}

    public AbstractActivityRecognitionCallback setClient(GoogleApiClient client) {
        mClient = client;
        return this;
    }
}

Update to latest Google Play Services APIs


package org.spoofax.interpreter.library.ssl;

import io.usethesource.capsule.Set;

import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;

public class SSL_immutable_relation_values_set extends AbstractPrimitive {

    protected SSL_immutable_relation_values_set() {
        super("SSL_immutable_relation_values", 0, 0);
    }

    @Override
    public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs) {
        if(!(env.current() instanceof StrategoImmutableRelation)) {
            return false;
        }

        final StrategoImmutableRelation map = (StrategoImmutableRelation) env.current();
        final Set.Transient<IStrategoTerm> result = Set.Transient.of();
        for(IStrategoTerm value : map.backingRelation.inverse().keySet()) {
            result.__insert(value);
        }

        env.setCurrent(new StrategoImmutableSet(result.freeze()));
        return true;
    }
}

package org.spoofax.interpreter.library.ssl;

import io.usethesource.capsule.Set;

import org.spoofax.interpreter.core.IContext;
import org.spoofax.interpreter.library.AbstractPrimitive;
import org.spoofax.interpreter.stratego.Strategy;
import org.spoofax.interpreter.terms.IStrategoTerm;

public class SSL_immutable_relation_values_set extends AbstractPrimitive {

    protected SSL_immutable_relation_values_set() {
        super("SSL_immutable_relation_values_set", 0, 0);
    }

    @Override
    public boolean call(IContext env, Strategy[] sargs, IStrategoTerm[] targs) {
        if(!(env.current() instanceof StrategoImmutableRelation)) {
            return false;
        }

        final StrategoImmutableRelation map = (StrategoImmutableRelation) env.current();
        final Set.Transient<IStrategoTerm> result = Set.Transient.of();
        result.__insertAll(map.backingRelation.inverse().keySet());

        env.setCurrent(new StrategoImmutableSet(result.freeze()));
        return true;
    }
}

Fix bug where two primitives use the same name


package org.jboss.as.test.integration.ee.appclient.basic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Singleton;

/**
 * @author Stuart Douglas
 */
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class AppClientStateSingleton implements AppClientSingletonRemote {

    private volatile CountDownLatch latch = new CountDownLatch(1);

    private volatile String value;

    @Override
    public void reset() {
        value = null;
        //if we have a thread blocked on the latch release it
        latch.countDown();
        latch = new CountDownLatch(1);
    }

    @Override
    public void makeAppClientCall(final String value) {
        this.value = value;
        latch.countDown();
    }

    @Override
    public String awaitAppClientCall() {
        try {
            latch.await(10, TimeUnit.SECONDS);
            return value;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

package org.jboss.as.test.integration.ee.appclient.basic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.ejb.ConcurrencyManagement;
import javax.ejb.ConcurrencyManagementType;
import javax.ejb.Singleton;

import org.jboss.logging.Logger;

/**
 * @author Stuart Douglas
 */
@Singleton
@ConcurrencyManagement(ConcurrencyManagementType.BEAN)
public class AppClientStateSingleton implements AppClientSingletonRemote {
    private static final Logger logger = Logger.getLogger("org.jboss.as.test.appclient");

    private volatile CountDownLatch latch = new CountDownLatch(1);

    private volatile String value;

    @Override
    public void reset() {
        logger.info("Reset called!");
        value = null;
        //if we have a thread blocked on the latch release it
        latch.countDown();
        latch = new CountDownLatch(1);
    }

    @Override
    public void makeAppClientCall(final String value) {
        logger.info("AppClient Call called!");
        this.value = value;
        latch.countDown();
    }

    @Override
    public String awaitAppClientCall() {
        try {
            boolean b = latch.await(10, TimeUnit.SECONDS);
            logger.info("Await returned: " + b + " : " + value);
            return value;
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

Add some temporary debug logging to figure out test failures


package org.csstudio.opibuilder.adl2boy.translator;

import org.csstudio.opibuilder.model.AbstractWidgetModel;
import org.csstudio.utility.adlparser.fileParser.ADLWidget;
import org.eclipse.swt.graphics.RGB;

public class Composite2Model extends AbstractADL2Model {

	public Composite2Model(ADLWidget adlWidget, RGB[] colorMap) {
		super(adlWidget, colorMap);
		// TODO Auto-generated constructor stub
	}

	@Override
	public	AbstractWidgetModel getWidgetModel() {
		// TODO Auto-generated method stub
		return null;
	}

}

package org.csstudio.opibuilder.adl2boy.translator;

import org.csstudio.opibuilder.model.AbstractContainerModel;
import org.csstudio.opibuilder.model.AbstractWidgetModel;
import org.csstudio.opibuilder.widgets.model.GroupingContainerModel;
import org.csstudio.opibuilder.widgets.model.LabelModel;
import org.csstudio.opibuilder.widgets.model.LinkingContainerModel;
import org.csstudio.utility.adlparser.fileParser.ADLWidget;
import org.csstudio.utility.adlparser.fileParser.widgets.Composite;
import org.eclipse.swt.graphics.RGB;

public class Composite2Model extends AbstractADL2Model {
	AbstractContainerModel containerModel;

	public Composite2Model(ADLWidget adlWidget, RGB[] colorMap) {
		super(adlWidget, colorMap);
		Composite compositeWidget = new Composite(adlWidget);
		if (!compositeWidget.hasCompositeFile()) {
			containerModel = new LinkingContainerModel();
		}
		else {
			containerModel = new GroupingContainerModel();
			if (compositeWidget != null) {
				setADLObjectProps(compositeWidget, containerModel);
			}
			TranslatorUtils.ConvertChildren(compositeWidget.getChildren(), containerModel, colorMap);
			((GroupingContainerModel)(containerModel)).setPropertyValue(GroupingContainerModel.PROP_SHOW_SCROLLBAR, false);
			FixChildPositions();
		}
		if (compositeWidget != null) {
			setADLObjectProps(compositeWidget, containerModel);
			if (compositeWidget != null) {
				setADLObjectProps(compositeWidget, containerModel);
			}
		}

	}

	@Override
	public	AbstractWidgetModel getWidgetModel() {
		return containerModel;
	}

	private void FixChildPositions() {
		int compositeX = containerModel.getX();
		int compositeY = containerModel.getY();

		for (AbstractWidgetModel model : containerModel.getChildren()){
			model.setX(model.getX() - compositeX);
			model.setY(model.getY() - compositeY);
		}
	}
}

Add the first round of handling code.


package com.hubspot.baragon.service.config;

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

import javax.validation.constraints.NotNull;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hubspot.baragon.models.BaragonService;

@JsonIgnoreProperties(ignoreUnknown = true)
public class PurgeCacheConfiguration {
  @JsonProperty("enabledTemplates")
  @NotNull
  private List<String> enabledTemplates;

  @JsonProperty(value = "excludedServiceIds")
  @NotNull
  private List<String> excludedServiceIds;

  public List<String> getEnabledTemplates() {
    if (enabledTemplates == null) {
      return new ArrayList<>();
    }
    return enabledTemplates;
  }

  public void setEnabledTemplates(List<String> enabledTemplates) {
    this.enabledTemplates = enabledTemplates;
  }

  public List<String> getExcludedServiceIds() {
    if (excludedServiceIds == null) {
      return new ArrayList<>();
    }
    return excludedServiceIds;
  }

  public void setExcludedServiceIds(List<String> excludedServiceIds) {
    this.excludedServiceIds = excludedServiceIds;
  }

}

package com.hubspot.baragon.service.config;

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

import javax.validation.constraints.NotNull;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.hubspot.baragon.models.BaragonService;

@JsonIgnoreProperties(ignoreUnknown = true)
public class PurgeCacheConfiguration {
  @JsonProperty("enabledTemplates")
  @NotNull
  private List<String> enabledTemplates = new ArrayList<>();

  @JsonProperty(value = "excludedServiceIds")
  @NotNull
  private List<String> excludedServiceIds = new ArrayList<>();

  public List<String> getEnabledTemplates() {
    return enabledTemplates;
  }

  public void setEnabledTemplates(List<String> enabledTemplates) {
    this.enabledTemplates = enabledTemplates;
  }

  public List<String> getExcludedServiceIds() {
    return excludedServiceIds;
  }

  public void setExcludedServiceIds(List<String> excludedServiceIds) {
    this.excludedServiceIds = excludedServiceIds;
  }

}

Update null handling for enabledTemplates and excludedServiceIds


package com.kaviju.accesscontrol.model;

import org.apache.log4j.Logger;

@SuppressWarnings("serial")
public class KAAccessListItem extends com.kaviju.accesscontrol.model.base._KAAccessListItem {
	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(KAAccessListItem.class);
}

package com.kaviju.accesscontrol.model;

import org.apache.log4j.Logger;

import com.webobjects.foundation.NSArray;

@SuppressWarnings("serial")
public class KAAccessListItem extends com.kaviju.accesscontrol.model.base._KAAccessListItem {
	@SuppressWarnings("unused")
	private static Logger log = Logger.getLogger(KAAccessListItem.class);

	public NSArray<? extends KAUserProfile>fetchUserProfileWithItemForRole(String roleCode) {
		KARole role = KARole.roleWithCode(editingContext(), roleCode);

		NSArray<KAUserProfileRole> userProfileRoles = KAUserProfileRole.fetchKAUserProfileRoles(editingContext(), KAUserProfileRole.ROLE.eq(role), null);
		userProfileRoles = KAUserProfileRole.LIST_ITEMS.containsObject(this).filtered(userProfileRoles);

		return KAUserProfileRole.USER_PROFILE.arrayValueInObject(userProfileRoles);
	}
}

Add a way to get all the users with a specific role.


package me.mattlogan.pancakes;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;

import me.mattlogan.library.ViewStack;
import me.mattlogan.library.ViewStackDelegate;

public class MainActivity extends AppCompatActivity
        implements ViewStackActivity, ViewStackDelegate {

    private ViewStack viewStack;

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

        viewStack = ViewStack.create((ViewGroup) findViewById(R.id.container), this);

        if (savedInstanceState != null) {
            viewStack.rebuildFromBundle(savedInstanceState);
        } else {
            viewStack.push(new RedView.Factory());
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        viewStack.saveToBundle(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        viewStack.pop();
    }

    @Override
    public ViewStack viewStack() {
        return viewStack;
    }

    @Override
    public void onFinishStack() {
        finish();
    }
}

package me.mattlogan.pancakes;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ViewGroup;

import me.mattlogan.library.ViewStack;
import me.mattlogan.library.ViewStackDelegate;

public class MainActivity extends AppCompatActivity
        implements ViewStackActivity, ViewStackDelegate {

    private static final String STACK_TAG = "stack";

    private ViewStack viewStack;

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

        viewStack = ViewStack.create((ViewGroup) findViewById(R.id.container), this);

        if (savedInstanceState != null) {
            viewStack.rebuildFromBundle(savedInstanceState, STACK_TAG);
        } else {
            viewStack.push(new RedView.Factory());
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        viewStack.saveToBundle(outState, STACK_TAG);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onBackPressed() {
        viewStack.pop();
    }

    @Override
    public ViewStack viewStack() {
        return viewStack;
    }

    @Override
    public void onFinishStack() {
        finish();
    }
}

Update app module with bundle tag


package internal.org.springframework.content.s3.boot.autoconfigure;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;

import internal.org.springframework.content.s3.config.S3StoreConfiguration;
import internal.org.springframework.content.s3.config.S3StoreFactoryBean;
import internal.org.springframework.versions.jpa.boot.autoconfigure.JpaVersionsAutoConfiguration;

@Configuration
@AutoConfigureAfter({ JpaVersionsAutoConfiguration.class })
@ConditionalOnClass(AmazonS3Client.class)
public class S3ContentAutoConfiguration {

	@Configuration
	@ConditionalOnMissingBean(S3StoreFactoryBean.class)
	@Import({ S3StoreConfiguration.class, S3ContentAutoConfigureRegistrar.class })
	public static class EnableS3StoresConfig {}

	@Bean
	@ConditionalOnMissingBean
	public AmazonS3 s3Client() {
		AmazonS3 s3Client = new AmazonS3Client();
		return s3Client;
	}
}

package internal.org.springframework.content.s3.boot.autoconfigure;

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;

import internal.org.springframework.content.s3.config.S3StoreConfiguration;
import internal.org.springframework.content.s3.config.S3StoreFactoryBean;
import internal.org.springframework.versions.jpa.boot.autoconfigure.JpaVersionsAutoConfiguration;

@Configuration
@AutoConfigureAfter({ JpaVersionsAutoConfiguration.class })
@ConditionalOnClass(AmazonS3Client.class)
public class S3ContentAutoConfiguration {

	@Configuration
	@ConditionalOnMissingBean(S3StoreFactoryBean.class)
	@Import({ S3StoreConfiguration.class, S3ContentAutoConfigureRegistrar.class })
	public static class EnableS3StoresConfig {}

	@Bean
	@ConditionalOnMissingBean()
	public AmazonS3 amazonS3() {
		AmazonS3 s3Client = new AmazonS3Client();
		return s3Client;
	}
}

Rename the autoconfigured AmazonS3 bean


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

import java.nio.file.Path;

/**
 * @author Kevin Pollet
 */
public interface RepositoryProvider {
    Resource getResource(String projectId, Path resourcePath);

    void createResource(Resource resource);

    void deleteResource(Resource resource);

    RepositoryWatchingService getWatchingService();
}

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

import java.nio.file.Path;

/**
 * @author Kevin Pollet
 */
public interface RepositoryProvider {
    boolean addProject(String projectId, Path projectPath);

    boolean removeProject(String projectId);

    Resource getResource(String projectId, Path resourcePath);

    void createResource(Resource resource);

    void deleteResource(Resource resource);

    RepositoryWatchingService getWatchingService();
}

Add methods to add and remove a project from a repository


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

import net.kuujo.copycat.log.Entry;

/**
 * Cluster partitioner.
 *
 * @author Jordan Halterman
 */
public interface Partitioner {

  /**
   * Returns the index of a partition for the given entry.
   *
   * @param entry The entry to partition.
   * @param numPartitions The number of partitions.
   * @return The index of the partition for the given entry.
   */
  int partition(Entry entry, int numPartitions);

}

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

import net.kuujo.copycat.log.Entry;

/**
 * Cluster partitioner.
 *
 * @author Jordan Halterman
 */
public interface Partitioner<T> {

  /**
   * Returns the index of a partition for the given entry.
   *
   * @param entry The entry to partition.
   * @param numPartitions The number of partitions.
   * @return The index of the partition for the given entry.
   */
  int partition(T entry, int numPartitions);

}

Add types to partitioner SPI.


package net.ihiroky.niotty.buffer;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

/**
 * @author Hiroki Itoh
 */
public class EncodeBufferGroup implements Iterable<EncodeBuffer> {

    private Deque<EncodeBuffer> group = new ArrayDeque<>();

    public void addLast(EncodeBuffer encodeBuffer) {
        group.addLast(encodeBuffer);
    }

    public void addFirst(EncodeBuffer encodeBuffer) {
        group.addFirst(encodeBuffer);
    }

    public EncodeBuffer pollFirst() {
        return group.pollFirst();
    }

    public EncodeBuffer pollLast() {
        return group.pollLast();
    }

    @Override
    public Iterator<EncodeBuffer> iterator() {
        return group.iterator();
    }
}

package net.ihiroky.niotty.buffer;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;

/**
 * @author Hiroki Itoh
 */
public class EncodeBufferGroup implements Iterable<EncodeBuffer> {

    private Deque<EncodeBuffer> group = new ArrayDeque<>();

    public void addLast(EncodeBuffer encodeBuffer) {
        group.addLast(encodeBuffer);
    }

    public void addFirst(EncodeBuffer encodeBuffer) {
        group.addFirst(encodeBuffer);
    }

    public EncodeBuffer pollFirst() {
        return group.pollFirst();
    }

    public EncodeBuffer pollLast() {
        return group.pollLast();
    }

    @Override
    public Iterator<EncodeBuffer> iterator() {
        return group.iterator();
    }

    public int filledBytes() {
        int sum = 0;
        for (EncodeBuffer encodeBuffer : group) {
            sum += encodeBuffer.filledBytes();
        }
        return sum;
    }
}

Add method to count filled bytes


package org.ndgf.endit;

import org.dcache.pool.nearline.spi.NearlineStorage;
import org.dcache.pool.nearline.spi.NearlineStorageProvider;

public class EnditNearlineStorageProvider implements NearlineStorageProvider
{
    @Override
    public String getName()
    {
        return "endit";
    }

    @Override
    public String getDescription()
    {
        return "Endit TSM integration provider.";
    }

    @Override
    public NearlineStorage createNearlineStorage(String type, String name)
    {
        return new PollingEnditNearlineStorage(type, name);
    }
}

package org.ndgf.endit;

import org.dcache.pool.nearline.spi.NearlineStorage;
import org.dcache.pool.nearline.spi.NearlineStorageProvider;

public class EnditNearlineStorageProvider implements NearlineStorageProvider
{
    @Override
    public String getName()
    {
        return "endit";
    }

    @Override
    public String getDescription()
    {
        return "Endit TSM integration provider.";
    }

    @Override
    public NearlineStorage createNearlineStorage(String type, String name)
    {
        return new WatchingEnditNearlineStorage(type, name);
    }
}

Make watching provider the default


package com.llnw.storage.client;

import com.google.common.collect.Lists;
import com.llnw.storage.client.io.ActivityCallback;

import javax.annotation.Nullable;

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

public class MockEndpointFactory extends EndpointFactory {
    public MockEndpointFactory() {
        super(null, null, null);
    }

    @Override
    public Endpoint create(boolean useFTP) {
        return new Endpoint() {
            @Override
            public void deleteDirectory(String path) throws IOException {
            }

            @Override
            public void deleteFile(String path) throws IOException {
            }

            @Override
            public void close() {
            }

            @Override
            public void makeDirectory(String path) throws IOException {
            }

            @Override
            public List<String> listFiles(String path) throws IOException {
                return Lists.newArrayList();
            }

            @Override
            public void upload(File file, String path, String name, @Nullable ActivityCallback callback)
                    throws IOException {
            }

            @Override
            public void noop() throws IOException {
            }

            @Override
            public boolean exists(String path) throws IOException {
                return false;
            }
        };
    }
}

package com.llnw.storage.client;

import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.llnw.storage.client.io.ActivityCallback;

import javax.annotation.Nullable;

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

public class MockEndpointFactory extends EndpointFactory {

    private final File destination;

    public MockEndpointFactory() {
        this(null);
    }

    public MockEndpointFactory(File destination) {
        super(null, null, null);
        this.destination = destination;
    }

    @Override
    public Endpoint create(boolean useFTP) {
        return new Endpoint() {
            @Override
            public void deleteDirectory(String path) throws IOException {
            }

            @Override
            public void deleteFile(String path) throws IOException {
            }

            @Override
            public void close() {
            }

            @Override
            public void makeDirectory(String path) throws IOException {
            }

            @Override
            public List<String> listFiles(String path) throws IOException {
                return Lists.newArrayList();
            }

            @Override
            public void upload(File file, String path, String name, @Nullable ActivityCallback callback)
                    throws IOException {
                if (destination != null) {
                    Files.copy(file, destination);
                }
            }

            @Override
            public void noop() throws IOException {
            }

            @Override
            public boolean exists(String path) throws IOException {
                return false;
            }
        };
    }
}

Allow for destination file in mock endpoint