/*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015, 2016
*/
package quarks.execution;

import java.util.concurrent.Future;

import com.google.gson.JsonObject;

/**
 * An interface for submission of an executable.
 * <p>
 * The class implementing this interface is responsible
 * for the semantics of this operation.  e.g., an direct topology
 * provider would run the topology as threads in the current jvm.
 *
 * @param <E> the executable type
 * @param <J> the submitted executable's future
 */
public interface Submitter<E, J extends Job> {

    /**
     * Submit an executable.
     * No configuration options are specified,
     * this is equivalent to {@code submit(executable, new JsonObject())}.
     *
     * @param executable executable to submit
     * @return a future for the submitted executable
     */
    Future<J> submit(E executable);

    /**
     * Submit an executable.
     *
     * @param executable executable to submit
     * @param config context information for the submission.
     * @return a future for the submitted executable
     */
    Future<J> submit(E executable, JsonObject config);
}

/*
# Licensed Materials - Property of IBM
# Copyright IBM Corp. 2015, 2016
*/
package quarks.execution;

import java.util.concurrent.Future;

import com.google.gson.JsonObject;

/**
 * An interface for submission of an executable.
 * <p>
 * The class implementing this interface is responsible
 * for the semantics of this operation.  e.g., an direct topology
 * provider would run the topology as threads in the current jvm.
 *
 * @param <E> the executable type
 * @param <J> the submitted executable's future
 */
public interface Submitter<E, J extends Job> {

    /**
     * Submit an executable.
     * No configuration options are specified,
     * this is equivalent to {@code submit(executable, new JsonObject())}.
     *
     * @param executable executable to submit
     * @return a future for the submitted executable
     */
    Future<J> submit(E executable);

    /**
     * Submit an executable.
     *
     * @param executable executable to submit
     * @param config reserved for future use: context information for the submission.
     * @return a future for the submitted executable
     */
    Future<J> submit(E executable, JsonObject config);
}

Clarify that Submit config is not currently used


package org.broadinstitute.sting.gatk.walkers.fasta;

import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedDatum;
import org.broadinstitute.sting.gatk.walkers.RodWalker;
import org.broadinstitute.sting.utils.genotype.Variation;

import java.util.Iterator;

public class CreateSequenomMask extends RodWalker<Integer, Integer> {

    public void initialize() {}

	public Integer map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context) {
        int result = 0;

        Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator();
        while (rods.hasNext()) {
            ReferenceOrderedDatum rod = rods.next();
            if ( rod instanceof Variation && ((Variation)rod).isSNP() ) {
                out.println(context.getLocation());
                result = 1;
                break;
            }
        }

        return result;
    }

    public Integer reduceInit() {
        return 0;
    }

	public Integer reduce(Integer value, Integer sum) {
		return value + sum;
	}

    public void onTraversalDone(Integer sum) {
        logger.info("Found " + sum + " masking sites.");
    }
}

package org.broadinstitute.sting.gatk.walkers.fasta;

import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.refdata.ReferenceOrderedDatum;
import org.broadinstitute.sting.gatk.walkers.RodWalker;
import org.broadinstitute.sting.utils.genotype.Variation;

import java.util.Iterator;

public class CreateSequenomMask extends RodWalker<Integer, Integer> {

    public void initialize() {}

	public Integer map(RefMetaDataTracker rodData, ReferenceContext ref, AlignmentContext context) {
        int result = 0;
        if ( rodData == null ) // apparently, RodWalkers make funky map calls
            return 0;

        Iterator<ReferenceOrderedDatum> rods = rodData.getAllRods().iterator();
        while (rods.hasNext()) {
            ReferenceOrderedDatum rod = rods.next();
            if ( rod instanceof Variation && ((Variation)rod).isSNP() ) {
                out.println(context.getLocation());
                result = 1;
                break;
            }
        }

        return result;
    }

    public Integer reduceInit() {
        return 0;
    }

	public Integer reduce(Integer value, Integer sum) {
		return value + sum;
	}

    public void onTraversalDone(Integer sum) {
        logger.info("Found " + sum + " masking sites.");
    }
}

Check that map isn't being called passing in null arguments.
(This seems wrong; see JIRA entry GSA-211)

git-svn-id: 4561c0a8f080806b19201efb9525134c00b76d40@1907 348d0f76-0448-11de-a6fe-93d51630548a


package main.doge.service;

import main.doge.service.domain.Todo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

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

@Service
public class TodoService {

    private final RestTemplate restTemplate;
    private final String uri;

    @Autowired
    public TodoService(RestTemplate restTemplate, @Value("${doge.service.uri}") String uri) {
        this.restTemplate = restTemplate;
        this.uri = uri;
    }

    public List<Todo> getTodos() {
        return Arrays.asList(callService(uri + "/todos", Todo[].class));
    }

    public Todo getSingleTodo(int todoId) {
        return callService(uri + "/todo/" + Integer.toString(todoId), Todo.class);
    }

    private <T> T callService(String uri, Class<T> type) {
        return restTemplate.getForObject(uri, type);
    }
}

package main.doge.service;

import main.doge.service.domain.Todo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TodoService {

    private final RestTemplate restTemplate;
    private final String uri;

    @Autowired
    public TodoService(RestTemplate restTemplate, @Value("${doge.service.uri}") String uri) {
        this.restTemplate = restTemplate;
        this.uri = uri;
    }

    public List<Todo> getTodos() {
        return Arrays.stream(callService(uri + "/todos", Todo[].class)).collect(Collectors.toList());
    }

    public Todo getSingleTodo(int todoId) {
        return callService(uri + "/todo/" + Integer.toString(todoId), Todo.class);
    }

    private <T> T callService(String uri, Class<T> type) {
        return restTemplate.getForObject(uri, type);
    }
}

Refactor to use Java 8 stream

Refactor to use Java 8 stream


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

package com.googlesource.gerrit.plugins.webhooks;

import java.util.concurrent.ScheduledThreadPoolExecutor;

import com.google.gerrit.extensions.annotations.PluginName;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.server.git.WorkQueue;
import com.google.inject.Inject;
import com.google.inject.Provider;

class ExecutorProvider
    implements Provider<ScheduledThreadPoolExecutor>, LifecycleListener {
  private WorkQueue.Executor executor;

  @Inject
  ExecutorProvider(WorkQueue workQueue,
      Configuration cfg,
      @PluginName String name) {
    executor = workQueue.createQueue(cfg.getThreadPoolSize(), name);
  }

  @Override
  public void start() {
    // do nothing
  }

  @Override
  public void stop() {
    executor.shutdown();
    executor.unregisterWorkQueue();
    executor = null;
  }

  @Override
  public ScheduledThreadPoolExecutor get() {
    return executor;
  }
}

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

package com.googlesource.gerrit.plugins.webhooks;

import java.util.concurrent.ScheduledThreadPoolExecutor;

import com.google.gerrit.extensions.annotations.PluginName;
import com.google.gerrit.extensions.events.LifecycleListener;
import com.google.gerrit.server.git.WorkQueue;
import com.google.inject.Inject;
import com.google.inject.Provider;

class ExecutorProvider
    implements Provider<ScheduledThreadPoolExecutor>, LifecycleListener {
  private WorkQueue.Executor executor;

  @Inject
  ExecutorProvider(WorkQueue workQueue,
      Configuration cfg,
      @PluginName String name) {
    executor = workQueue.createQueue(cfg.getThreadPoolSize(), name);
  }

  @Override
  public void start() {
    // do nothing
  }

  @Override
  public void stop() {
    executor.shutdown();
    executor = null;
  }

  @Override
  public ScheduledThreadPoolExecutor get() {
    return executor;
  }
}

Stop calling unregisterWorkqueue which was removed in gerrit

Change-Id: I9e60c229bab42b893c565196ce058000c647783e


package seedu.emeraldo.logic.commands;

public class EditCommand extends Command{

    public static final String COMMAND_WORD = "edit";

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ": Edits the task identified by the index number used in the last tasks listing.\n"
            + "Parameters: INDEX (must be a positive integer) and \"TASK_DESCRIPTION\"\n"
            + "Example: " + COMMAND_WORD + " 1" + "CS2103T Week 8 Tutorial";

    public static final String MESSAGE_EDIT_TASK_SUCCESS = "Edited task: %1$s";

    public final int targetIndex;

    public final String field;

    public EditCommand(int targetIndex, String field) {
        this.targetIndex = targetIndex;
        this.field = field;
    }

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

}

package seedu.emeraldo.logic.commands;

import seedu.emeraldo.commons.exceptions.IllegalValueException;

public class EditCommand extends Command{

    public static final String COMMAND_WORD = "edit";

