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

import java.util.function.Supplier;

/**
 * The IdentifierService provides a mechanism for creating new identifiers.
 *
 * @author acoburn
 */
public interface IdentifierService {

    /**
     * Get a Supplier that generates Strings with the provided prefix
     * @param prefix the prefix
     * @return a String Supplier
     */
    Supplier<String> getSupplier(String prefix);

    /**
     * Get a Supplier that generates Strings with the provided prefix
     * @return a String Supplier
     */
    Supplier<String> getSupplier();
}

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

import java.util.function.Supplier;

/**
 * The IdentifierService provides a mechanism for creating new identifiers.
 *
 * @author acoburn
 */
public interface IdentifierService {

    /**
     * Get a Supplier that generates Strings with the provided prefix
     * @param prefix the prefix
     * @param hierarchy the levels of hierarchy to add
     * @param length the length of each level of hierarchy
     * @return a String Supplier
     */
    Supplier<String> getSupplier(String prefix, Integer hierarchy, Integer length);

    /**
     * Get a Supplier that generates Strings with the provided prefix
     * @param prefix the prefix
     * @return a String Supplier
     */
    Supplier<String> getSupplier(String prefix);

    /**
     * Get a Supplier that generates Strings with the provided prefix
     * @return a String Supplier
     */
    Supplier<String> getSupplier();
}

Add method to ID Generator


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.synyx.urlaubsverwaltung.core.application.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.synyx.urlaubsverwaltung.core.application.dao.ApplicationCommentDAO;
import org.synyx.urlaubsverwaltung.core.application.domain.Application;
import org.synyx.urlaubsverwaltung.core.application.domain.ApplicationAction;
import org.synyx.urlaubsverwaltung.core.application.domain.ApplicationComment;
import org.synyx.urlaubsverwaltung.core.person.Person;

import java.util.List;
import java.util.Optional;

/**
 * Implementation of interface {@link ApplicationCommentService}.
 */
@Service
@Transactional
class ApplicationCommentServiceImpl implements ApplicationCommentService {

    private final ApplicationCommentDAO commentDAO;

    @Autowired
    ApplicationCommentServiceImpl(ApplicationCommentDAO commentDAO) {

        this.commentDAO = commentDAO;
    }

    @Override
    public ApplicationComment create(Application application, ApplicationAction action, Optional<String> text,
        Person author) {

        ApplicationComment comment = new ApplicationComment(author);

        comment.setAction(action);
        comment.setApplication(application);

        text.ifPresent(comment::setText);

        commentDAO.save(comment);

        return comment;
    }

    @Override
    public List<ApplicationComment> getCommentsByApplication(Application application) {

        return commentDAO.getCommentsByApplication(application);
    }
}

Remove editor template for class


package org.pdxfinder.services.constants;

import org.junit.Test;
import org.pdxfinder.BaseTest;

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

public class DataUrlTest extends BaseTest {

    private final static String ASSERTION_ERROR = "Unknown Data Url Found: ";

    @Test
    public void given_DataUrlEnumListCount_EnsureListIntegrity() {

        final int DATA_URL_COUNT = 8;

        assertEquals(DATA_URL_COUNT, DataUrl.values().length);
    }

    @Test
    public void given_DataUrl_When_EnumListIsChanged_Then_Error() {

        boolean expected = true;
        String message = "";

        for (DataUrl option : DataUrl.values()) {

            switch (option) {
                case HUGO_FILE_URL:
                    break;
                case DISEASES_BRANCH_URL:
                    break;
                case ONTOLOGY_URL:
                    break;
                default:
                    message = String.format("%s %s", ASSERTION_ERROR, option);
                    expected = false;
            }

            assertTrue(message, expected);
        }

    }
}

package org.pdxfinder.services.constants;

import org.junit.Test;
import org.pdxfinder.BaseTest;

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

public class DataUrlTest extends BaseTest {

    private final static String ASSERTION_ERROR = "Unknown Data Url Found: ";

    @Test
    public void given_DataUrlEnumListCount_EnsureListIntegrity() {

        final int DATA_URL_COUNT = 3;

        assertEquals(DATA_URL_COUNT, DataUrl.values().length);
    }

    @Test
    public void given_DataUrl_When_EnumListIsChanged_Then_Error() {

        boolean expected = true;
        String message = "";

        for (DataUrl option : DataUrl.values()) {

            switch (option) {
                case HUGO_FILE_URL:
                    break;
                case DISEASES_BRANCH_URL:
                    break;
                case ONTOLOGY_URL:
                    break;
                default:
                    message = String.format("%s %s", ASSERTION_ERROR, option);
                    expected = false;
            }

            assertTrue(message, expected);
        }

    }
}

Add more unit test cases


package pl.aetas.bakspad.presentation;

import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;

public class LocaleAwareStringComparator implements Comparator<String> {

    private final Collator localeCollator;

    public LocaleAwareStringComparator(Locale locale) {
        localeCollator = Collator.getInstance(locale);
    }

    @Override
    public int compare(String o1, String o2) {
        return localeCollator.compare(o1, o2);
    }
}

package pl.aetas.bakspad.presentation;

import java.text.Collator;
import java.util.Comparator;
import java.util.Locale;

public class LocaleAwareStringComparator implements Comparator<String> {

    private final Collator localeCollator;

    public LocaleAwareStringComparator(Locale locale) {
        localeCollator = Collator.getInstance(locale);
    }

    @Override
    public int compare(String o1, String o2) {
        if (o1.isEmpty()) {
            return 1;
        }
        if (o2.isEmpty()) {
            return -1;
        }
        return localeCollator.compare(o1, o2);
    }
}

Change for table columns comparator to put empty string at the end


package org.bouncycastle.crypto.util;

public abstract class Pack
{
    public static int bigEndianToInt(byte[] bs, int off)
    {
        int n = bs[off++] << 24;
        n |= (bs[off++] & 0xff) << 16;
        n |= (bs[off++] & 0xff) << 8;
        n |= (bs[off++] & 0xff);
        return n;
    }

    public static void intToBigEndian(int n, byte[] bs, int off)
    {
        bs[off++] = (byte)(n >>> 24);
        bs[off++] = (byte)(n >>> 16);
        bs[off++] = (byte)(n >>>  8);
        bs[off  ] = (byte)(n       );
    }
}

package org.bouncycastle.crypto.util;

public abstract class Pack
{
    public static int bigEndianToInt(byte[] bs, int off)
    {
        int n = bs[  off] << 24;
        n |= (bs[++off] & 0xff) << 16;
        n |= (bs[++off] & 0xff) << 8;
        n |= (bs[++off] & 0xff);
        return n;
    }

    public static void intToBigEndian(int n, byte[] bs, int off)
    {
        bs[  off] = (byte)(n >>> 24);
        bs[++off] = (byte)(n >>> 16);
        bs[++off] = (byte)(n >>>  8);
        bs[++off] = (byte)(n       );
    }

    public static long bigEndianToLong(byte[] bs, int off)
    {
        int hi = bigEndianToInt(bs, off);
        int lo = bigEndianToInt(bs, off + 4);
        return ((long)(hi & 0xffffffffL) << 32) | (long)(lo & 0xffffffffL);
    }

    public static void longToBigEndian(long n, byte[] bs, int off)
    {
        intToBigEndian((int)(n >>> 32), bs, off);
        intToBigEndian((int)(n & 0xffffffffL), bs, off + 4);
    }
}

Improve existing methods, add new ones for packing longs


package edu.umd.cs.piccolox.swt;

import junit.framework.TestCase;

public class PSWTTextTest extends TestCase {
    private PSWTText testNode;

    public void setUp() {
        testNode = new PSWTText();
    }

    public void testTextPersistsTrainingAndInternalNewlines() {
        testNode.setText("Hello\nWorld\n\n");
        assertEquals("Hello\nWorld\n\n", testNode.getText());
    }

}

package edu.umd.cs.piccolox.swt;

import junit.framework.TestCase;

public class PSWTTextTest extends TestCase {
    private PSWTText testNode;

    public void setUp() {
        testNode = new PSWTText();
    }

    public void testTextPersistsTrainingAndInternalNewlines() {
        // TODO: Make this work in headless mode if possible.
        // testNode.setText("Hello\nWorld\n\n");
        // assertEquals("Hello\nWorld\n\n", testNode.getText());
    }

}

Test added doesn't work in headless. Will need to figure something out. Otherwise SWT module will remain untestable.


/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.xpack.ml.job.process.autodetect.writer;

import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.xpack.ml.job.process.autodetect.state.DataCounts;

import java.io.IOException;
import java.io.InputStream;
import java.util.function.BiConsumer;

/**
 * Interface defining writers to a {@link org.elasticsearch.xpack.ml.job.process.autodetect.AutodetectProcess}
 */
public interface DataToProcessWriter {

    /**
     * Write the header.
     * The header is created from the list of analysis input fields,
     * the time field and the control field.
     */
    void writeHeader() throws IOException;

    /**
     * Write the contents of inputStream.
     * If any of the fields in analysisFields or the
     * DataDescriptions timeField is missing from the CSV header
     * a MissingFieldException is thrown
     */
    void write(InputStream inputStream, XContentType xContentType, BiConsumer<DataCounts, Exception> handler) throws IOException;