    public static final String MESSAGE_USAGE = COMMAND_WORD
            + ": Edits the task identified by the index number used in the last tasks listing.\n"
            + "Parameters: INDEX (must be a positive integer) and \"TASK_DESCRIPTION\"\n"
            + "Example: " + COMMAND_WORD + " 1" + "CS2103T Week 8 Tutorial";

    public static final String MESSAGE_EDIT_TASK_SUCCESS = "Edited task: %1$s";

    public final int targetIndex;

    public final String field;

    public EditCommand(String targetIndex, String field) throws IllegalValueException {
        this.targetIndex = Integer.parseInt(targetIndex);
        this.field = field;
    }

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

}

Add IllegalValueException and convert String to int


package es.ucm.fdi.tp.control;

import java.util.List;

import es.ucm.fdi.tp.basecode.bgame.control.Player;
import es.ucm.fdi.tp.basecode.bgame.model.Board;
import es.ucm.fdi.tp.basecode.bgame.model.GameMove;
import es.ucm.fdi.tp.basecode.bgame.model.GameRules;
import es.ucm.fdi.tp.basecode.bgame.model.Piece;

public class SwingPlayer extends Player{

	/**
	 *
	 */
	private static final long serialVersionUID = -257722318128195740L;

	@Override
	public GameMove requestMove(Piece p, Board board, List<Piece> pieces, GameRules rules) {
		// TODO Auto-generated method stub
		return null;
	}

	private void setMove(){

	}

}

package es.ucm.fdi.tp.control;

import java.util.List;

import es.ucm.fdi.tp.basecode.bgame.control.Player;
import es.ucm.fdi.tp.basecode.bgame.model.Board;
import es.ucm.fdi.tp.basecode.bgame.model.GameMove;
import es.ucm.fdi.tp.basecode.bgame.model.GameRules;
import es.ucm.fdi.tp.basecode.bgame.model.Piece;

public class SwingPlayer extends Player {

	private static final long serialVersionUID = -257722318128195740L;

	private GameMove move;

	public SwingPlayer() {}

	@Override
	public GameMove requestMove(Piece p, Board board, List<Piece> pieces, GameRules rules) {
		if(p.equals(move.getPiece()) {
			return this.move;
		}
		return null;
	}

	public void setMove(GameMove newMove) {
		this.move = move;
	}

	public GameMove getMove() {
		return this.move;
	}

}

Add one swing player to rule them all

Add one swing player to rule them all


package org.scalaxb.maven.it;

import org.junit.Test;

public class ITP03WSDL extends AbstractIT {

    private String[] expected = new String[] {
            "generated/stockquote.scala",
            "generated/xmlprotocol.scala",
            "scalaxb/httpclients_dispatch.scala",
            "scalaxb/scalaxb.scala",
            "scalaxb/soap.scala",
            "soapenvelope12/soapenvelope12.scala",
            "soapenvelope12/soapenvelope12_xmlprotocol.scala"
    };

    @Test
    public void filesAreGeneratedInCorrectLocation() {
        assertFilesGenerated("itp03-wsdl", expected);
    }

}

package org.scalaxb.maven.it;

import org.junit.Test;

public class ITP03WSDL extends AbstractIT {

    private String[] expected = new String[] {
            "generated/stockquote.scala",
            "generated/xmlprotocol.scala",
            "scalaxb/httpclients_dispatch.scala",
            "scalaxb/scalaxb.scala",
            "scalaxb/soap12.scala",
            "soapenvelope12/soapenvelope12.scala",
            "soapenvelope12/soapenvelope12_xmlprotocol.scala"
    };

    @Test
    public void filesAreGeneratedInCorrectLocation() {
        assertFilesGenerated("itp03-wsdl", expected);
    }

}

Update WSDL integration test for 0.6.7

mvn-scalaxb: Update WSDL integration test for 0.6.7

The generated soap.scala file is now named soap12.scala.


/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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.facebook.litho;

import androidx.annotation.Nullable;

public class ArrayBatchAllocator {

  private static int batchSize = 200;

  @Nullable private static int[][] arrays = null;
  private static int index = 0;

  /** same as calling new int[2]; */
  public static int[] newArrayOfSize2() {
    if (arrays == null || arrays.length == index) {
      arrays = new int[batchSize][2];
      index = 0;
    }
    int[] toReturn = arrays[index];
    arrays[index++] = null;
    return toReturn;
  }
}

/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * 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.facebook.litho;

import androidx.annotation.Nullable;
import com.facebook.infer.annotation.Nullsafe;

@Nullsafe(Nullsafe.Mode.LOCAL)
public class ArrayBatchAllocator {

  private static int batchSize = 200;

  @Nullable private static int[][] arrays = null;
  private static int index = 0;

  /** same as calling new int[2]; */
  public static int[] newArrayOfSize2() {
    if (arrays == null || arrays.length == index) {
      arrays = new int[batchSize][2];
      index = 0;
    }
    int[] toReturn = arrays[index];
    arrays[index++] = null;
    return toReturn;
  }
}

Annotate clean classes as @Nullsafe:: (4/14) libraries/components/litho-core/src/main/java/com/facebook/litho/

Reviewed By: pasqualeanatriello

Differential Revision: D28505758

fbshipit-source-id: 2bb4c97a1d166c4090db5edb7e6178719f0c2a5d


package sample;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {

	private SessionFactory sessionFactory;

	public SampleController(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@RequestMapping("/")
	@Transactional
	public List<SampleEntity> home() {
		return this.sessionFactory.getCurrentSession()
				.createQuery("from SampleEntity se")
				.list();
	}

}

package sample;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SampleController {

	private SessionFactory sessionFactory;

	public SampleController(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@RequestMapping("/")
	@Transactional(readOnly = true)
	public List<SampleEntity> home() {
		return this.sessionFactory.getCurrentSession()
				.createQuery("from SampleEntity se")
				.list();
	}

}

Use readonly transactions where possible


package org.computelab.config;

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

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

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

public class PropertiesConfigReaderTest {

    private Properties properties;

    @Before
    public void before() throws IOException {
        try (InputStream inStream =
                getClass().getResourceAsStream("/test.properties")) {
            properties = new Properties();
            properties.load(inStream);
        }
    }

    @Test(expected=NullPointerException.class)
    public void constructorPropertiesCannotBeNull() {
        new PropertiesConfigReader(null);
    }

    @Test
    public void test() {
        PropertiesConfigReader reader = new PropertiesConfigReader(properties);
        assertEquals("567", reader.getVal("sp.researcher.id"));
        assertEquals("abc", reader.getVal("sp.provider.secret"));
        assertEquals("http://provider.test.com/, http://provider.test2.com/",
                reader.getVal("sp.provider.urls"));
    }

    @Test
    public void testMissingKey() {
        PropertiesConfigReader reader = new PropertiesConfigReader(properties);
        assertNull(reader.getVal("sp.researcher.key"));
    }
}

package org.computelab.config;

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

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

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

public class PropertiesConfigReaderTest {

    private Properties properties;

    @Before
    public void before() throws IOException {
        try (InputStream inStream =
                getClass().getResourceAsStream("/test.properties")) {
            properties = new Properties();
            properties.load(inStream);
        }
    }

    @Test(expected=NullPointerException.class)
    public void constructorPropertiesCannotBeNull() {
        new PropertiesConfigReader(null);
    }

    @Test
    public void test() {
        PropertiesConfigReader reader = new PropertiesConfigReader(properties);
        assertEquals("567", reader.getVal("sp.researcher.id"));
        assertEquals("abc", reader.getVal("sp.provider.secret"));
        assertEquals("http://provider.test.com/, http://provider.test2.com/",
                reader.getVal("sp.provider.urls"));
    }

    @Test
    public void testMissingKey() {
        PropertiesConfigReader reader = new PropertiesConfigReader(properties);
        assertNull(reader.getVal("sp.researcher.key"));
    }

    @Test
    public void emptyPropertiesAreAllowed() {
        PropertiesConfigReader reader = new PropertiesConfigReader(
                new Properties());
        assertNull(reader.getVal("sp.researcher.id"));
    }
}

Add test on empty properties

Add test on empty properties


package mtsar.api.validation;

import io.dropwizard.validation.ValidationMethod;
import mtsar.api.Answer;
import mtsar.api.Task;
import org.apache.commons.lang3.ArrayUtils;

public class TaskAnswerValidation {
    private final Task task;
    private final Answer answer;

    public TaskAnswerValidation(Task task, Answer answer) {
        this.task = task;
        this.answer = answer;
    }

    @ValidationMethod(message="task type 'single' requires one answer")
    public boolean isAnswerPresentForTypeSingle() {
        return !task.getType().equalsIgnoreCase("single") || ArrayUtils.getLength(answer.getAnswers()) == 1;
    }
}

package mtsar.api.validation;

import io.dropwizard.validation.ValidationMethod;
import mtsar.api.Answer;
import mtsar.api.Task;
import org.apache.commons.lang3.ArrayUtils;

public class TaskAnswerValidation {
    private final Task task;
    private final Answer answer;

    public TaskAnswerValidation(Task task, Answer answer) {
        this.task = task;
        this.answer = answer;
    }

    @ValidationMethod(message = "#task-single-no-answer: task type 'single' requires one answer")
    public boolean isAnswerPresentForTypeSingle() {
        return !task.getType().equalsIgnoreCase("single") || ArrayUtils.getLength(answer.getAnswers()) == 1;
    }

}

Add parsable IDs to validation errors

Add parsable IDs to validation errors [ci skip]


package org.hyperledger.fabricjavasdk.util;

import java.util.logging.Level;

public class Logger {
	private java.util.logging.Logger logger = null;

	private Logger(@SuppressWarnings("rawtypes") Class clazz) {
		this.logger = java.util.logging.Logger.getLogger(clazz.getName());
	}

	public static Logger getLogger(@SuppressWarnings("rawtypes") Class clazz) {
		return new Logger(clazz);
	}

	public void info(String message) {
		logger.info(message);
	}

	public void info(String message, Object... args) {
		logger.log(Level.INFO, message, args);
	}

	public void warn(String message) {
		logger.warning(message);
	}

	public void warn(String message, Object... args) {
		logger.log(Level.WARNING, message, args);
	}

	public void debug(String message) {
		logger.fine(message);
	}

	public void debug(String message, Object... args) {
		logger.log(Level.FINE, message, args);
	}
}

package org.hyperledger.fabricjavasdk.util;

import java.util.logging.Level;

public class Logger {
	private java.util.logging.Logger logger = null;

	private Logger(@SuppressWarnings("rawtypes") Class clazz) {
		this.logger = java.util.logging.Logger.getLogger(clazz.getName());
	}

	public static Logger getLogger(@SuppressWarnings("rawtypes") Class clazz) {
		return new Logger(clazz);
	}

	public void info(String message) {
		logger.info(message);
	}

	public void info(String message, Object... args) {
		logger.log(Level.INFO, String.format(message, args));
	}

	public void warn(String message) {
		logger.warning(message);
	}

	public void warn(String message, Object... args) {
		logger.log(Level.WARNING, String.format(message, args));
	}

	public void debug(String message) {
		logger.fine(message);
	}

	public void debug(String message, Object... args) {
		logger.log(Level.FINE, String.format(message, args));
	}
}

Use String.format for variable substitution in a log message


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

package org.eclipse.january.dataset;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

/**
 * Class used by DynamicDataset to delegate
 */
public class DataListenerDelegate {

	private List<IDataListener> listeners;

	public DataListenerDelegate() {
		listeners = Collections.synchronizedList(new ArrayList<IDataListener>());
	}

	public void addDataListener(IDataListener l) {
		synchronized (listeners) {
			if (!listeners.contains(l)) {
				listeners.add(l);
			}
		}
	}

	public void removeDataListener(IDataListener l) {
		listeners.remove(l);
	}

	public void fire(DataEvent evt) {
		synchronized (listeners) {
			for (Iterator<IDataListener> iterator = listeners.iterator(); iterator.hasNext();) {
				iterator.next().dataChangePerformed(evt);
			}
		}
	}

	public boolean hasDataListeners() {
		return listeners.size() > 0;
	}

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

}

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

package org.eclipse.january.dataset;

import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Class used by DynamicDataset to delegate
 */
public class DataListenerDelegate {

	private Set<IDataListener> listeners;

	public DataListenerDelegate() {
		listeners = Collections.newSetFromMap(new ConcurrentHashMap<IDataListener, Boolean>());
	}

	public void addDataListener(IDataListener l) {
		listeners.add(l);
	}

	public void removeDataListener(IDataListener l) {
		listeners.remove(l);
	}

	public void fire(DataEvent evt) {
		for (IDataListener listener : listeners) {
			listener.dataChangePerformed(evt);
		}
	}

	public boolean hasDataListeners() {
		return listeners.size() > 0;
	}

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

}

Improve thread safety around adding and removing IDataListener's

Previously deadlock was possible if a listener was running in the same
thread as a call attempting to add or remove listeners. As might be
commonly the case for the UI thread.

Also replaced the listeners List with a Set to prevent duplicate
listeners being added. Using a set backed by a ConcurrentHashMap should
allow all operation to complete safely without requiring external
synchronized, this allows the methods in the class to be simplified.

Signed-off-by: James Mudd <50b9fff9a292b5df2aef2220dca201538f796e13@diamond.ac.uk>


package io.github.vyo.hellojersey.application;

import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import io.swagger.jersey.listing.ApiListingResourceJSON;
import org.glassfish.jersey.server.ResourceConfig;

import javax.ws.rs.ApplicationPath;

/**
 * Created by Manuel Weidmann on 01.03.2015.
 */
@ApplicationPath("api")
public class Application extends ResourceConfig {

    public Application() {
        packages(true, "io.github.vyo.hellojersey");

        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setTitle("Hello Jersey");
        beanConfig.setVersion("3.1.0");
        beanConfig.setHost("hellojersey.herokuapp.com");
        beanConfig.setBasePath("/api");
        beanConfig.setResourcePackage("io.github.vyo.hellojersey");
        beanConfig.setScan(true);
        register(new ApiListingResourceJSON());
        register(new SwaggerSerializers());
    }
}

package io.github.vyo.hellojersey.application;

import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import io.swagger.jersey.listing.ApiListingResourceJSON;
import org.glassfish.jersey.server.ResourceConfig;

import javax.ws.rs.ApplicationPath;

/**
 * Created by Manuel Weidmann on 01.03.2015.
 */
@ApplicationPath("api")
public class Application extends ResourceConfig {

    public Application() {
        packages(true, "io.github.vyo.hellojersey");

        BeanConfig beanConfig = new BeanConfig();
        beanConfig.setTitle("Hello Jersey");
        beanConfig.setVersion("3.2.0");
        beanConfig.setHost("hellojersey.herokuapp.com");
        beanConfig.setBasePath("/api");
        beanConfig.setResourcePackage("io.github.vyo.hellojersey");
        beanConfig.setScan(true);
        register(new ApiListingResourceJSON());
        register(new SwaggerSerializers());
    }
}

Fix version in swagger spec to be 3.2.0

Fix version in swagger spec to be 3.2.0


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

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

import java.util.Map;

import org.apache.commons.lang3.builder.ToStringStyle;
import org.junit.jupiter.api.AfterEach;

public class AbstractLangTest {

    /**
     * All tests should leave the {@link ToStringStyle} registry empty.
     */
    @AfterEach
    public void after() {
        validateNullToStringStyleRegistry();
    }

    void validateNullToStringStyleRegistry() {
        final Map<Object, Object> registry = ToStringStyle.getRegistry();
        assertNull(registry, "Expected null, actual: " + registry);
    }

}

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

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

import java.util.Map;

import org.apache.commons.lang3.builder.ToStringStyle;
import org.junit.jupiter.api.AfterEach;

public class AbstractLangTest {

    /**
     * All tests should leave the {@link ToStringStyle} registry empty.
     */
    @AfterEach
    public void after() {
        validateNullToStringStyleRegistry();
    }

    void validateNullToStringStyleRegistry() {
        assertNull(ToStringStyle.getRegistry(), "Expected null, actual: " + ToStringStyle.getRegistry());
    }

}

Remove single use locval variable

Remove single use locval variable


package reactor.kafka;

import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;

public class KafkaPublisher<T> implements Publisher<T> {

  @Override
  public void subscribe(Subscriber<? super T> subscriber) {

  }
}

package reactor.kafka;

import kafka.consumer.Consumer;
import kafka.consumer.ConsumerConfig;
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import kafka.message.MessageAndMetadata;
import kafka.serializer.Decoder;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class KafkaPublisher<K, V> implements Publisher<KeyValuePair<K, V>> {

  private final static int concurrencyLevel = 1;

  private final ExecutorService                                           executor;
  private final Map<Subscription, Subscriber<? super KeyValuePair<K, V>>> subscribers;

  public KafkaPublisher(Properties consumerProperties,
                        String topic,
                        Decoder<K> keyDecoder,
                        Decoder<V> valueDecoder) {
    this.subscribers = new ConcurrentHashMap<>();
    this.executor = Executors.newFixedThreadPool(concurrencyLevel);
    ConsumerConnector consumer = Consumer.createJavaConsumerConnector(
      new ConsumerConfig(consumerProperties));

    Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
    topicCountMap.put(topic, concurrencyLevel);
    Map<String, List<KafkaStream<K, V>>> consumerMap =
      consumer.createMessageStreams(topicCountMap,
                                    keyDecoder,
                                    valueDecoder);
    List<KafkaStream<K, V>> streams = consumerMap.get(topic);

    for (final KafkaStream stream : streams) {
      executor.execute(() -> {
        ConsumerIterator<K, V> it = stream.iterator();
        while (it.hasNext() && !Thread.currentThread().isInterrupted()) {
          MessageAndMetadata<K, V> msg = it.next();
          KeyValuePair<K, V> kvp = new KeyValuePair<K, V>(msg.key(), msg.message());

          for(Map.Entry<Subscription, Subscriber<? super KeyValuePair<K, V>>> entry: subscribers.entrySet()) {
            entry.getValue().onNext(kvp);
          }

        }
      });
    }

  }

  @Override
  public void subscribe(Subscriber<? super KeyValuePair<K, V>> subscriber) {
    this.subscribers.put(new KafkaSubscription<>(subscriber,
                                                 subscribers::remove),
                         subscriber);

  }

}

Implement kafka publisher on top of reactive streams


package org.themoviedb.movieinfo.testcase;

import org.robolectric.annotation.Config;
import org.themoviedb.movieinfo.BuildConfig;
import org.themoviedb.movieinfo.TestApplication;

@Config(application = TestApplication.class,
        constants = BuildConfig.class,
        sdk = 18)
public class BaseTest {
}

package org.themoviedb.movieinfo.testcase;

import org.robolectric.annotation.Config;
import org.themoviedb.movieinfo.BuildConfig;
import org.themoviedb.movieinfo.TestApplication;

@Config(application = TestApplication.class,
        constants = BuildConfig.class,
        sdk = 21)
public class BaseTest {
}

Use sdk 21 to run robolectric

Use sdk 21 to run robolectric


public class HelloWorldAppl {

	public static void main(String[] args) {
		System.out.println("Hello, world!");
	}

}

public class HelloWorldAppl {

	public static void main(String[] args) {
		System.out.println("Hello, world!");
		System.out.println("Good buy, world!");
	}

}

Add "Good buy" to main appl

Add "Good buy" to main appl


package me.coley.recaf.command.completion;

import me.coley.recaf.Recaf;
import me.coley.recaf.workspace.Workspace;

import java.util.*;

/**
 * Picocli completion for names loaded in the current workspace.
 *
 * @author Matt
 */
public abstract class WorkspaceNameCompletions implements Iterable<String> {
	@Override
	public Iterator<String> iterator() {
		Workspace workspace = Recaf.getCurrentWorkspace();
		if (workspace == null)
			return Collections.emptyIterator();
		return workspace.getClassNames().stream().sorted().iterator();
	}
}

package me.coley.recaf.command.completion;

import me.coley.recaf.Recaf;
import me.coley.recaf.workspace.Workspace;

import java.util.*;

/**
 * Picocli completion for names loaded in the current workspace.
 *
 * @author Matt
 */
public class WorkspaceNameCompletions implements Iterable<String> {
	@Override
	public Iterator<String> iterator() {
		Workspace workspace = Recaf.getCurrentWorkspace();
		if (workspace == null)
			return Collections.emptyIterator();
		return workspace.getClassNames().stream().sorted().iterator();
	}
}

Fix initialization error for autocompletion


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

//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//

package javax.persistence;

public interface TupleElement<X> {
    Class<? extends X> getJavaType();

    String getAlias();
}

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

//
// This source code implements specifications defined by the Java
// Community Process. In order to remain compliant with the specification
// DO NOT add / change / or delete method signatures!
//

package javax.persistence;

public interface TupleElement<X> {
    Class<X> getJavaType();

    String getAlias();
}

Revert last JPA EA7 change per Jeremy/Panaki for further testing

git-svn-id: 60e751271f50ec028ae56d425821c1c711e0b018@807385 13f79535-47bb-0310-9956-ffa450edef68


package com.amalgam.view;

import android.content.res.Resources;
import android.util.DisplayMetrics;
import android.view.WindowManager;

public final class ViewUtils {
    private ViewUtils() {}

    /**
     * Convert the dips to pixels, based on density scale
     *
     * @param resources application resources
     * @param dip to be converted value
     * @return converted value(px)
     */
    public static int dipToPixel(Resources resources, int dip) {
        final float scale = resources.getDisplayMetrics().density;
        // add 0.5f to round the figure up to the nearest whole number
        return (int) (dip * scale + 0.5f);
    }

    /**
     * Convert the pixels to dips, based on density scale
     * @param windowManager the window manager of the display to use the scale density of
     * @param pixel
     * @return converted value(dip)
     */
    public static float pixelToDip(WindowManager windowManager, int pixel) {
        float dip = 0;
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        dip = metrics.scaledDensity * pixel;
        return dip;
    }
}

package com.amalgam.view;

import android.content.Context;
import android.content.res.Resources;
import android.hardware.display.DisplayManager;
import android.util.DisplayMetrics;
import android.view.WindowManager;

import com.amalgam.content.ContextUtils;

public final class ViewUtils {
    private ViewUtils() {}

    public static int dipToPixel(Context context, int dip) {
        return dipToPixel(context.getResources(), dip);
    }

    /**
     * Convert the dips to pixels, based on density scale
     *
     * @param resources application resources
     * @param dip to be converted value
     * @return converted value(px)
     */
    public static int dipToPixel(Resources resources, int dip) {
        final float scale = resources.getDisplayMetrics().density;
        // add 0.5f to round the figure up to the nearest whole number
        return (int) (dip * scale + 0.5f);
    }

    public static float pixelToDip(Context context, int pixel) {
        return pixelToDip(ContextUtils.getWindowManager(context), pixel);
    }

    /**
     * Convert the pixels to dips, based on density scale
     * @param windowManager the window manager of the display to use the scale density of
     * @param pixel
     * @return converted value(dip)
     */
    public static float pixelToDip(WindowManager windowManager, int pixel) {
        DisplayMetrics metrics = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(metrics);
        return metrics.scaledDensity * pixel;
    }

    public static float sipToPixel(Context context, float sip) {
        return sipToPixel(context.getResources(), sip);
    }

    public static float sipToPixel(Resources resources, float sip) {
        float density = resources.getDisplayMetrics().scaledDensity;
        return sip * density;
    }

    public static float pixelToSip(Context context, float pixels) {
        DisplayMetrics metrics = new DisplayMetrics();
        float scaledDensity = metrics.scaledDensity;
        if (pixels == 0 || scaledDensity == 0) {
            return 1;
        }
        return pixels/scaledDensity;
    }
}

Add sip to pixel conversion

Add sip to pixel conversion


package org.sagebionetworks.dashboard;

import javax.annotation.Resource;

import org.sagebionetworks.dashboard.service.BridgeDynamoImporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Schedules the work of importing Bridge data into data warehouse.
 */
@Component("bridgeScheduler")
public final class BridgeScheduler {

    private final Logger logger = LoggerFactory.getLogger(BridgeScheduler.class);

    @Resource
    private BridgeDynamoImporter bridgeDynamoImporter;

    /**
     * 12 pm UTC or 5 am PDT.  Make sure this happens after daily backup is done.
     */
    @Scheduled(cron="00 55 * * * *", zone="UTC")
    public void run() {
        logger.info("Begin importing Bridge DynamoDB tables to Redshift.");
        bridgeDynamoImporter.run();
        logger.info("Finished importing Bridge DynamoDB tables to Redshift.");
    }
}

package org.sagebionetworks.dashboard;

import javax.annotation.Resource;

import org.sagebionetworks.dashboard.service.BridgeDynamoImporter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * Schedules the work of importing Bridge data into data warehouse.
 */
@Component("bridgeScheduler")
public final class BridgeScheduler {

    private final Logger logger = LoggerFactory.getLogger(BridgeScheduler.class);

    @Resource
    private BridgeDynamoImporter bridgeDynamoImporter;

    /**
     * 12 pm UTC or 5 am PDT.  Make sure this happens after daily backup is done.
     */
    @Scheduled(cron="00 00 12 * * *", zone="UTC")
    public void run() {
        logger.info("Begin importing Bridge DynamoDB tables to Redshift.");
        bridgeDynamoImporter.run();
        logger.info("Finished importing Bridge DynamoDB tables to Redshift.");
    }
}

Change back Bridge scheduler to 12 pm daily


package com.example.myapplication;

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

public class MainActivity extends AppCompatActivity {

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

    }
}

package com.example.myapplication;

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

public class MainActivity extends AppCompatActivity {

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

    }
}

Rebase interactive rebase in progress; onto d2cd27f


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

import java.util.logging.Logger;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class Resources {

    // Expose an entity manager using the resource producer pattern
    @SuppressWarnings("unused")
    @PersistenceContext
    @Produces
    private EntityManager em;

    @Produces
    public Logger getLogger(InjectionPoint ip) {
        String category = ip.getMember().getDeclaringClass().getName();
        return Logger.getLogger(category);
    }

    @Produces
    @RequestScoped
    public FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

}

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

import java.util.logging.Logger;

import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class Resources {

    // Expose an entity manager using the resource producer pattern
    @PersistenceContext
    @Produces
    private EntityManager em;

    @Produces
    public Logger getLogger(InjectionPoint ip) {
        String category = ip.getMember().getDeclaringClass().getName();
        return Logger.getLogger(category);
    }

    @Produces
    @RequestScoped
    public FacesContext getFacesContext() {
        return FacesContext.getCurrentInstance();
    }

}

Bz1178769: Fix JBDS import errors for greeter quickstart


package edu.northwestern.bioinformatics.studycalendar.domain.delta;

import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeInnerNode;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;

import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
import javax.persistence.Column;
import java.util.Set;

import org.hibernate.validator.NotNull;

/**
 * @author Rhett Sutphin
 */
@Entity // TODO
@DiscriminatorValue("add")
public class Add extends Change {
    private Integer newChildId;
    private Integer index;