    /**
     * Flush the outputstream
     */
    void flushStream() throws IOException;
}

/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.xpack.ml.job.process.autodetect.writer;

import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.xpack.ml.job.process.autodetect.state.DataCounts;

import java.io.IOException;
import java.io.InputStream;
import java.util.function.BiConsumer;

/**
 * Interface defining writers to a
 * {@link org.elasticsearch.xpack.ml.job.process.autodetect.AutodetectProcess}
 */
public interface DataToProcessWriter {

    /**
     * Write the header.
     * The header is created from the list of analysis input fields,
     * the time field and the control field.
     */
    void writeHeader() throws IOException;

    /**
     * Write the contents of inputStream.
     * If any of the fields in analysisFields or the
     * DataDescriptions timeField is missing from the CSV header
     * a MissingFieldException is thrown
     */
    void write(InputStream inputStream, XContentType xContentType,
               BiConsumer<DataCounts, Exception> handler) throws IOException;

    /**
     * Flush the outputstream
     */
    void flushStream() throws IOException;
}

Fix check style line length failure


package uk.ac.ebi.quickgo.rest.search;

/**
 * Enumerates the aggregation functions supported by the domain.
 *
 * @author Ricardo Antunes
 */
public enum AggregateFunction {
    COUNT("count"),
    UNIQUE("unique");

    private String name;

    AggregateFunction(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public static AggregateFunction typeOf(String functionText) {
        for(AggregateFunction function : AggregateFunction.values()) {
            if(function.getName().equals(functionText)) {
                return function;
            }
        }

        throw new IllegalArgumentException("Unable to find aggregation function for: " + functionText);
    }
}

package uk.ac.ebi.quickgo.rest.search;

/**
 * Enumerates the aggregation functions supported by the domain.
 *
 * @author Ricardo Antunes
 */
public enum AggregateFunction {
    COUNT("count"),
    UNIQUE("unique"),
    SUM("sum");

    private String name;

    AggregateFunction(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public static AggregateFunction typeOf(String functionText) {
        for(AggregateFunction function : AggregateFunction.values()) {
            if(function.getName().equals(functionText)) {
                return function;
            }
        }

        throw new IllegalArgumentException("Unable to find aggregation function for: " + functionText);
    }
}

Add sum aggregation as a supported function in QuickGO.


package org.osiam.client.query;
/*
 * for licensing see the file license.txt.
 */

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.osiam.resources.scim.CoreResource;

import java.util.Collections;
import java.util.Set;

@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
public class QueryResult<T extends CoreResource> {

    private int totalResults;
    private int itemsPerPage;
    private int startIndex;
    private String schemas;
    @JsonProperty("Resources")
    private Set<T> resources;

    public int getTotalResults() {
        return totalResults;
    }

    public int getItemsPerPage() {
        return itemsPerPage;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public String getSchemas() {
        return schemas;
    }

    public Set<T> getResources() {
        return Collections.unmodifiableSet(resources);
    }
}

package org.osiam.client.query;
/*
 * for licensing see the file license.txt.
 */

import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.osiam.resources.scim.CoreResource;

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

@JsonSerialize(include = JsonSerialize.Inclusion.NON_EMPTY)
public class QueryResult<T extends CoreResource> {

    private int totalResults;
    private int itemsPerPage;
    private int startIndex;
    private String schemas;
    @JsonProperty("Resources")
    private List<T> resources;

    public int getTotalResults() {
        return totalResults;
    }

    public int getItemsPerPage() {
        return itemsPerPage;
    }

    public int getStartIndex() {
        return startIndex;
    }

    public String getSchemas() {
        return schemas;
    }

    public List<T> getResources() {
        return Collections.unmodifiableList(resources);
    }
}

Use List instead of Set to make sure that the returned order is preserved


package org.springframework.data.rest.shell.formatter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

public class XmlFormatter extends FormatterSupport {
  private final List<String> supportedContentTypes = Arrays.asList("xml");

  @Override
  public Collection<String> getSupportedList() {
    return supportedContentTypes;
  }

  @Override
  public String format(String nonFormattedString) {
    try {
      Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(nonFormattedString.getBytes())));
      StreamResult res = new StreamResult(new ByteArrayOutputStream());

      serializer.transform(xmlSource, res);

      return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray());
    } catch (Exception e) {
      return nonFormattedString;
    }
  }
}

package org.springframework.data.rest.shell.formatter;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;

public class XmlFormatter extends FormatterSupport {
  private final List<String> supportedContentTypes = Arrays.asList("xml");

  @Override
  public Collection<String> getSupportedList() {
    return supportedContentTypes;
  }

  @Override
  public String format(String nonFormattedString) {
    try {
      Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();
      serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "true");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(nonFormattedString.getBytes())));
      StreamResult res = new StreamResult(new ByteArrayOutputStream());

      serializer.transform(xmlSource, res);

      return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray());
    } catch (Exception e) {
      return nonFormattedString;
    }
  }
}

Remove xml declaration which is added while formatting the content.


package com.vrachieru.cnp4j;

public class CnpUtil {

    public static final int CNP_LENGTH = 13;

    public static final int[] WEIGHTS = new int[]{2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9};

    public static int calculateCheckDigit(String cnp) {
        int sum = calculateSum(cnp);
        int checkDigit = sum % 11;
        return (checkDigit == 10) ? 1 : checkDigit;
    }

    public static int calculateSum(String cnp) {
        int sum = 0;
        for (int i = 0; i < CNP_LENGTH - 1; i++) {
            sum += Integer.valueOf(cnp.charAt(i)) * WEIGHTS[i];
        }
        return sum;
    }
}

package com.vrachieru.cnp4j;

import static java.lang.Character.getNumericValue;

public class CnpUtil {

    public static final int CNP_LENGTH = 13;

    public static final int[] WEIGHTS = new int[]{2, 7, 9, 1, 4, 6, 3, 5, 8, 2, 7, 9};

    public static int calculateCheckDigit(String cnp) {
        int sum = calculateSum(cnp);
        int checkDigit = sum % 11;
        return (checkDigit == 10) ? 1 : checkDigit;
    }

    public static int calculateSum(String cnp) {
        int sum = 0;
        for (int i = 0; i < CNP_LENGTH - 1; i++) {
            sum += getNumericValue(cnp.charAt(i)) * WEIGHTS[i];
        }
        return sum;
    }
}

Fix char to int convesion


package lib.morkim.mfw.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceFragment;

import lib.morkim.mfw.app.MorkimApp;

@SuppressLint("NewApi")
public abstract class MPreferenceFragment extends PreferenceFragment implements Viewable {

	private static final String TAG_CONTROLLER_FRAGMENT = "fragment.controller.fragment.tag";

	protected Navigation navigation;

	protected Controller controller;
	private Presenter presenter;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		MorkimApp morkimApp = (MorkimApp) activity.getApplication();

		navigation = morkimApp.acquireNavigation();

		controller = morkimApp.acquireController(this);
		presenter = morkimApp.acquirePresenter(this);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	protected abstract Controller createController();
}

package lib.morkim.mfw.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.preference.PreferenceFragment;

import lib.morkim.mfw.app.AppContext;
import lib.morkim.mfw.app.MorkimApp;

@SuppressLint("NewApi")
public abstract class MPreferenceFragment extends PreferenceFragment implements Viewable {

	private static final String TAG_CONTROLLER_FRAGMENT = "fragment.controller.fragment.tag";

	protected Navigation navigation;

	protected Controller controller;
	private Presenter presenter;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		MorkimApp morkimApp = (MorkimApp) activity.getApplication();

		navigation = morkimApp.acquireNavigation();

		controller = morkimApp.acquireController(this);
		presenter = morkimApp.acquirePresenter(this);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	protected abstract Controller createController();

	@Override
	public AppContext getMorkimContext() {
		return ((Screen) getActivity()).getMorkimContext();
	}

	@Override
	public void keepScreenOn(boolean keepOn) {
		((Screen) getActivity()).keepScreenOn(keepOn);
	}
}

Remove view model in presenter


package net.sf.jabref;

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

import java.util.Arrays;

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

public class JabRefCLITest {

    @Test
    public void testCLIParsingLongOptions() {
        JabRefCLI cli = new JabRefCLI(new String[] {"--nogui", "--import=some/file", "--output=some/export/file"});

        Assert.assertEquals("[]", Arrays.toString(cli.getLeftOver()));
        Assert.assertEquals("some/file", cli.getFileImport());
        Assert.assertTrue(cli.isDisableGui());
        Assert.assertEquals("some/export/file", cli.getFileExport());
    }

    @Test
    public void testCLIParsingShortOptions() {
        JabRefCLI cli = new JabRefCLI(new String[] {"-n", "-i=some/file", "-o=some/export/file"});

        Assert.assertEquals("[]", Arrays.toString(cli.getLeftOver()));
        Assert.assertEquals("some/file", cli.getFileImport());
        Assert.assertTrue(cli.isDisableGui());
        Assert.assertEquals("some/export/file", cli.getFileExport());
    }

}

package net.sf.jabref;

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

import java.util.Arrays;

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

public class JabRefCLITest {

    @Test
    public void testCLIParsingLongOptions() {
        JabRefCLI cli = new JabRefCLI(new String[] {"--nogui", "--import=some/file", "--output=some/export/file"});

        Assert.assertEquals("[]", Arrays.toString(cli.getLeftOver()));
        Assert.assertEquals("some/file", cli.getFileImport());
        Assert.assertTrue(cli.isDisableGui());
        Assert.assertEquals("some/export/file", cli.getFileExport());
    }

    @Test
    public void testCLIParsingShortOptions() {
        JabRefCLI cli = new JabRefCLI(new String[] {"-n", "-i=some/file", "-o=some/export/file"});

        Assert.assertEquals("[]", Arrays.toString(cli.getLeftOver()));
        Assert.assertEquals("some/file", cli.getFileImport());
        Assert.assertTrue(cli.isDisableGui());
        Assert.assertEquals("some/export/file", cli.getFileExport());
    }

    @Test
    public void testPreferencesExport() {
        JabRefCLI cli = new JabRefCLI(new String[] {"-n", "-x=some/file"});

        Assert.assertEquals("[]", Arrays.toString(cli.getLeftOver()));
        Assert.assertEquals("some/file", cli.getPreferencesExport());
        Assert.assertTrue(cli.isDisableGui());
    }

}

Add test for export command line option


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

import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment;
import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: nshurupova
 * Date: Aug 29, 2007
 * Time: 3:41:38 PM
 * To change this template use File | Settings | File Templates.
 */
public class AmendmentDao  extends StudyCalendarDao<Amendment> {
        private static final Logger log = LoggerFactory.getLogger(AmendmentDao.class.getName());

    public Class<Amendment> domainClass() {
        return Amendment.class;
    }

    public List<Amendment> getAll() {
        return getHibernateTemplate().find("from Amendment");
    }

    @Transactional(readOnly = false)
    public void save(Amendment amendment) {
        getHibernateTemplate().saveOrUpdate(amendment);
    }

    public List<Amendment> getByName (String name) {
        return getHibernateTemplate().find("from Amendment a where a.name= ?", name);
    }

    public List<Amendment> getByDate(String date) {
        return getHibernateTemplate().find("from Amendment a where a.date= ?", date);
    }

    public Amendment getByPreviousAmendmentId(Integer previousAmendmentId) {
        List<Amendment> results = getHibernateTemplate().find("from Amendment a where a.previousAmendment= ?", previousAmendmentId);
        return results.get(0);
    }

    public Amendment getByStudyId(Integer studyId) {
        List<Amendment> results = getHibernateTemplate().find("from Amendment a where a.studyId= ?", studyId);
        return results.get(0);
    }
}

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

import edu.northwestern.bioinformatics.studycalendar.dao.StudyCalendarDao;
import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Nataliya Shurupova
 */
public class AmendmentDao  extends StudyCalendarDao<Amendment> {
    @Override
    public Class<Amendment> domainClass() {
        return Amendment.class;
    }

    public List<Amendment> getAll() {
        return getHibernateTemplate().find("from Amendment");
    }

    @Transactional(readOnly = false)
    public void save(Amendment amendment) {
        getHibernateTemplate().saveOrUpdate(amendment);
    }

    @Deprecated
    public Amendment getByStudyId(Integer studyId) {
        throw new UnsupportedOperationException("Deprecated");
    }
}

Remove unused/untested methods; deprecate & de-support getStudyById because that field's about to disappear


/*
 * Copyright (c) 2015-2017 Dzikoysk
 *
 * 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.panda_lang.panda.implementation.interpreter.parser.pipeline;

/**
 * Used by {@link org.panda_lang.panda.implementation.interpreter.parser.pipeline.registry.ParserRegistration}
 */
public class DefaultPipelines {

    /**
     * Used by {@link org.panda_lang.panda.implementation.interpreter.parser.defaults.OverallParser}
     */
    public static final String OVERALL = "overall";

    /**
     * Used by {@link org.panda_lang.panda.language.structure.prototype.parser.ClassPrototypeParser}
     */
    public static final String PROTOTYPE = "prototype";

    /**
     * Used by {@link org.panda_lang.panda.implementation.interpreter.parser.defaults.ScopeParser}
     */
    public static final String SCOPE = "scope";

}

/*
 * Copyright (c) 2015-2017 Dzikoysk
 *
 * 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.panda_lang.panda.implementation.interpreter.parser.pipeline;

/**
 * Used by {@link org.panda_lang.panda.implementation.interpreter.parser.pipeline.registry.ParserRegistration}
 */
public class DefaultPipelines {

    /**
     * Used by {@link org.panda_lang.panda.implementation.interpreter.parser.defaults.OverallParser}
     */
    public static final String OVERALL = "overall";

    /**
     * Used by {@link org.panda_lang.panda.language.structure.prototype.parser.ClassPrototypeParser}
     */
    public static final String PROTOTYPE = "prototype";

    /**
     * Used by {@link org.panda_lang.panda.implementation.interpreter.parser.defaults.ScopeParser}
     */
    public static final String SCOPE = "scope";

    /**
     * Used by {@link org.panda_lang.panda.language.structure.block.BlockParser}
     */
    public static final String BLOCK = "block";

}

Add BLOCK pipeline definition to the default pipelines


package sg.ncl;

import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.validation.constraints.NotNull;

/**
 * @author by Te Ye
 * @updated by James, 27-Dec-2017
 *
 * References:
 * [1] https://www.mkyong.com/spring/spring-and-java-thread-example/
 */
@Configuration("sg.ncl.AppConfig")
public class AppConfig {

    @Bean
    public AppErrorController appErrorController(@NotNull ErrorAttributes errorAttributes) {
        return new AppErrorController(errorAttributes);
    }

    // thymleaf-layout-dialect
    // for fragments
    @Bean
    public LayoutDialect layoutDialect() {
        return new LayoutDialect();
    }

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setCorePoolSize(5);
        pool.setMaxPoolSize(10);
        pool.setWaitForTasksToCompleteOnShutdown(true);
        return pool;
    }
}

package sg.ncl;

import nz.net.ultraq.thymeleaf.LayoutDialect;
import org.springframework.boot.autoconfigure.web.ErrorAttributes;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.validation.constraints.NotNull;

/**
 * @author by Te Ye
 * @updated by James, 27-Dec-2017
 *
 * References:
 * [1] https://www.mkyong.com/spring/spring-and-java-thread-example/
 */
@Configuration("sg.ncl.AppConfig")
public class AppConfig {

    @Bean
    public AppErrorController appErrorController(@NotNull ErrorAttributes errorAttributes) {
        return new AppErrorController(errorAttributes);
    }

    // thymleaf-layout-dialect
    // for fragments
    @Bean
    public LayoutDialect layoutDialect() {
        return new LayoutDialect();
    }

    @Bean
    public ThreadPoolTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor();
        pool.setCorePoolSize(10);
        pool.setMaxPoolSize(100);
        pool.setWaitForTasksToCompleteOnShutdown(true);
        return pool;
    }
}

Increase Core and Maximum ThreadPool Size


package org.goplayer.util;

public class Coord {
	private final int row;
	private final int col;

	public Coord(int row, int col) {
		this.row = row;
		this.col = col;
	}

	public int getRow() {
		return row;
	}

	public int getCol() {
		return col;
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		} else if (obj instanceof Coord) {
			Coord c = (Coord) obj;
			return row == c.row && col == c.col;
		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		return (int) (row * 3881 + col * 3967);
	}
}

package org.goplayer.util;

public class Coord {
	private final int row;
	private final int col;

	public Coord(int row, int col) {
		this.row = row;
		this.col = col;
	}

	public int getRow() {
		return row;
	}

	public int getCol() {
		return col;
	}

	@Override
	public String toString() {
		return "(" + row + ", " + col + ")";
	}

	@Override
	public boolean equals(Object obj) {
		if (obj == this) {
			return true;
		} else if (obj instanceof Coord) {
			Coord c = (Coord) obj;
			return row == c.row && col == c.col;
		} else {
			return false;
		}
	}

	@Override
	public int hashCode() {
		return (int) (row * 3881 + col * 3967);
	}
}

Add a string representation for the coords.


package com.codingchili.core.storage;

import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Robin Duda
 *

 *         parses a query in string format.
 *

 *         Implementation is pluggable.
 */
public class QueryParser<T extends Storable> implements StringQueryParser<T> {
    private AsyncStorage<T> store;

    public QueryParser(AsyncStorage<T> store) {
        this.store = store;
    }

    @Override
    public Handler<AsyncResult<Collection<T>>> parse(String expression) {
        throw new NotImplementedException();
    }

    private static String name(String expression) {
        Pattern pattern = Pattern.compile("([a-zA-Z ])+(?::)");
        Matcher matcher = pattern.matcher(expression);
        matcher.group();
        if (matcher.groupCount() > 0) {
            return matcher.group(0);
        } else {
            return QueryParser.class.getSimpleName();
        }
    }
}

package com.codingchili.core.storage;

import io.vertx.core.AsyncResult;
import io.vertx.core.Handler;

import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Robin Duda
 *

 *         parses a query in string format.
 *

 *         Implementation is pluggable.
 */
public class QueryParser<T extends Storable> implements StringQueryParser<T> {
    private AsyncStorage<T> store;