    @Override
    @Transient
    public ChangeAction getAction() { return ChangeAction.ADD; }

    ////// BEAN PROPERTIES

    @Column (name = "new_value")
    public Integer getNewChildId() {
        return newChildId;
    }

    public void setNewChildId(Integer newChildId) {
        this.newChildId = newChildId;
    }

    @Column (name = "attribute")
    public Integer getIndex() {
        return index;
    }

    public void setIndex(Integer index) {
        this.index = index;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(getClass().getSimpleName())
            .append("[id=").append(getId()).append("; child id ").append(getNewChildId());
        if (getIndex() != null) {
            sb.append(" at index ").append(getIndex());
        }
        return sb.append(']').toString();
    }
}

package edu.northwestern.bioinformatics.studycalendar.domain.delta;

import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeInnerNode;
import edu.northwestern.bioinformatics.studycalendar.domain.PlanTreeNode;

import javax.persistence.Entity;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Transient;
import javax.persistence.Column;
import java.util.Set;

import org.hibernate.validator.NotNull;

/**
 * @author Rhett Sutphin
 */
@Entity
@DiscriminatorValue("add")
public class Add extends Change {
    private Integer newChildId;
    private Integer index;

    @Override
    @Transient
    public ChangeAction getAction() { return ChangeAction.ADD; }