    public QueryParser(AsyncStorage<T> store) {
        this.store = store;
    }

    @Override
    public Handler<AsyncResult<Collection<T>>> parse(String expression) {
        throw new RuntimeException("NOT IMPLEMENTED");
    }

    private static String name(String expression) {
        Pattern pattern = Pattern.compile("([a-zA-Z ])+(?::)");
        Matcher matcher = pattern.matcher(expression);
        matcher.group();
        if (matcher.groupCount() > 0) {
            return matcher.group(0);
        } else {
            return QueryParser.class.getSimpleName();
        }
    }
}

Remove bad import of sun.NotImplementedException


package in.twizmwaz.cardinal.module.modules.regions.type;

import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.module.modules.regions.parsers.PointParser;
import org.bukkit.block.Block;
import org.bukkit.util.BlockVector;
import org.bukkit.util.Vector;

public class PointRegion extends BlockRegion {

    private final Vector look;

    public PointRegion(String name, Vector vector, Vector look) {
        super(name, vector);
        this.look = look;
    }

    public PointRegion(String name, double x, double y, double z) {
        super(name, x, y, z);
        this.look = new BlockVector();
    }

    public PointRegion(PointParser parser) {
        this(parser.getName(), parser.getVector(), parser.getLook());
    }

    public PointRegion(String name, Vector vector) {
        this(name, vector, new BlockVector());
    }

    @Override
    public Vector getVector() {
        return vector.clone();
    }

    public float getYaw() {
        return vector.toLocation(null).getYaw();
    }

    public float getPitch() {
        return vector.toLocation(null).getPitch();
    }

    public Block getBlock() {
        return vector.toLocation(GameHandler.getGameHandler().getMatchWorld()).getBlock();
    }

    public Vector getLook() {
        return look;
    }
}

package in.twizmwaz.cardinal.module.modules.regions.type;

import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.module.modules.regions.parsers.PointParser;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.util.BlockVector;
import org.bukkit.util.Vector;

public class PointRegion extends BlockRegion {

    private final Vector look;

    public PointRegion(String name, Vector vector, Vector look) {
        super(name, vector);
        this.look = look;
    }

    public PointRegion(String name, double x, double y, double z) {
        super(name, x, y, z);
        this.look = new BlockVector();
    }

    public PointRegion(PointParser parser) {
        this(parser.getName(), parser.getVector(), parser.getLook());
    }

    public PointRegion(String name, Vector vector) {
        this(name, vector, new BlockVector());
    }

    @Override
    public Vector getVector() {
        return vector.clone();
    }

    @Override
    public PointRegion getRandomPoint() {
        return this;
    }

    @Override
    public Location getLocation() {
        return new Location(GameHandler.getGameHandler().getMatchWorld(), getX(), getY(), getZ(), getYaw(), getPitch());
    }

    public float getYaw() {
        return vector.toLocation(null).getYaw();
    }

    public float getPitch() {
        return vector.toLocation(null).getPitch();
    }

    public Block getBlock() {
        return vector.toLocation(GameHandler.getGameHandler().getMatchWorld()).getBlock();
    }

    public Vector getLook() {
        return look;
    }
}

Improve handling of point regions


package org.metaborg.spoofax.eclipse.meta.ant;

import java.io.PrintStream;

import org.apache.tools.ant.DefaultLogger;
import org.eclipse.ui.console.MessageConsole;
import org.metaborg.spoofax.eclipse.util.ConsoleUtils;

public class EclipseAntLogger extends DefaultLogger {
    private final MessageConsole console;
    private final PrintStream stream;

    public EclipseAntLogger() {
        super();
        console = ConsoleUtils.get("Spoofax language build");
        stream = new PrintStream(console.newMessageStream());
        console.activate();
    }

    @Override protected void printMessage(String message, PrintStream unusedStream, int priority) {
        /*
         * HACK: instead of setting the output and error streams, just pass our own stream to printMessage. The reason
         * being that Ant likes to change the stream to stdout and stderr after class instantiation, overriding our
         * streams.
         */
        super.printMessage(message, stream, priority);
    }
}

package org.metaborg.spoofax.eclipse.meta.ant;

import java.io.PrintStream;

import org.apache.tools.ant.DefaultLogger;
import org.eclipse.ui.console.MessageConsole;
import org.metaborg.spoofax.eclipse.util.ConsoleUtils;

public class EclipseAntLogger extends DefaultLogger {
    private final MessageConsole console;
    private final PrintStream stream;

    public EclipseAntLogger() {
        super();
        console = ConsoleUtils.get("Spoofax console");
        stream = new PrintStream(console.newMessageStream());
    }

    @Override protected void printMessage(String message, PrintStream unusedStream, int priority) {
        /*
         * HACK: instead of setting the output and error streams, just pass our own stream to printMessage. The reason
         * being that Ant likes to change the stream to stdout and stderr after class instantiation, overriding our
         * streams.
         */
        super.printMessage(message, stream, priority);
    }
}

Use existing console for Ant build log


/*
 * Copyright 2018, EnMasse authors.
 * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
 */
package io.enmasse.k8s.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogEventLogger implements EventLogger {
    private static final Logger log = LoggerFactory.getLogger(LogEventLogger.class);

    @Override
    public void log(Reason reason, String message, Type type, ObjectKind objectKind, String objectName) {
        log(log, reason, message, type, objectKind, objectName);
    }

    public static void log(Logger logger, Reason reason, String message, Type type, ObjectKind objectKind, String objectName) {
        String line = String.format("%s (%s): %s %s", objectName, objectKind.name(), reason.name(), message);
        switch (type) {
            case Warning:
                logger.warn(line);
                break;
            case Normal:
                logger.info(line);
                break;
        }
    }
}

/*
 * Copyright 2018, EnMasse authors.
 * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
 */
package io.enmasse.k8s.api;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogEventLogger implements EventLogger {
    private static final Logger log = LoggerFactory.getLogger(LogEventLogger.class);

    @Override
    public void log(Reason reason, String message, Type type, ObjectKind objectKind, String objectName) {
        log(log, reason, message, type, objectKind, objectName);
    }

    public static void log(Logger logger, Reason reason, String message, Type type, ObjectKind objectKind, String objectName) {
        String line = String.format("%s (kind=%s name=%s): %s", reason.name(), objectKind.name(), objectName, message);
        switch (type) {
            case Warning:
                logger.warn(line);
                break;
            case Normal:
                logger.info(line);
                break;
        }
    }
}

Make log event format more readable


package org.csveed.bean;

import org.csveed.bean.conversion.Converter;
import org.csveed.test.converters.BeanSimpleConverter;
import org.csveed.test.model.BeanSimple;
import org.csveed.test.model.BeanVariousNotAnnotated;
import org.junit.Test;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.math.BigDecimal;

import static junit.framework.Assert.*;

public class BeanPropertyTest {

    @Test
    public void construct() throws IntrospectionException {
        BeanProperty property = new BeanProperty();
        Converter converter = new BeanSimpleConverter();
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor("name", BeanSimple.class);
        property.setConverter(converter);
        property.setColumnIndex(3);
        property.setColumnName("name");
        property.setPropertyDescriptor(propertyDescriptor);
        property.setRequired(true);
        assertEquals(converter, property.getConverter());
        assertEquals(3, property.getColumnIndex());
        assertEquals("name", property.getColumnName());
        assertEquals(propertyDescriptor, property.getPropertyDescriptor());
        assertTrue(property.isRequired());
    }

    @Test
    public void numberClass() throws IntrospectionException {
        BeanProperty property = new BeanProperty();
        property.setPropertyDescriptor(new PropertyDescriptor("number", BeanVariousNotAnnotated.class));
        assertNotNull(property.getNumberClass());
    }

    @Test
    public void notANumberClass() throws IntrospectionException {
        BeanProperty property = new BeanProperty();
        property.setPropertyDescriptor(new PropertyDescriptor("name", BeanSimple.class));
        assertNull(property.getNumberClass());
    }

}

package org.csveed.bean;

import org.csveed.bean.conversion.Converter;
import org.csveed.test.converters.BeanSimpleConverter;
import org.csveed.test.model.BeanSimple;
import org.csveed.test.model.BeanVariousNotAnnotated;
import org.junit.Test;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import static junit.framework.Assert.*;

public class BeanPropertyTest {

    @Test
    public void construct() throws IntrospectionException {
        BeanProperty property = new BeanProperty();
        Converter<BeanSimple> converter = new BeanSimpleConverter();
        PropertyDescriptor propertyDescriptor = new PropertyDescriptor("name", BeanSimple.class);
        property.setConverter(converter);
        property.setColumnIndex(3);
        property.setColumnName("name");
        property.setPropertyDescriptor(propertyDescriptor);
        property.setRequired(true);
        assertEquals(converter, property.getConverter());
        assertEquals(3, property.getColumnIndex());
        assertEquals("name", property.getColumnName());
        assertEquals(propertyDescriptor, property.getPropertyDescriptor());
        assertTrue(property.isRequired());
    }

    @Test
    public void numberClass() throws IntrospectionException {
        BeanProperty property = new BeanProperty();
        property.setPropertyDescriptor(new PropertyDescriptor("number", BeanVariousNotAnnotated.class));
        assertNotNull(property.getNumberClass());
    }