    ////// BEAN PROPERTIES

    @Column (name = "new_value")
    public Integer getNewChildId() {
        return newChildId;
    }

    public void setNewChildId(Integer newChildId) {
        this.newChildId = newChildId;
    }

    @Column (name = "attribute")
    public Integer getIndex() {
        return index;
    }

    public void setIndex(Integer index) {
        this.index = index;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(getClass().getSimpleName())
            .append("[id=").append(getId()).append("; child id ").append(getNewChildId());
        if (getIndex() != null) {
            sb.append(" at index ").append(getIndex());
        }
        return sb.append(']').toString();
    }
}

Remove TODO for done thing

Remove TODO for done thing

git-svn-id: 4b387fe5ada7764508e2ca96c335714e4c1692c6@1257 0d517254-b314-0410-acde-c619094fa49f


package org.realityforge.replicant.client;

/**
 * Interface implemented by imitations that need to be linked.
 */
public interface Linkable
{
  void link();

  void delink();
}

package org.realityforge.replicant.client;

/**
 * Interface implemented by imitations that need to be linked.
 */
public interface Linkable
{
  /**
   * Resolve any references to related entities.
   */
  void link();

  /**
   * Remove direct references to related entities and mark as unresolved.
   */
  void delink();
}

Add some basic javadoc documentation

Add some basic javadoc documentation


package org.michaelbel.bottomsheet.annotation;

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

/**
 * Date: Sut, Mar 3 2018
 * Time: 20:09 MSK
 *
 * @author Michael Bel
 */

@Retention(RetentionPolicy.CLASS)
@Target({
        ElementType.ANNOTATION_TYPE,
        ElementType.CONSTRUCTOR,
        ElementType.FIELD,
        ElementType.METHOD,
        ElementType.TYPE })
@Documented
@SuppressWarnings("all")
public @interface New {}

package org.michaelbel.bottomsheet.annotation;

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

/**
 * Date: Sut, Mar 3 2018
 * Time: 20:09 MSK
 *
 * @author Michael Bel
 */

@Retention(RetentionPolicy.SOURCE)
@Target({
        ElementType.ANNOTATION_TYPE,
        ElementType.CONSTRUCTOR,
        ElementType.FIELD,
        ElementType.METHOD,
        ElementType.TYPE })
@Documented
@SuppressWarnings("all")
public @interface New {
    String version();
}

Update retention policy and add version field


package wumpus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;

import wumpus.Environment.*;

/**
 * The iteration of plays that the player can take until reaches its end.
 */
public class Runner implements Iterable<Player>, Iterator<Player> {
    private static final int DEFAULT_MAX_ITERATIONS = 200;

    private final World world;
    private int iterations = 0;

    /**
     * The runner constructor.
     * @param world The world instance.
     */
    public Runner(World world) {
        this.world = world;
    }

    /**
     * Returns the iterator that can be user in a loop.
     * @return Itself
     */
    public Iterator<Player> iterator() {
        return this;
    }

    /**
     * Check if the game has ended.
     * @return
     */
    public boolean hasNext() {
        Player player = world.getPlayer();
        return iterations < DEFAULT_MAX_ITERATIONS &&
                player.isAlive() && player.getResult() != Result.WIN;
    }

    /**
     * Get player instance to calculate the next iteration.
     * @return The current player instance
     */
    public Player next() {
        if (!hasNext()) throw new NoSuchElementException();
        iterations++;
        return world.getPlayer();
    }

    /**
     * Operation not supported, throws an error.
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }

    /**
     * Get how many iterations have been made so far.
     * @return The amount of iterations
     */
    public int getDepth() {
        return iterations;
    }
}

package wumpus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;

import wumpus.Environment.*;

/**
 * The iteration of plays that the player can take until reaches its end.
 */
public class Runner implements Iterable<Player>, Iterator<Player> {
    private static final int DEFAULT_MAX_ITERATIONS = 200;

    private final World world;
    private final String name;
    private int iterations = 0;

    /**
     * The runner constructor.
     * @param world The world instance.
     */
    public Runner(String name, World world) {
        this.name = name;
        this.world = world;
    }

    /**
     * Returns the iterator that can be user in a loop.
     * @return Itself
     */
    public Iterator<Player> iterator() {
        return this;
    }

    /**
     * Check if the game has ended.
     * @return
     */
    public boolean hasNext() {
        Player player = world.getPlayer();
        return iterations < DEFAULT_MAX_ITERATIONS &&
                player.isAlive() && player.getResult() != Result.WIN;
    }

    /**
     * Get player instance to calculate the next iteration.
     * @return The current player instance
     */
    public Player next() {
        if (!hasNext()) throw new NoSuchElementException();
        iterations++;
        return world.getPlayer();
    }

    /**
     * Operation not supported, throws an error.
     */
    public void remove() {
        throw new UnsupportedOperationException();
    }

    /**
     * Get how many iterations have been made so far.
     * @return The amount of iterations
     */
    public int getDepth() {
        return iterations;
    }
}

Add a name to the runner

Add a name to the runner


/*
 * IKToolExecutor.java
 *
 * Created on August 11, 2010, 12:38 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.opensim.tools.serializers;

import java.io.IOException;
import java.util.Observable;
import org.opensim.modeling.Model;
import org.opensim.tools.serializers.ToolExecutor.Operation;
import org.opensim.tracking.ForwardToolModel;
import org.opensim.tracking.ResultDisplayerInterface;

/**
 *
 * @author ayman
 */
public class ForwardToolExecutor extends ToolExecutor  {

    ForwardToolModel toolModel;

    /** Creates a new instance of IKToolExecutor */
    public ForwardToolExecutor(Model model, String setupFile, ResultDisplayerInterface displayer) throws IOException {
        super(model, setupFile);
        toolModel = new ForwardToolModel(model);
        toolModel.addResultDisplayer(displayer);
        //toolModel.loadSettings(setupFile);
        toolModel.addObserver(this);
    }

    public void execute() {
        toolModel.loadSettings(setupFile);
        toolModel.execute();
    }

    public void cancel() {
        toolModel.cancel();
    }