    @Test
    public void notANumberClass() throws IntrospectionException {
        BeanProperty property = new BeanProperty();
        property.setPropertyDescriptor(new PropertyDescriptor("name", BeanSimple.class));
        assertNull(property.getNumberClass());
    }

}

Remove unused import and add type converter.


package com.smartdevicelink.test.util;

import android.os.Build;

public class DeviceUtil {
    public static boolean isEmulator() {
        return Build.FINGERPRINT.startsWith("generic")
                || Build.FINGERPRINT.startsWith("unknown")
                || Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.MODEL.contains("Android SDL built for")
                || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
                || (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic"))
                || (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone"))
                || "google_sdk".equals(Build.PRODUCT);
    }
}

package com.smartdevicelink.test.util;

import android.os.Build;

public class DeviceUtil {
    public static boolean isEmulator() {
        return Build.FINGERPRINT.startsWith("generic")
                || Build.FINGERPRINT.startsWith("unknown")
                || Build.MODEL.contains("google_sdk")
                || Build.MODEL.contains("Emulator")
                || Build.MODEL.contains("Android SDK built for")
                || (Build.BRAND.startsWith("generic") && Build.DEVICE.startsWith("generic"))
                || (Build.BRAND.startsWith("Android") && Build.DEVICE.startsWith("generic"))
                || (Build.PRODUCT != null && Build.PRODUCT.startsWith("sdk_google_phone"))
                || "google_sdk".equals(Build.PRODUCT);
    }
}

Fix an issue in isEmulator


package com.redhat.ceylon.compiler.typechecker.treegen;

public class Util {

    static java.io.PrintStream out = System.out;

    public static String className(String nodeName) {
        return toJavaIdentifier(nodeName, true);
    }

    public static String fieldName(String nodeName) {
        return toJavaIdentifier(nodeName, false);
    }

    public static String toJavaIdentifier(String nodeName, boolean boundary) {
        StringBuilder result = new StringBuilder();
        for (char c: nodeName.toCharArray()) {
            if (c=='_') {
                boundary=true;
            }
            else if (boundary) {
                result.append(c);
                boundary=false;
            }
            else {
                result.append(Character.toLowerCase(c));
            }
        }
        return result.toString();
    }

    public static String initialUpper(String s) {
        return Character.toUpperCase(s.charAt(0)) + s.substring(1);
    }

    public static String description(String nodeName) {
        return nodeName.toLowerCase().replace('_', ' ');
    }

    public static void print(String text) {
       out.print(text);
    }

    public static void println(String text) {
       out.println(text);
    }

}

package com.redhat.ceylon.compiler.typechecker.treegen;

public class Util {

    public static java.io.PrintStream out = System.out;

    public static String className(String nodeName) {
        return toJavaIdentifier(nodeName, true);
    }

    public static String fieldName(String nodeName) {
        return toJavaIdentifier(nodeName, false);
    }

    public static String toJavaIdentifier(String nodeName, boolean boundary) {
        StringBuilder result = new StringBuilder();
        for (char c: nodeName.toCharArray()) {
            if (c=='_') {
                boundary=true;
            }
            else if (boundary) {
                result.append(c);
                boundary=false;
            }
            else {
                result.append(Character.toLowerCase(c));
            }
        }
        return result.toString();
    }

    public static String initialUpper(String s) {
        return Character.toUpperCase(s.charAt(0)) + s.substring(1);
    }

    public static String description(String nodeName) {
        return nodeName.toLowerCase().replace('_', ' ');
    }

    public static void print(String text) {
       out.print(text);
    }

    public static void println(String text) {
       out.println(text);
    }

}

Allow other packages to use `out` (for example the intelliJ plugin)


package net.shadowfacts.foodies.block;

/**
 * Helper class for registering blocks.
 * @author shadowfacts
 */
public class FBlocks {
}

package net.shadowfacts.foodies.block;

/**
 * Helper class for registering blocks.
 * @author shadowfacts
 */
public class FBlocks {
	public static void preInit() {

	}

	public static void load() {

	}

	public static void postInit() {

	}
}

Add helper methods for block helper class


package org.robockets.stronghold.robot.intake;

public enum Direction {
	FORWARD,
	BACKWARD,
	STOP;
}

package org.robockets.stronghold.robot.intake;

public enum Direction {
	FORWARD,
	BACKWARD,
	LEFT,
	RIGHT,
	STOP;
}

Add LEFT and RIGHT enums


/* Copyright (c) 2014 Andrea Zoli. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file. */

package it.inaf.android;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class DateFormatter {
    public static String format(String date)
    {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z");
        java.util.Date tmpDate = null;
        try {
            tmpDate = format.parse(date);
        } catch(ParseException e) {
            format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            try {
                tmpDate = format.parse(date);
            } catch (ParseException e1) {
                format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
                try {
                    tmpDate = format.parse(date);
                } catch (ParseException e2) {
                    e2.printStackTrace();
                }
            }
        }

        SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
        return postFormater.format(tmpDate);
    }
}

/* Copyright (c) 2014 Andrea Zoli. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file. */

package it.inaf.android;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

public class DateFormatter {
    public static String format(String date)
    {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.UK);
        java.util.Date tmpDate = null;
        try {
            tmpDate = format.parse(date);
        } catch(ParseException e) {
            format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.UK);
            try {
                tmpDate = format.parse(date);
            } catch (ParseException e1) {
                format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.UK);
                try {
                    tmpDate = format.parse(date);
                } catch (ParseException e2) {
                    e2.printStackTrace();
                }
            }
        }

        SimpleDateFormat postFormater = new SimpleDateFormat("dd.MM.yyyy", Locale.ITALY);
        return postFormater.format(tmpDate);
    }
}

Use Locale.UK while parsing dates.


package com.google.fhirengine;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

package com.google.fhirengine;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

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

    // Gets FHIR Engine using Dagger component.
    FhirEngine fhirEngine = DaggerFhirEngineComponent.builder()
        .context(this).build().getFhirEngine();
  }
}

Add sample code to create FhirEngine in the reference app.


package org.asciidoctor.jruby.cli;

import com.beust.jcommander.IStringConverter;
import org.asciidoctor.SafeMode;
import org.asciidoctor.log.Severity;

public class SeverityConverter implements IStringConverter<Severity> {

    @Override
    public Severity convert(String argument) { return Severity.valueOf(argument.toUpperCase()); }

}

package org.asciidoctor.jruby.cli;

import com.beust.jcommander.converters.EnumConverter;
import org.asciidoctor.log.Severity;

public class SeverityConverter extends EnumConverter<Severity> {

    public SeverityConverter() {
        super("--failure-level", Severity.class);
    }

    @Override
    public Severity convert(String argument) {
        return super.convert(argument.toUpperCase());
    }

}

Improve error messages when parsing --failure-level parameter


package com.utopia.pxview;

import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
import org.devio.rn.splashscreen.SplashScreen;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "PxView";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SplashScreen.show(this);
    }

    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected ReactRootView createRootView() {
                return new RNGestureHandlerEnabledRootView(MainActivity.this);
            }
        };
    }
}

package com.utopia.pxview;

import android.os.Bundle;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.swmansion.gesturehandler.react.RNGestureHandlerEnabledRootView;
import org.devio.rn.splashscreen.SplashScreen;

public class MainActivity extends ReactActivity {

    /**
     * Returns the name of the main component registered from JavaScript.
     * This is used to schedule rendering of the component.
     */
    @Override
    protected String getMainComponentName() {
        return "PxView";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // workaround for crashing on killed app restore
        // https://github.com/kmagiera/react-native-screens/issues/17#issuecomment-424704067
        // https://github.com/kmagiera/react-native-screens/issues/114
        super.onCreate(null);
        // super.onCreate(savedInstanceState);
        SplashScreen.show(this);
    }

    @Override
    protected ReactActivityDelegate createReactActivityDelegate() {
        return new ReactActivityDelegate(this, getMainComponentName()) {
            @Override
            protected ReactRootView createRootView() {
                return new RNGestureHandlerEnabledRootView(MainActivity.this);
            }
        };
    }
}

Fix crash on killed app restore on android


/*
 The caLAB Software License, Version 0.5

 Copyright 2006 SAIC. This software was developed in conjunction with the National
 Cancer Institute, and so to the extent government employees are co-authors, any
 rights in such works shall be subject to Title 17 of the United States Code,
 section 105.

 */
package gov.nih.nci.calab.ui.core;

/**
 * This class calls the Struts ForwardAction to forward to a page, aslo
 * extends AbstractBaseAction to inherit the user authentication features.
 *
 * @author pansu
 */

/* CVS $Id: BaseForwardAction.java,v 1.3 2006-08-02 21:27:59 pansu Exp $ */

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.ForwardAction;

public class BaseForwardAction extends AbstractBaseAction {
	public ActionForward executeTask(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ForwardAction forwardAction = new ForwardAction();
		return forwardAction.execute(mapping, form, request, response);
	}

	public boolean loginRequired() {
		return true;
	}

	public boolean canUserExecute(HttpSession session) {
		return true;
	}
}

/*
 The caLAB Software License, Version 0.5

 Copyright 2006 SAIC. This software was developed in conjunction with the National
 Cancer Institute, and so to the extent government employees are co-authors, any
 rights in such works shall be subject to Title 17 of the United States Code,
 section 105.

 */
package gov.nih.nci.calab.ui.core;

/**
 * This class calls the Struts ForwardAction to forward to a page, aslo
 * extends AbstractBaseAction to inherit the user authentication features.
 *
 * @author pansu
 */

/* CVS $Id: BaseForwardAction.java,v 1.4 2007-10-25 20:56:51 cais Exp $ */

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

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.ForwardAction;

public class BaseForwardAction extends AbstractBaseAction {
	public ActionForward executeTask(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ForwardAction forwardAction = new ForwardAction();
		return forwardAction.execute(mapping, form, request, response);
	}

	public boolean loginRequired() {
		//return true;
		return false;
	}

	public boolean canUserExecute(HttpSession session) {
		return true;
	}
}

Set loginRequired to false. For users without login, this is required for "back" link on some pages to function.


/*
 * Mutability Detector
 *
 * Copyright 2009 Graham Allan
 *
 * 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.mutabilitydetector.checkers;

import org.mutabilitydetector.MutabilityReason;
import org.objectweb.asm.Opcodes;

public class FinalClassChecker extends AbstractMutabilityChecker {

	@Override
	public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
		if((access & Opcodes.ACC_FINAL) == 0) {
			addResult("Is not declared final, and thus may be mutable.", null, MutabilityReason.NOT_DECLARED_FINAL);
		}
	}

}

/*
 * Mutability Detector
 *
 * Copyright 2009 Graham Allan
 *
 * 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.mutabilitydetector.checkers;

import static org.mutabilitydetector.checkers.AccessModifierQuery.type;

import org.mutabilitydetector.MutabilityReason;

public class FinalClassChecker extends AbstractMutabilityChecker {

	@Override
	public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
		if(type(access).isNotFinal()) {
			addResult("Is not declared final, and thus may be mutable.", null, MutabilityReason.NOT_DECLARED_FINAL);
		}
	}

}

Use more readable version for checking the final modifier is present.


package nanomsg;

import com.google.common.base.Preconditions;
import com.sun.jna.Pointer;

import java.nio.ByteBuffer;

import static nanomsg.Error.check;
import static nanomsg.Nanomsg.NANOMSG;

public class Message implements AutoCloseable {

    private Pointer message;
    private final int size;

    Message(Pointer message, int size) {
        this.message = message;
        this.size = size;
    }

    @Override
    public synchronized void close() {
        check(NANOMSG.nn_freemsg(message));
        message = null;
    }

    @Override
    protected void finalize() throws Throwable {
        close();
    }

    public synchronized ByteBuffer getDirectByteBuffer() {
        Preconditions.checkState(message != null);
        return message.getByteBuffer(0, size);
    }

    public synchronized ByteBuffer getByteBuffer() {
        Preconditions.checkState(message != null);

        ByteBuffer buffer = getDirectByteBuffer();

        ByteBuffer copy = ByteBuffer.allocate(buffer.remaining());
        copy.put(buffer).flip();

        return copy;
    }
}

package nanomsg;

import com.google.common.base.Preconditions;
import com.sun.jna.Pointer;

import java.nio.ByteBuffer;

import static nanomsg.Error.check;
import static nanomsg.Nanomsg.NANOMSG;

public class Message implements AutoCloseable {

    private Pointer message;
    private final int size;

    Message(Pointer message, int size) {
        this.message = message;
        this.size = size;
    }

    @Override
    public synchronized void close() {
        if (message != null) {
            check(NANOMSG.nn_freemsg(message));
            message = null;
        }
    }

    @Override
    protected void finalize() throws Throwable {
        close();
    }

    public synchronized ByteBuffer getDirectByteBuffer() {
        Preconditions.checkState(message != null);
        return message.getByteBuffer(0, size);
    }

    public synchronized ByteBuffer getByteBuffer() {
        Preconditions.checkState(message != null);

        ByteBuffer buffer = getDirectByteBuffer();

        ByteBuffer copy = ByteBuffer.allocate(buffer.remaining());
        copy.put(buffer).flip();

        return copy;
    }
}

Fix nn_freemsg SIGSEGV on NULL


package info.u_team.u_team_core;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.IModProxy;
import info.u_team.u_team_core.intern.proxy.*;
import info.u_team.u_team_core.util.verify.JarSignVerifier;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.*;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;

@Mod(UCoreMain.MODID)
public class UCoreMain {

	public static final String MODID = "uteamcore";
	public static final Logger LOGGER = LogManager.getLogger("UTeamCore");

	private static final IModProxy PROXY = DistExecutor.runForDist(() -> ClientProxy::new, () -> CommonProxy::new);

	public UCoreMain() {
		JarSignVerifier.checkSigned(MODID);
		FMLJavaModLoadingContext.get().getModEventBus().register(this);
		PROXY.construct();
	}

	@SubscribeEvent
	public void setup(FMLCommonSetupEvent event) {
		PROXY.setup();
	}

	@SubscribeEvent
	public void ready(FMLLoadCompleteEvent event) {
		PROXY.complete();
	}

}

package info.u_team.u_team_core;

import org.apache.logging.log4j.*;

import info.u_team.u_team_core.api.IModProxy;
import info.u_team.u_team_core.intern.proxy.*;
import info.u_team.u_team_core.util.verify.JarSignVerifier;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.DistExecutor;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.event.lifecycle.*;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;

@Mod(UCoreMain.MODID)
public class UCoreMain {

	public static final String MODID = "uteamcore";
	public static final Logger LOGGER = LogManager.getLogger("UTeamCore");

	private static final IModProxy PROXY = DistExecutor.safeRunForDist(() -> ClientProxy::new, () -> CommonProxy::new);

	public UCoreMain() {
		JarSignVerifier.checkSigned(MODID);
		FMLJavaModLoadingContext.get().getModEventBus().register(this);
		PROXY.construct();
	}

	@SubscribeEvent
	public void setup(FMLCommonSetupEvent event) {
		PROXY.setup();
	}

	@SubscribeEvent
	public void ready(FMLLoadCompleteEvent event) {
		PROXY.complete();
	}

}

Use the new safeRunForDist method


package com.fsck.k9.helper;

import android.app.Notification;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.NotificationCompat;

/**
 * Notification builder that will set {@link Notification#number} on pre-Honeycomb devices.
 *
 * @see android - Issue 38028
 */
public class NotificationBuilder extends NotificationCompat.Builder {
    protected int mNumber;

    public NotificationBuilder(Context context) {
        super(context);
    }

    @Override
    public NotificationCompat.Builder setNumber(int number) {
        mNumber = number;
        return this;
    }

    @Override
    public Notification build() {
        Notification notification = super.build();

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            notification.number = mNumber;
        }

        return notification;
    }
}

package com.fsck.k9.helper;

import android.app.Notification;
import android.content.Context;
import android.os.Build;
import android.support.v4.app.NotificationCompat;

/**
 * Notification builder that will set {@link Notification#number} on pre-Honeycomb devices.
 *
 * @see android - Issue 38028
 */
public class NotificationBuilder extends NotificationCompat.Builder {
    protected int mNumber;

    public NotificationBuilder(Context context) {
        super(context);
    }

    @Override
    public NotificationCompat.Builder setNumber(int number) {
        super.setNumber(number);
        mNumber = number;
        return this;
    }

    @Override
    public Notification build() {
        Notification notification = super.build();

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            notification.number = mNumber;
        }

        return notification;
    }
}

Fix unread count in notifications (again)


package com.webkreator.canoe.demo;

import javax.servlet.ServletException;

import com.webkreator.qlue.QlueApplication;
import com.webkreator.qlue.QlueServlet;

public class CanoeServlet extends QlueServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void createApplicationObject() throws ServletException {
		setApp(new QlueApplication("com.webkreator.canoe.demo.pages"));
	}
}

package com.webkreator.canoe.demo;

import javax.servlet.ServletException;

import com.webkreator.qlue.QlueApplication;
import com.webkreator.qlue.QlueServlet;

public class CanoeServlet extends QlueServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void createApplicationObject() {
		setApp(new QlueApplication("com.webkreator.canoe.demo.pages"));
	}
}

Fix broken Canoe servlet example.


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

package org.gradle.caching.local;

import org.gradle.api.Incubating;
import org.gradle.api.Nullable;
import org.gradle.caching.configuration.AbstractBuildCache;

/**
 * Configuration object for the local directory build cache.
 *
 * By default, the build cache is stored in {@code GRADLE_HOME/.caches/<GRADLE_VERSION>/build-cache}.
 *
 * @since 3.5
 */
@Incubating
public class DirectoryBuildCache extends AbstractBuildCache {
    private Object directory;

    /**
     * Returns the directory to use to store the build cache.
     */
    @Nullable
    public Object getDirectory() {
        return directory;
    }

    /**
     * Sets the directory to use to store the build cache.
     *
     * The directory is evaluated as per {@link org.gradle.api.Project#file(Object)}.
     */
    public void setDirectory(Object directory) {
        this.directory = directory;
    }
}

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

package org.gradle.caching.local;

import org.gradle.api.Incubating;
import org.gradle.api.Nullable;
import org.gradle.caching.configuration.AbstractBuildCache;