    public void update(Observable o, Object arg) {
          if (arg==ForwardToolModel.Operation.ExecutionStateChanged && !toolModel.isExecuting()){
             setChanged();
             notifyObservers(Operation.ExecutionFinished);
         }
    }

}

/*
 * IKToolExecutor.java
 *
 * Created on August 11, 2010, 12:38 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.opensim.tools.serializers;

import java.io.IOException;
import java.util.Observable;
import org.opensim.modeling.Model;
import org.opensim.tools.serializers.ToolExecutor.Operation;
import org.opensim.tracking.ForwardToolModel;
import org.opensim.tracking.ResultDisplayerInterface;

/**
 *
 * @author ayman
 */
public class ForwardToolExecutor extends ToolExecutor  {

    ForwardToolModel toolModel;

    /** Creates a new instance of IKToolExecutor */
    public ForwardToolExecutor(Model model, String setupFile, ResultDisplayerInterface displayer) throws IOException {
        super(model, setupFile);
        toolModel = new ForwardToolModel(model);
        toolModel.addResultDisplayer(displayer);
        //toolModel.loadSettings(setupFile);
        toolModel.addObserver(this);
    }

    public void execute() {
        toolModel.loadSettings(setupFile);
        toolModel.execute();
    }

    public void cancel() {
        toolModel.interrupt(true);
    }

    public void update(Observable o, Object arg) {
          if (arg==ForwardToolModel.Operation.ExecutionStateChanged && !toolModel.isExecuting()){
             setChanged();
             notifyObservers(Operation.ExecutionFinished);
         }
    }

}

GUI: Make stop button from custom gui keep partial results

git-svn-id: c451f99c539e6b066ec18a47a9c67064d2e0d34d@8709 fc29be9c-2cb0-420d-b520-73dbd18add6e


package sk.tuke.cloud.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * @author Dominik Matta
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final PublicKeyProvider publicKeyProvider;

    @Autowired
    public SecurityConfiguration(PublicKeyProvider publicKeyProvider) {
        this.publicKeyProvider = publicKeyProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .apply(new JWTConfigurer(publicKeyProvider));
    }
}

package sk.tuke.cloud.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

/**
 * @author Dominik Matta
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    private final PublicKeyProvider publicKeyProvider;

    @Autowired
    public SecurityConfiguration(PublicKeyProvider publicKeyProvider) {
        this.publicKeyProvider = publicKeyProvider;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
                .authorizeRequests()
                .anyRequest().authenticated()
        .and()
                .apply(new JWTConfigurer(publicKeyProvider));
        // @formatter:on
    }
}

Disable code formatting in security configuration region


/*
 * See LICENSE file in distribution for copyright and licensing information.
 */
package ioke.lang;

import java.util.IdentityHashMap;

/**
 *
 * @author Ola Bini
 */
public class Context extends IokeObject {
    IokeObject ground;

    public IokeObject message;
    public IokeObject surroundingContext;

    public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) {
        super(runtime, documentation);
        this.ground = ground.getRealContext();
        this.message = message;
        this.surroundingContext = surroundingContext;

        if(runtime.context != null) {
            this.mimics(runtime.context);
        }

        setCell("self", getRealContext());
    }

    public void init() {
    }

    public IokeObject getRealContext() {
        return ground;
    }

    public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) {
        IokeObject nn = super.findCell(m, context, name, visited);

        if(nn == runtime.nul) {
            return ground.findCell(m, context, name, visited);
        } else {
            return nn;
        }
    }

    @Override
    public String toString() {
        return "Context:" + System.identityHashCode(this) + "<" + ground + ">";
    }
}// Context

/*
 * See LICENSE file in distribution for copyright and licensing information.
 */
package ioke.lang;

import java.util.IdentityHashMap;

/**
 *
 * @author Ola Bini
 */
public class Context extends IokeObject {
    IokeObject ground;

    public IokeObject message;
    public IokeObject surroundingContext;

    public Context(Runtime runtime, IokeObject ground, String documentation, IokeObject message, IokeObject surroundingContext) {
        super(runtime, documentation);
        this.ground = ground.getRealContext();
        this.message = message;
        this.surroundingContext = surroundingContext;

        if(runtime.context != null) {
            this.mimics(runtime.context);
        }

        setCell("self", getRealContext());
    }

    public void init() {
        setKind("Context");
    }

    public IokeObject getRealContext() {
        return ground;
    }

    public IokeObject findCell(IokeObject m, IokeObject context, String name, IdentityHashMap<IokeObject, Object> visited) {
        IokeObject nn = super.findCell(m, context, name, visited);

        if(nn == runtime.nul) {
            return ground.findCell(m, context, name, visited);
        } else {
            return nn;
        }
    }

    @Override
    public String toString() {
        return "Context:" + System.identityHashCode(this) + "<" + ground + ">";
    }
}// Context

Complete refactoring, including addition of kind to all core objects


package backupBasic.backup;
/*(c)2016, Tobias Hotz
 * Further Information can be found in Info.txt
 */

import backupBasic.util.i18n;

import javax.swing.*;
import java.awt.*;
import java.util.logging.Logger;

/**
 * @author Tobias Hotz
 */
public class Main implements Thread.UncaughtExceptionHandler {

    private static final Logger logger = i18n.getLogger(Main.class);
	/**
	 * Verwaltet das Logging-System und gibt dann an den ArgParser ab
	 */
	public static void main(String[] args) {
		Thread.setDefaultUncaughtExceptionHandler(new Main());
        i18n.initLogging();
        ArgParser.parseArgs(args);
	}

	@Override
	public void uncaughtException(Thread t, Throwable e) {
		logger.severe(i18n.translate("UncaughtException")+ "\t Stacktrace:");
		e.printStackTrace();
		if(!GraphicsEnvironment.isHeadless()) {
			JOptionPane.showMessageDialog(null, i18n.translate("UncaughtException") + "\n" + i18n.translate("Error") + ": "+ e +"\n" +  i18n.translate("Details"), "ERROR", JOptionPane.ERROR_MESSAGE);
		}
		System.exit(-1);
	}
}

package backupBasic.backup;
/*(c)2016, Tobias Hotz
 * Further Information can be found in Info.txt
 */

import backupBasic.util.i18n;

import javax.swing.*;
import java.awt.*;
import java.util.logging.Logger;

/**
 * @author Tobias Hotz
 */
public class Main implements Thread.UncaughtExceptionHandler {
    private static final Logger logger = i18n.getLogger(Main.class);

	/**
	 * Verwaltet das Logging-System und gibt dann an den ArgParser ab
	 */
	public static void main(String[] args) {
		Thread.setDefaultUncaughtExceptionHandler(new Main());
        i18n.initLogging();
        ArgParser.parseArgs(args);
	}

	@Override
	public void uncaughtException(Thread t, Throwable e) {
	    try {
            logger.severe(i18n.translate("UncaughtException")+ "\t Stacktrace:");
            e.printStackTrace();
            if(!GraphicsEnvironment.isHeadless())
                JOptionPane.showMessageDialog(null, i18n.translate("UncaughtException") +
                        "\n" + i18n.translate("Error") + ": " + e + "\n" + i18n.translate("Details"), "ERROR", JOptionPane.ERROR_MESSAGE);
            } catch(Exception e2) {
	            e.printStackTrace();
	            System.err.println("Errors while printing Error:");
	            e2.printStackTrace();
	            if(!GraphicsEnvironment.isHeadless())
	            JOptionPane.showMessageDialog(null, "An fatal error occurred, and the program crashed." +
                        "\nIn addition to that, it failed to translate this Message", "ERROR", JOptionPane.ERROR_MESSAGE);
            }
		System.exit(-1);
	}
}

Fix crash when showing crash information


package com.faforever.api.db;

import com.faforever.api.config.ApplicationProfile;
import org.springframework.context.annotation.Profile;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.util.Objects;

@Component
@Profile(ApplicationProfile.PRODUCTION)
public class SchemaVersionVerifier implements PriorityOrdered {

  private static final String DB_COMPATIBILITY_VERSION = "35";

  private final SchemaVersionRepository schemaVersionRepository;

  public SchemaVersionVerifier(SchemaVersionRepository schemaVersionRepository) {
    this.schemaVersionRepository = schemaVersionRepository;
  }

  @PostConstruct
  public void postConstruct() {
    String maxVersion = schemaVersionRepository.findMaxVersion()
      .orElseThrow(() -> new IllegalStateException("No database version is available"));

    Assert.state(Objects.equals(DB_COMPATIBILITY_VERSION, maxVersion),
      String.format("Database version is '%s' but this software requires '%s'", maxVersion, DB_COMPATIBILITY_VERSION));
  }

  @Override
  public int getOrder() {
    return HIGHEST_PRECEDENCE;
  }
}

package com.faforever.api.db;

import com.faforever.api.config.ApplicationProfile;
import org.springframework.context.annotation.Profile;
import org.springframework.core.PriorityOrdered;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.util.Objects;

@Component
@Profile(ApplicationProfile.PRODUCTION)
public class SchemaVersionVerifier implements PriorityOrdered {