/**
 * Configuration object for the local directory build cache.
 *
 * By default, the build cache is stored in {@code GRADLE_HOME/caches}.
 *
 * @since 3.5
 */
@Incubating
public class DirectoryBuildCache extends AbstractBuildCache {
    private Object directory;

    /**
     * Returns the directory to use to store the build cache.
     */
    @Nullable
    public Object getDirectory() {
        return directory;
    }

    /**
     * Sets the directory to use to store the build cache.
     *
     * The directory is evaluated as per {@link org.gradle.api.Project#file(Object)}.
     */
    public void setDirectory(Object directory) {
        this.directory = directory;
    }
}

Change documentation for directory build cache default location


package com.github.pedrovgs.androidwifiadb.adb;

import com.github.pedrovgs.androidwifiadb.Device;
import java.util.LinkedList;
import java.util.List;

public class ADBParser {

  public List<Device> parseGetDevicesOutput(String adbDevicesOutput) {
    List<Device> devices = new LinkedList<>();
    String[] splittedOutput = adbDevicesOutput.split("\\n");
    for (String line : splittedOutput) {
      String[] deviceLine = line.split("\\t");
      if (deviceLine.length == 2) {
        String id = deviceLine[0];
        if (id.contains(".")) {
          continue;
        }
        String name = deviceLine[1];
        Device device = new Device(name, id);
        devices.add(device);
      }
    }
    return devices;
  }

  public String parseGetDeviceIp(String ipInfoOutput) {
    String[] splittedOutput = ipInfoOutput.split("\\n");
    int end = splittedOutput[1].indexOf("/");
    int start = splittedOutput[1].indexOf("t");
    return splittedOutput[1].substring(start + 2, end);
  }
}

package com.github.pedrovgs.androidwifiadb.adb;

import com.github.pedrovgs.androidwifiadb.Device;
import java.util.LinkedList;
import java.util.List;

public class ADBParser {

  public List<Device> parseGetDevicesOutput(String adbDevicesOutput) {
    List<Device> devices = new LinkedList<Device>();
    String[] splittedOutput = adbDevicesOutput.split("\\n");
    for (String line : splittedOutput) {
      String[] deviceLine = line.split("\\t");
      if (deviceLine.length == 2) {
        String id = deviceLine[0];
        if (id.contains(".")) {
          continue;
        }
        String name = deviceLine[1];
        Device device = new Device(name, id);
        devices.add(device);
      }
    }
    return devices;
  }

  public String parseGetDeviceIp(String ipInfoOutput) {
    String[] splittedOutput = ipInfoOutput.split("\\n");
    int end = splittedOutput[1].indexOf("/");
    int start = splittedOutput[1].indexOf("t");
    return splittedOutput[1].substring(start + 2, end);
  }
}

Remove diamond usage. IntelliJ plugins needs java 6 and this feature is not supported


/*
 * 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 fi.jgke.tagger.domain;

import java.util.UUID;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author jgke
 */
public class SourceTest {

    public SourceTest() {
    }

    @Test
    public void testSetGetTitle() {
        String title = UUID.randomUUID().toString();
        Source instance = new Source();
        instance.setTitle(title);
        assertEquals(title, instance.getTitle());
    }

    @Test
    public void testSetGetUrl() {
        String url = UUID.randomUUID().toString();
        Source instance = new Source();
        instance.setUrl(url);
        assertEquals(url, instance.getUrl());
    }

    @Test
    public void testSetGetTitleAndUrl() {
        String title = UUID.randomUUID().toString();
        String url = UUID.randomUUID().toString();
        Source instance = new Source();
        instance.setTitle(title);
        instance.setUrl(url);
        assertEquals(title, instance.getTitle());
        assertEquals(url, instance.getUrl());
    }
}

/*
 * 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 fi.jgke.tagger.domain;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import org.junit.Test;
import static org.junit.Assert.*;

/**
 *
 * @author jgke
 */
public class SourceTest {

    public SourceTest() {
    }

    @Test
    public void testSetGetTitle() {
        String title = UUID.randomUUID().toString();
        Source instance = new Source();
        instance.setTitle(title);
        assertEquals(title, instance.getTitle());
    }

    @Test
    public void testSetGetUrl() {
        String url = UUID.randomUUID().toString();
        Source instance = new Source();
        instance.setUrl(url);
        assertEquals(url, instance.getUrl());
    }

    @Test
    public void testSetGetTitleAndUrl() {
        String title = UUID.randomUUID().toString();
        String url = UUID.randomUUID().toString();
        Source instance = new Source();
        instance.setTitle(title);
        instance.setUrl(url);
        assertEquals(title, instance.getTitle());
        assertEquals(url, instance.getUrl());
    }

    @Test
    public void testSetGetSourcetype() {
        Type sourcetype = new Type();
        sourcetype.setValue(UUID.randomUUID().toString());
        Source instance = new Source();
        instance.setSourcetype(sourcetype);
        assertEquals(sourcetype, instance.getSourcetype());
    }

    @Test
    public void testSetGetTags() throws NoSuchMethodException {
        List<Tag> tags = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            Tag tag = new Tag();
            tag.setValue(UUID.randomUUID().toString());
            tags.add(tag);
        }
        Source instance = new Source();
        instance.setTags(tags);
        assertEquals(tags, instance.getTags());
    }

}

Add more tests for Source


package org.commcare.modern.parse;

import org.commcare.core.interfaces.UserSandbox;
import org.commcare.core.parse.ParseUtils;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * Convenience methods, mostly for touchforms so we don't have to deal with Java IO
 * in Jython which is terrible
 *
 * Used by touchforms
 *
 * Created by wpride1 on 8/20/15.
 */
@SuppressWarnings("unused")
public class ParseUtilsHelper  extends ParseUtils {
    public static void parseXMLIntoSandbox(String restore, UserSandbox sandbox)
            throws InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException, IOException {
        InputStream stream = new ByteArrayInputStream(restore.getBytes(StandardCharsets.UTF_8));
        parseIntoSandbox(stream, sandbox);
    }

    public static void parseFileIntoSandbox(File restore, UserSandbox sandbox)
            throws IOException, InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException {
        InputStream stream = new FileInputStream(restore);
        parseIntoSandbox(stream, sandbox);
    }
}

package org.commcare.modern.parse;

import org.commcare.core.interfaces.UserSandbox;
import org.commcare.core.parse.ParseUtils;
import org.javarosa.xml.util.InvalidStructureException;
import org.javarosa.xml.util.UnfullfilledRequirementsException;
import org.xmlpull.v1.XmlPullParserException;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * Convenience methods, mostly for touchforms so we don't have to deal with Java IO
 * in Jython which is terrible
 *
 * Used by touchforms
 *
 * Created by wpride1 on 8/20/15.
 */
@SuppressWarnings("unused")
public class ParseUtilsHelper  extends ParseUtils {
    public static void parseXMLIntoSandbox(InputStream restoreStream, UserSandbox sandbox)
            throws InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException, IOException {
        parseIntoSandbox(restoreStream, sandbox);
    }

    public static void parseXMLIntoSandbox(String restore, UserSandbox sandbox)
            throws InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException, IOException {
        InputStream stream = new ByteArrayInputStream(restore.getBytes(StandardCharsets.UTF_8));
        parseIntoSandbox(stream, sandbox);
    }

    public static void parseFileIntoSandbox(File restore, UserSandbox sandbox)
            throws IOException, InvalidStructureException, UnfullfilledRequirementsException, XmlPullParserException {
        InputStream stream = new FileInputStream(restore);
        parseIntoSandbox(stream, sandbox);
    }
}

Add method to accept stream


package org.hiero.sketch.dataset.api;

import java.io.Serializable;

/**
 * A partial result always describes a DELTA between the previous partial result
 * and the current one.
 * @param <T>  Type of data in partial result.
 */
public class PartialResult<T> implements Serializable {
    /**
     * How much more has been deltaDone from the computation has been deltaDone
     * since the previous partial result.  A number between 0 and 1.  Even if this
     * is 1, it does not necessarily mean that the work is finished.
     */
    public final double deltaDone;
    /**
     * Additional data computed since the previous partial result.
     */
    public final T deltaValue;

    /**
     * Creates a partial result.
     * @param deltaDone  How much more has been done.  A number between 0 and 1.
     * @param deltaValue Extra result produced.
     */
    public PartialResult(double deltaDone, final T deltaValue) {
        if (deltaDone < 0) {
            throw new RuntimeException("Illegal value for deltaDone");
        } else if (deltaDone > 1) {
            // This can happen due to double addition imprecision.
            deltaDone = 1.0;
        }
        this.deltaDone = deltaDone;
        this.deltaValue = deltaValue;
    }

    @Override
    public String toString() {
        return "PR[" + Double.toString(this.deltaDone) + "," + this.deltaValue.toString() + "]";
    }
}

package org.hiero.sketch.dataset.api;

import java.io.Serializable;

/**
 * A partial result always describes a DELTA between the previous partial result
 * and the current one.
 * @param <T>  Type of data in partial result.
 */
public class PartialResult<T> implements Serializable {
    /**
     * How much more has been deltaDone from the computation has been deltaDone
     * since the previous partial result.  A number between 0 and 1.  Even if this
     * is 1, it does not necessarily mean that the work is finished.
     */
    public final double deltaDone;
    /**
     * Additional data computed since the previous partial result.
     */
    public final T deltaValue;