  private static final String DB_COMPATIBILITY_VERSION = "43";

  private final SchemaVersionRepository schemaVersionRepository;

  public SchemaVersionVerifier(SchemaVersionRepository schemaVersionRepository) {
    this.schemaVersionRepository = schemaVersionRepository;
  }

  @PostConstruct
  public void postConstruct() {
    String maxVersion = schemaVersionRepository.findMaxVersion()
      .orElseThrow(() -> new IllegalStateException("No database version is available"));

    Assert.state(Objects.equals(DB_COMPATIBILITY_VERSION, maxVersion),
      String.format("Database version is '%s' but this software requires '%s'", maxVersion, DB_COMPATIBILITY_VERSION));
  }

  @Override
  public int getOrder() {
    return HIGHEST_PRECEDENCE;
  }
}

Update required DB version to v43

Update required DB version to v43


package com.telecomsys.cmc.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;

/**
 * The schedule message model which encapsulates the request and response sent when the client requests details about a
 * scheduled message.
 */
@JsonRootName("schedulemessage")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPropertyOrder(alphabetic = true)
public class ScheduleMessage {

    /**
     * Message id of the scheduled message.
     */
    @JsonProperty("messageID")
    private Long messageId;

    /**
     * Message data.
     */
    private Message message;

    /**
     * Schedule data.
     */
    private Schedule schedule;

    /**
     * @return the messageId
     */
    public Long getMessageId() {
        return messageId;
    }

    /**
     * @param messageId the messageId to set
     */
    public void setMessageId(Long messageId) {
        this.messageId = messageId;
    }

    /**
     * @return the schedule
     */
    public Schedule getSchedule() {
        return schedule;
    }

    /**
     * @param schedule the schedule to set
     */
    public void setSchedule(Schedule schedule) {
        this.schedule = schedule;
    }

    /**
     * @return the message
     */
    public Message getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(Message message) {
        this.message = message;
    }
}

package com.telecomsys.cmc.model;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;

/**
 * The schedule message model which encapsulates the request and response sent when the client requests details about a
 * scheduled message.
 */
@JsonRootName("schedulemessage")
@JsonIgnoreProperties(ignoreUnknown = true)
public class ScheduleMessage {

    /**
     * Message id of the scheduled message.
     */
    @JsonProperty("messageID")
    private Long messageId;

    /**
     * Message data.
     */
    private Message message;

    /**
     * Schedule data.
     */
    private Schedule schedule;

    /**
     * @return the messageId
     */
    public Long getMessageId() {
        return messageId;
    }

    /**
     * @param messageId the messageId to set
     */
    public void setMessageId(Long messageId) {
        this.messageId = messageId;
    }

    /**
     * @return the schedule
     */
    public Schedule getSchedule() {
        return schedule;
    }

    /**
     * @param schedule the schedule to set
     */
    public void setSchedule(Schedule schedule) {
        this.schedule = schedule;
    }

    /**
     * @return the message
     */
    public Message getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(Message message) {
        this.message = message;
    }
}

Remove order as the tests are independent of the order.


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

public interface Infinite<T> {
	boolean isNaN(T a);
	boolean isInfinite(T a);
	// positive or negative can be determined with signum() for Ordered groups.
	// Complex has no concept of pos inf and neg inf.
}

Add missing license header to an interface


package pokefenn.totemic.apiimpl.totem;

import pokefenn.totemic.api.totem.TotemEffect;
import pokefenn.totemic.api.totem.TotemEffectAPI;
import pokefenn.totemic.api.totem.TotemEffectContext;

public enum TotemEffectApiImpl implements TotemEffectAPI {
    INSTANCE;

    @Override
    public int getDefaultRange(TotemEffect effect, int repetition, TotemEffectContext context) {
        return getDefaultRange(effect, DEFAULT_BASE_RANGE, repetition, context);
    }

    @Override
    public int getDefaultRange(TotemEffect effect, int repetition, int baseRange, TotemEffectContext context) {
        return baseRange + context.getTotemEffectMusic() / 32 + (context.getPoleSize() >= TotemEffectAPI.MAX_POLE_SIZE ? 1 : 0);
    }
}

package pokefenn.totemic.apiimpl.totem;

import pokefenn.totemic.api.totem.TotemEffect;
import pokefenn.totemic.api.totem.TotemEffectAPI;
import pokefenn.totemic.api.totem.TotemEffectContext;

public enum TotemEffectApiImpl implements TotemEffectAPI {
    INSTANCE;

    @Override
    public int getDefaultRange(TotemEffect effect, int repetition, TotemEffectContext context) {
        return getDefaultRange(effect, repetition, DEFAULT_BASE_RANGE, context);
    }

    @Override
    public int getDefaultRange(TotemEffect effect, int repetition, int baseRange, TotemEffectContext context) {
        return baseRange + context.getTotemEffectMusic() / 32 + (context.getPoleSize() >= TotemEffectAPI.MAX_POLE_SIZE ? 1 : 0);
    }
}

Fix getDefaultRange, wrong order of parameters


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blazzify.jasonium.ui;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;

/**
 *
 * @author Azzuwan Aziz <azzuwan@gmail.com>
 */
public class ServerTreeContextMenu extends ContextMenu {

    MenuItem connect = new MenuItem("Connect");
    MenuItem disconnect = new MenuItem("Disconnect");
    MenuItem remove = new MenuItem("Remove");

    public ServerTreeContextMenu() {
        connect.setOnAction((event) -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK);
        });
        disconnect.setOnAction((event) -> {
        });
        remove.setOnAction((event) -> {
        });
        this.getItems().addAll(connect, disconnect, remove);
    }

}

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.blazzify.jasonium.ui;

import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;

/**
 *
 * @author Azzuwan Aziz <azzuwan@gmail.com>
 */
public class ServerTreeContextMenu extends ContextMenu {

    MenuItem connect = new MenuItem("Connect");
    MenuItem disconnect = new MenuItem("Disconnect");
    MenuItem remove = new MenuItem("Remove");

    public ServerTreeContextMenu() {
        connect.setOnAction((event) -> {
            Alert alert = new Alert(Alert.AlertType.INFORMATION, "Connecting!", ButtonType.OK);
            alert.showAndWait();
        });
        disconnect.setOnAction((event) -> {
        });
        remove.setOnAction((event) -> {
        });
        this.getItems().addAll(connect, disconnect, remove);
    }

}

Refactor server tree context menu into it's own component


package com.thoughtworks.acceptance;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.synth.SynthLookAndFeel;

public class SwingTest extends AbstractAcceptanceTest {

    // JTable is one of the nastiest components to serialize. If this works, we're in good shape :)

    public void testJTable() {
        // Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
        JTable original = new JTable();
        String originalXml = xstream.toXML(original);

        JTable deserialized = (JTable) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);
    }

    public void testDefaultListModel() {
        final DefaultListModel original = new DefaultListModel();
        final JList list = new JList();
        list.setModel(original);

        String originalXml = xstream.toXML(original);

        DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

    public void testSynthLookAndFeel() {
        LookAndFeel plaf = new SynthLookAndFeel();
        String originalXml = xstream.toXML(plaf);
        assertBothWays(plaf, originalXml);
    }
}

package com.thoughtworks.acceptance;

import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JTable;
import javax.swing.LookAndFeel;
import javax.swing.plaf.metal.MetalLookAndFeel;

public class SwingTest extends AbstractAcceptanceTest {

    // JTable is one of the nastiest components to serialize. If this works, we're in good shape :)

    public void testJTable() {
        // Note: JTable does not have a sensible .equals() method, so we compare the XML instead.
        JTable original = new JTable();
        String originalXml = xstream.toXML(original);

        JTable deserialized = (JTable) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);
    }

    public void testDefaultListModel() {
        final DefaultListModel original = new DefaultListModel();
        final JList list = new JList();
        list.setModel(original);

        String originalXml = xstream.toXML(original);

        DefaultListModel deserialized = (DefaultListModel) xstream.fromXML(originalXml);
        String deserializedXml = xstream.toXML(deserialized);

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

    public void testMetalLookAndFeel() {
        LookAndFeel plaf = new MetalLookAndFeel();
        String originalXml = xstream.toXML(plaf);
        assertBothWays(plaf, originalXml);
    }
}

Use L&F that is available on JDK 1.3

Use L&F that is available on JDK 1.3

git-svn-id: fe6d842192ccfb78748eb71580d1ce65f168b559@1344 9830eeb5-ddf4-0310-9ef7-f4b9a3e3227e


/*
 * 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 io.opencensus.trace.unsafe;

import io.grpc.Context;
import io.opencensus.trace.Span;

/**
 * Util methods/functionality to interact with the {@link io.grpc.Context}.
 *
 * <p>Users must interact with the current Context via the public APIs in {@link
 * io.opencensus.trace.Tracer} and avoid usages of the {@link #CONTEXT_SPAN_KEY} directly.
 */
public final class ContextUtils {
  // No instance of this class.
  private ContextUtils() {}

  /** The {@link io.grpc.Context.Key} used to interact with {@link io.grpc.Context}. */
  public static final Context.Key<Span> CONTEXT_SPAN_KEY = Context.key("instrumentation-trace-key");
}

/*
 * 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 io.opencensus.trace.unsafe;

import io.grpc.Context;
import io.opencensus.trace.Span;

/**
 * Util methods/functionality to interact with the {@link io.grpc.Context}.
 *
 * <p>Users must interact with the current Context via the public APIs in {@link
 * io.opencensus.trace.Tracer} and avoid usages of the {@link #CONTEXT_SPAN_KEY} directly.
 */
public final class ContextUtils {
  // No instance of this class.
  private ContextUtils() {}

  /** The {@link io.grpc.Context.Key} used to interact with {@link io.grpc.Context}. */
  public static final Context.Key<Span> CONTEXT_SPAN_KEY = Context.key("opencensus-trace-span-key");
}

Rename trace io.grpc.Context key to opencensus-trace-span-key.


// 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 codeu.chat;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public final class TestRunner {
  public static void main(String[] args) {
     final Result result =
         JUnitCore.runClasses(
             codeu.chat.common.SecretTest.class,
             codeu.chat.relay.ServerTest.class,
             codeu.chat.server.BasicControllerTest.class,
             codeu.chat.server.RawControllerTest.class,
             codeu.chat.util.TimeTest.class,
             codeu.chat.util.UuidTest.class,
             codeu.chat.util.store.StoreTest.class
         );
      for (final Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

// 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 codeu.chat;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public final class TestRunner {
  public static void main(String[] args) {
     final Result result =
         JUnitCore.runClasses(
             codeu.chat.common.SecretTest.class,
             codeu.chat.relay.ServerTest.class,
             codeu.chat.server.BasicControllerTest.class,
             codeu.chat.server.RawControllerTest.class,
             codeu.chat.util.TimeTest.class,
             codeu.chat.util.UuidTest.class,
             codeu.chat.util.store.StoreTest.class,
             codeu.chat.util.TokenizerTest.class
         );
      for (final Failure failure : result.getFailures()) {
         System.out.println(failure.toString());
      }
      System.out.println(result.wasSuccessful());
   }
}

Add TokenizerTest to the list of tests to run


package uk.gov.dvla.services.enquiry;

import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;

public interface DriverEnquiry extends ManagedService
{
    public static final String DRIVER_URI = "/driver/";
    public static final String CUSTOMER_PORTAL = "customer_portal";
    public static final String MIB = "mib";

    public static final String DLN_PARAM = "dln";
    public static final String ENQUIRY_ID_PARAM = "id";

    public static final String FORENAME_PARAM = "fn";
    public static final String SURNAME_PARAM = "sn";
    public static final String DOB_PARAM = "d";
    public static final String GENDER_PARAM = "g";
    public static final String POSTCODE_PARAM = "p";

	public Driver get(String dln);

	public Driver get(Person person);

    public Driver get(String forename, String surname, String dob,
                      String gender, String postCode);
}

package uk.gov.dvla.services.enquiry;

import uk.gov.dvla.domain.Driver;
import uk.gov.dvla.domain.Person;
import uk.gov.dvla.services.ManagedService;

public interface DriverEnquiry extends ManagedService
{
    public static final String DRIVER_URI = "/driver/";
    public static final String CUSTOMER_PORTAL = "customer.portal";
    public static final String MIB = "mib";

    public static final String DLN_PARAM = "dln";
    public static final String ENQUIRY_ID_PARAM = "id";

    public static final String FORENAME_PARAM = "fn";
    public static final String SURNAME_PARAM = "sn";
    public static final String DOB_PARAM = "d";
    public static final String GENDER_PARAM = "g";
    public static final String POSTCODE_PARAM = "p";

	public Driver get(String dln);

	public Driver get(Person person);

    public Driver get(String forename, String surname, String dob,
                      String gender, String postCode);
}

Determine the rules that are run matching the context passed into the rules with the package name. Include some more tests. Remove redundant logging classes.


package org.opencb.opencga.server;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by pfurio on 04/10/16.
 */
public class CORSFilter implements Filter {

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

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println("Request " + request.getMethod());

        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.addHeader("Access-Control-Allow-Origin","*");
        resp.addHeader("Access-Control-Allow-Methods","GET,POST");
        resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Range");

        // Just ACCEPT and REPLY OK if OPTIONS
        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy() {}

}

package org.opencb.opencga.server;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by pfurio on 04/10/16.
 */
public class CORSFilter implements Filter {

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

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println("Request " + request.getMethod());

        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        resp.addHeader("Access-Control-Allow-Origin","*");
        resp.addHeader("Access-Control-Allow-Methods","GET,POST");
        resp.addHeader("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept, Range, Authorization");

        // Just ACCEPT and REPLY OK if OPTIONS
        if (request.getMethod().equals("OPTIONS")) {
            resp.setStatus(HttpServletResponse.SC_OK);
            return;
        }
        chain.doFilter(request, servletResponse);
    }

    @Override
    public void destroy() {}

}

server: Add Authorization to Access-Control-Allow-Headers list.


package game_objects.interactions;

/**
 * Created by mtvarkovsky on 12/10/16.
 */
public interface IHide {
}

package com.seven.game.game_objects.interactions;

public interface IHide {
    Boolean possibleToHide();
}

Add interface for GameObjects to be able to hide


package alien4cloud.plugin.marathon.config;

import alien4cloud.ui.form.annotation.FormProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author Adrian Fraisse
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@FormProperties({ "marathonURL", "mesosDNS" })
public class MarathonConfig {

    private String marathonURL;

    private String mesosDNS;
}

package alien4cloud.plugin.marathon.config;

import alien4cloud.ui.form.annotation.FormProperties;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

/**
 * @author Adrian Fraisse
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@FormProperties({ "marathonURL" })
public class MarathonConfig {

    private String marathonURL;
}

Remove mesosDNS url from configuration

Remove mesosDNS url from configuration


package com.sangdol.experiment.portableDb;

import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.h2.jdbcx.JdbcConnectionPool;

/**
 * @author hugh
 */
public class ViewApplication extends Application<ViewConfiguration>{
    public static void main(String[] args) throws Exception{
        new ViewApplication().run(args);
    }

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

    @Override
    public void initialize(Bootstrap<ViewConfiguration> bootstrap) {}

    @Override
    public void run(ViewConfiguration configuration, Environment environment) throws ClassNotFoundException {
        final ViewTable viewTable = new ViewTable();
        final ViewSimpleQuery viewSimpleQuery = new ViewSimpleQuery(viewTable);
        final ViewBatchQuery viewBatchQuery = new ViewBatchQuery(viewTable);
        final JdbcConnectionPool cp = JdbcConnectionPool.create("jdbc:h2:./view", "sa", ""); // TODO move to config
        final ViewDao viewDao = new ViewDao(cp, viewSimpleQuery, viewBatchQuery);
        final ViewResource resource = new ViewResource(viewDao);

        environment.healthChecks().register("database", new DatabaseHealthCheck(cp));
        environment.jersey().register(resource);
    }
}

package com.sangdol.experiment.portableDb;

import io.dropwizard.Application;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import org.h2.jdbcx.JdbcConnectionPool;

/**
 * @author hugh
 */
public class ViewApplication extends Application<ViewConfiguration>{
    public static void main(String[] args) throws Exception{
        new ViewApplication().run(args);
    }

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

    @Override
    public void initialize(Bootstrap<ViewConfiguration> bootstrap) {}

    @Override
    public void run(ViewConfiguration configuration, Environment environment) throws ClassNotFoundException {
        final ViewTable viewTable = new ViewTable();
        final ViewSimpleQuery viewSimpleQuery = new ViewSimpleQuery(viewTable);
        final ViewBatchQuery viewBatchQuery = new ViewBatchQuery(viewTable);

        // AUTO_SERVER=TRUE enables Automatic Mixed Mode which allows access of multiple processes.
        // Refer to http://h2database.com/html/features.html#auto_mixed_mode
        final JdbcConnectionPool cp = JdbcConnectionPool.create("jdbc:h2:./view;AUTO_SERVER=TRUE", "sa", "");
        final ViewDao viewDao = new ViewDao(cp, viewSimpleQuery, viewBatchQuery);
        final ViewResource resource = new ViewResource(viewDao);

        environment.healthChecks().register("database", new DatabaseHealthCheck(cp));
        environment.jersey().register(resource);
    }
}

Add AUTO_SERVER=TRUE for multiple processes access to the same db file