    /**
     * Creates a partial result.
     * @param deltaDone  How much more has been done.  A number between 0 and 1.
     * @param deltaValue Extra result produced.
     */
    public PartialResult(double deltaDone, final T deltaValue) {
        if (deltaDone < 0) {
            throw new RuntimeException("Illegal value for deltaDone");
        } else if (deltaDone > 1) {
            // This can happen due to double addition imprecision.
            deltaDone = 1.0;
        }
        this.deltaDone = deltaDone;
        this.deltaValue = deltaValue;
    }

    @Override
    public String toString() {
        return "PR[" + Double.toString(this.deltaDone) + "," + this.deltaValue + "]";
    }
}

Fix NPE because deltaValue can be null


package com.github.aureliano.edocs.app.gui.menu.file;

import javax.swing.JMenu;
import javax.swing.JSeparator;

import com.github.aureliano.edocs.common.locale.EdocsLocale;

public class FileMenu extends JMenu {

	private static final long serialVersionUID = -662548298147505185L;

	private CloseTabMenuItem closeTabMenuItem;
	private CloseAllTabsMenuItem closeAllTabsMenuItem;
	private ExitMenuItem exitMenuItem;

	public FileMenu() {
		super.setText(EdocsLocale.instance().getMessage("gui.menubar.file"));
		this.addMenuItems();
	}

	private void addMenuItems() {
		this.closeTabMenuItem = new CloseTabMenuItem();
		this.closeAllTabsMenuItem = new CloseAllTabsMenuItem();
		this.exitMenuItem = new ExitMenuItem();

		super.add(this.closeTabMenuItem);
		super.add(this.closeAllTabsMenuItem);

		super.add(new JSeparator());

		super.add(this.exitMenuItem);
	}
}

package com.github.aureliano.edocs.app.gui.menu.file;

import javax.swing.JMenu;
import javax.swing.JSeparator;

import com.github.aureliano.edocs.common.locale.EdocsLocale;

public class FileMenu extends JMenu {

	private static final long serialVersionUID = -662548298147505185L;

	private ConnectMenuItem connectMenuItem;
	private CloseTabMenuItem closeTabMenuItem;
	private CloseAllTabsMenuItem closeAllTabsMenuItem;
	private ExitMenuItem exitMenuItem;

	public FileMenu() {
		super.setText(EdocsLocale.instance().getMessage("gui.menubar.file"));
		this.addMenuItems();
	}

	private void addMenuItems() {
		this.connectMenuItem = new ConnectMenuItem();
		this.closeTabMenuItem = new CloseTabMenuItem();
		this.closeAllTabsMenuItem = new CloseAllTabsMenuItem();
		this.exitMenuItem = new ExitMenuItem();

		super.add(this.connectMenuItem);

		super.add(new JSeparator());

		super.add(this.closeTabMenuItem);
		super.add(this.closeAllTabsMenuItem);

		super.add(new JSeparator());

		super.add(this.exitMenuItem);
	}
}

Add connect menu item to file menu.


package com.ibm.streamsx.topology.internal.functional.ops;

import com.ibm.streams.operator.OperatorContext;
import com.ibm.streamsx.topology.function.FunctionContext;
import com.ibm.streamsx.topology.internal.functional.FunctionalHandler;
import com.ibm.streamsx.topology.internal.functional.StatelessFunctionalHandler;

class FunctionalOpUtils {

    static <T> FunctionalHandler<T> createFunctionHandler(OperatorContext context, FunctionContext functionContext, String functionalLogic) throws Exception {
        FunctionalHandler<T> handler = new StatelessFunctionalHandler<T>(functionContext, functionalLogic);
        return handler;
    }

}

package com.ibm.streamsx.topology.internal.functional.ops;

import com.ibm.streams.operator.OperatorContext;
import com.ibm.streams.operator.state.CheckpointContext;
import com.ibm.streams.operator.state.CheckpointContext.Kind;
import com.ibm.streamsx.topology.function.FunctionContext;
import com.ibm.streamsx.topology.internal.functional.FunctionalHandler;
import com.ibm.streamsx.topology.internal.functional.StatelessFunctionalHandler;

class FunctionalOpUtils {

    static <T> FunctionalHandler<T> createFunctionHandler(OperatorContext context, FunctionContext functionContext, String functionalLogic) throws Exception {
        CheckpointContext cc = context.getOptionalContext(CheckpointContext.class);
        if (cc != null) {
            if (cc.getKind() == Kind.OPERATOR_DRIVEN)
                throw new IllegalStateException(); // TODO compile time checks.

            StatefulFunctionalHandler<T> handler = new StatefulFunctionalHandler<T>(functionContext, functionalLogic);
            context.registerStateHandler(handler);
            return handler;
        }
        return new StatelessFunctionalHandler<T>(functionContext, functionalLogic);
    }
}

Use a stateful funcion handler if checkpointing is enabled


package edu.stuy.commands;

import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class LiftControlCommand extends Command {

    public LiftControlCommand() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(Robot.lift);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        if (Robot.oi.operatorPad.getLeftY() >= .5) {
            Robot.lift.goUp();
        } else if (Robot.oi.operatorPad.getLeftY() <= -.5) {
            Robot.lift.goDown();
        } else {
            Robot.lift.stop();
        }
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

package edu.stuy.commands;

import edu.stuy.Robot;
import edu.wpi.first.wpilibj.command.Command;

/**
 *
 */
public class LiftControlCommand extends Command {

    public LiftControlCommand() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(Robot.lift);
    }

    // Called just before this Command runs the first time
    protected void initialize() {
    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        if (Robot.oi.operatorPad.getLeftY() <= -.5) {
            Robot.lift.goUp();
        } else if (Robot.oi.operatorPad.getLeftY() >= .5) {
            Robot.lift.goDown();
        } else {
            Robot.lift.stop();
        }
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

Fix logic for operator pad


/*
 * 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 edu.afs.commands;

import edu.afs.subsystems.drivesubsystem.*;
/**
 *
 * @author User
 */
public class DriveWithJoystickCommand extends CommandBase {

    public DriveWithJoystickCommand() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(drive); // reserve the chassis subsystem
    }

    // Called just before this Command runs the first time
    protected void initialize() {

    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        drive.driveWithJoystick();
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

/*
 * 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 edu.afs.commands;

import edu.afs.subsystems.drivesubsystem.*;
import edu.afs.subsystems.autoranger.*;
import edu.afs.commands.AutoDriveToShotRangeCommand;
/**
 *
 * @author User
 */
public class DriveWithJoystickCommand extends CommandBase {

    private static double RANGE_TOLERANCE = 12.0;  // In inches.
    RangeBeacon m_rangeBeacon;
    double m_desiredRange;

    public DriveWithJoystickCommand() {
        // Use requires() here to declare subsystem dependencies
        // eg. requires(chassis);
        requires(drive); // reserve the chassis subsystem
        m_rangeBeacon = RangeBeacon.getInstance();
        m_desiredRange = AutoDriveToShotRangeCommand.GetDesiredRange();
    }

    // Called just before this Command runs the first time
    protected void initialize() {

    }

    // Called repeatedly when this Command is scheduled to run
    protected void execute() {
        // Check the range to target.
        double range = autoRanger.GetRange();
        double absError = Math.abs(m_desiredRange - range);
        if(absError <= RANGE_TOLERANCE){
            // At shooting range - set beaon indicator.
            m_rangeBeacon.SetAtShotRangeIndicator(true);
        } else {
            m_rangeBeacon.SetAtShotRangeIndicator(false);
        }
        drive.driveWithJoystick();
    }

    // Make this return true when this Command no longer needs to run execute()
    protected boolean isFinished() {
        return false;
    }

    // Called once after isFinished returns true
    protected void end() {
    }

    // Called when another command which requires one or more of the same
    // subsystems is scheduled to run
    protected void interrupted() {
    }
}

Add shot range indication while driving manually.


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

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

    private ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperProvider() {
        mapper.setConfig(mapper.getSerializationConfig().without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS));
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }

}

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

import com.fasterxml.jackson.databind.ObjectMapper;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import java.text.SimpleDateFormat;

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

    private ObjectMapper mapper = new ObjectMapper();

    public ObjectMapperProvider() {
        mapper.setConfig(mapper.getSerializationConfig().with(
                new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")));
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return mapper;
    }

}

Update JSON serialization date format


package org.knowm.xchange.interceptor;

import com.google.common.base.Suppliers;
import java.util.Collection;
import java.util.ServiceLoader;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import si.mazi.rescu.Interceptor;

public class InterceptorProvider {

  private static final Supplier<Collection<Interceptor>> INTERCEPTORS_SUPPLIER =
      Suppliers.memoize(
          () -> {
            final ServiceLoader<Interceptor> serviceLoader = ServiceLoader.load(Interceptor.class);
            return StreamSupport.stream(serviceLoader.spliterator(), false)
                .collect(Collectors.toSet());
          });

  public static Collection<Interceptor> provide() {
    return INTERCEPTORS_SUPPLIER.get();
  }
}

Add possibility to use custom Interceptors