package org.innovateuk.ifs.project.grantofferletter.viewmodel;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static java.util.Collections.singletonList;

/*
 * Holder of values for the other costs rows on GOL finance tables, which are handled differently
 */
public class OtherCostsRowModel {

    private final String otherCostName;
    private Map<String, List<BigDecimal>> otherCostValues;

    public OtherCostsRowModel(String otherCostName,
                              Map<String, List<BigDecimal>> otherCostValues) {
        this.otherCostName = otherCostName;
        this.otherCostValues = otherCostValues;
    }

    public String getOtherCostName() {
        return otherCostName;
    }

    public Map<String, List<BigDecimal>> getOtherCostValues() {
        return otherCostValues;
    }

    public void addToCostValues(String orgName, BigDecimal cost) {
        if(otherCostValues.keySet().contains(orgName)) {
            otherCostValues.get(orgName).add(cost);
        } else {
            otherCostValues.put(orgName, singletonList(cost));
        }
    }

    public Collection<String> getOrganisations() {
        return otherCostValues.keySet();
    }

    public BigDecimal getCostValuesForOrg(String organisation) {
        return otherCostValues.get(organisation)
                .stream()
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

package org.innovateuk.ifs.project.grantofferletter.viewmodel;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static java.util.Collections.singletonList;

/*
 * Holder of values for the other costs rows on GOL finance tables, which are handled differently
 */
public class OtherCostsRowModel {

    private final String otherCostName;
    private Map<String, List<BigDecimal>> otherCostValues;

    public OtherCostsRowModel(String otherCostName,
                              Map<String, List<BigDecimal>> otherCostValues) {
        this.otherCostName = otherCostName;
        this.otherCostValues = otherCostValues;
    }

    public String getOtherCostName() {
        return otherCostName;
    }

    public Map<String, List<BigDecimal>> getOtherCostValues() {
        return otherCostValues;
    }

    public void addToCostValues(String orgName, BigDecimal cost) {
        if(otherCostValues.keySet().contains(orgName)) {
            otherCostValues.get(orgName).add(cost);
        } else {
            otherCostValues.put(orgName, singletonList(cost));
        }
    }

    public Collection<String> getOrganisations() {
        return otherCostValues.keySet();
    }

    public BigDecimal getCostValuesForOrg(String organisation) {
        return otherCostValues.get(organisation)
                .stream()
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    public BigDecimal getTotal() {
        return otherCostValues == null ?
                BigDecimal.ZERO :
                otherCostValues
                        .values()
                        .stream()
                        .flatMap(List::stream)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
    }
}

Add support for totals to other costs rows


package org.commcare.utils;

import android.content.Context;

import org.commcare.util.ArrayDataSource;

/**
 * ArrayDataSource that uses the Android 'values' resources
 */

public class AndroidArrayDataSource implements ArrayDataSource {

    private Context context;

    public AndroidArrayDataSource(Context context){
        this.context = context;
    }

    @Override
    public String[] getArray(String key) {
        int resourceId = context.getResources().getIdentifier(key, "array", context.getPackageName());
        return context.getResources().getStringArray(resourceId);
    }
}

package org.commcare.utils;

import android.content.Context;

import org.commcare.util.ArrayDataSource;

/**
 * ArrayDataSource that uses the Android 'values' resources
 */

public class AndroidArrayDataSource implements ArrayDataSource {

    private Context context;

    public AndroidArrayDataSource(Context context){
        this.context = context;
    }

    @Override
    public String[] getArray(String key) {
        int resourceId = context.getResources().getIdentifier(key, "array", context.getPackageName());

        if (resourceId == 0) {
            throw new RuntimeException("Localized array data for '" + key + "' not found");
        }

        return context.getResources().getStringArray(resourceId);
    }
}

Add error handling for missing resource


package com.juliacomputing.jldt.eclipse.ui.console;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.dltk.launching.AbstractScriptLaunchConfigurationDelegate;
import org.eclipse.swt.widgets.Display;

import java.io.File;

public class JuliaREPLLaunchConfigurationDelegate extends AbstractScriptLaunchConfigurationDelegate {

  public void launch(final ILaunchConfiguration configuration, String mode, ILaunch launch,
      IProgressMonitor monitor) throws CoreException {

    monitor.setCanceled(true);

    final String workingDirectory = getProjectLocation(configuration);
    final String source = getSourceModule(configuration).getElementName();
    final String script = new File(workingDirectory, source).getAbsolutePath();

    Display.getDefault().asyncExec(new Runnable() {
      public void run() {
        final JuliaConsoleFactory consoleFactory = new JuliaConsoleFactory();
        final JuliaScriptConsole console = consoleFactory.newConsole();
        console.executeCommand("include(\"" + script + "\")");
      }
    });
  }

  @Override
  public String getLanguageId() {
    return "com.juliacomputing.jldt.eclipse.core.nature";
  }
}

package com.juliacomputing.jldt.eclipse.ui.console;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.dltk.launching.AbstractScriptLaunchConfigurationDelegate;
import org.eclipse.swt.widgets.Display;

import java.io.File;

public class JuliaREPLLaunchConfigurationDelegate extends AbstractScriptLaunchConfigurationDelegate {

  public void launch(final ILaunchConfiguration configuration, String mode, ILaunch launch,
      IProgressMonitor monitor) throws CoreException {

    monitor.setCanceled(true);

    final String workingDirectory = getProjectLocation(configuration);
    final String source = getSourceModule(configuration).getElementName();
    final String script = new File(workingDirectory, source).getAbsolutePath();

    Display.getDefault().asyncExec(new Runnable() {
      public void run() {
        final JuliaConsoleFactory consoleFactory = new JuliaConsoleFactory();
        final JuliaScriptConsole console = consoleFactory.newConsole();
        console.executeCommand(String.format("include(\\\"%s\\\")",script));
      }
    });
  }

  @Override
  public String getLanguageId() {
    return "com.juliacomputing.jldt.eclipse.core.nature";
  }
}

Fix current script repl include


package io.github.hidroh.materialistic;

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.view.Menu;

/**
 * Helper to tint menu items for activities and fragments
 */
public class MenuTintDelegate {
    private int mTextColorPrimary;

    /**
     * Callback that should be triggered after activity has been created
     * @param context    activity context
     */
    public void onActivityCreated(Context context) {
        mTextColorPrimary = ContextCompat.getColor(context,
                AppUtils.getThemedResId(context, android.R.attr.textColorPrimary));
    }

    /**
     * Callback that should be triggered after menu has been inflated
     * @param menu    inflated menu
     */
    public void onOptionsMenuCreated(Menu menu) {
        for (int i = 0; i < menu.size(); i++) {
            Drawable drawable = menu.getItem(i).getIcon();
            if (drawable == null) {
                continue;
            }
            drawable.mutate().setColorFilter(mTextColorPrimary, PorterDuff.Mode.SRC_IN);
        }
    }
}

package io.github.hidroh.materialistic;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.view.Menu;

/**
 * Helper to tint menu items for activities and fragments
 */
public class MenuTintDelegate {
    private int mTextColorPrimary;

    /**
     * Callback that should be triggered after activity has been created
     * @param context    activity context
     */
    public void onActivityCreated(Context context) {
        mTextColorPrimary = ContextCompat.getColor(context,
                AppUtils.getThemedResId(context, android.R.attr.textColorPrimary));
    }

    /**
     * Callback that should be triggered after menu has been inflated
     * @param menu    inflated menu
     */
    public void onOptionsMenuCreated(Menu menu) {
        for (int i = 0; i < menu.size(); i++) {
            Drawable drawable = menu.getItem(i).getIcon();
            if (drawable == null) {
                continue;
            }
            drawable = DrawableCompat.wrap(drawable);
            DrawableCompat.setTint(drawable, mTextColorPrimary);
        }
    }
}

Use DrawableCompat to tint drawables


package com.zulip.android.viewholders;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;

import com.zulip.android.activities.RecyclerMessageAdapter;

public class HeaderSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int verticalMargin;

    private int toolbarHeight;

    public HeaderSpaceItemDecoration(int verticalMargin, Context context) {
        this.verticalMargin = verticalMargin;
        TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            toolbarHeight = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {

        int position = parent.getChildAdapterPosition(view);

        int viewType = parent.getAdapter().getItemViewType(position);
        if (viewType == RecyclerMessageAdapter.VIEWTYPE_MESSAGE_HEADER && position != 0) {
            outRect.top = verticalMargin;
        } else if (viewType == RecyclerMessageAdapter.VIEWTYPE_HEADER) {
            outRect.top = toolbarHeight;
        }
    }
}

package com.zulip.android.viewholders;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;

import com.zulip.android.activities.RecyclerMessageAdapter;

public class HeaderSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int verticalMargin;

    private int toolbarHeight;

    public HeaderSpaceItemDecoration(int verticalMargin, Context context) {
        this.verticalMargin = verticalMargin;
        TypedValue tv = new TypedValue();
        if (context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            toolbarHeight = TypedValue.complexToDimensionPixelSize(tv.data, context.getResources().getDisplayMetrics());
        }
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {

        int position = parent.getChildAdapterPosition(view);
        int size = parent.getAdapter().getItemCount();
        int viewType = parent.getAdapter().getItemViewType(position);
        if (viewType == RecyclerMessageAdapter.VIEWTYPE_MESSAGE_HEADER && position != 0) {
            outRect.top = verticalMargin;
        } else if (viewType == RecyclerMessageAdapter.VIEWTYPE_HEADER) {
            outRect.top = toolbarHeight;
        }
        outRect.bottom = (position == size - 2) ? verticalMargin : 0;
    }
}

Add margin to the bottommost message


package guitests.guihandles;

import guitests.GuiRobot;
import javafx.stage.Stage;

/**
 * A handle to the Command Box in the GUI.
 */
public class CommandBoxHandle extends GuiHandle{

    public static final String COMMAND_INPUT_FIELD_ID = "#commandTextField";

    public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) {
        super(guiRobot, primaryStage, stageTitle);
    }

    public void enterCommand(String command) {
        setTextField(COMMAND_INPUT_FIELD_ID, command);
    }

    public String getCommandInput() {
        return getTextFieldText(COMMAND_INPUT_FIELD_ID);
    }

    /**
     * Enters the given command in the Command Box and presses enter.
     */
    public void runCommand(String command) {
        enterCommand(command);
        pressEnter();
        guiRobot.sleep(2000); //Give time for the command to take effect
    }

    public HelpWindowHandle runHelpCommand() {
        enterCommand("help");
        pressEnter();
        return new HelpWindowHandle(guiRobot, primaryStage);
    }
}

package guitests.guihandles;

import guitests.GuiRobot;
import javafx.stage.Stage;

/**
 * A handle to the Command Box in the GUI.
 */
public class CommandBoxHandle extends GuiHandle{

    public static final String COMMAND_INPUT_FIELD_ID = "#commandTextField";

    public CommandBoxHandle(GuiRobot guiRobot, Stage primaryStage, String stageTitle) {
        super(guiRobot, primaryStage, stageTitle);
    }

    public void enterCommand(String command) {
        setTextField(COMMAND_INPUT_FIELD_ID, command);
    }

    public String getCommandInput() {
        return getTextFieldText(COMMAND_INPUT_FIELD_ID);
    }

    /**
     * Enters the given command in the Command Box and presses enter.
     */
    public void runCommand(String command) {
        enterCommand(command);
        pressEnter();
        guiRobot.sleep(500); //Give time for the command to take effect
    }

    public HelpWindowHandle runHelpCommand() {
        enterCommand("help");
        pressEnter();
        return new HelpWindowHandle(guiRobot, primaryStage);
    }
}

Edit GUI robot sleep time


package com.thoughtworks.acceptance;

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

public class SwingTest extends AbstractAcceptanceTest {

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

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

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

        assertEquals(originalXml, deserializedXml);
    }

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

        String originalXml = xstream.toXML(original);

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

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

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

package com.thoughtworks.acceptance;

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

public class SwingTest extends AbstractAcceptanceTest {

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

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

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

        assertEquals(originalXml, deserializedXml);
    }

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

        String originalXml = xstream.toXML(original);

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

        assertEquals(originalXml, deserializedXml);

        list.setModel(deserialized);
    }

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

Use L&F that is available on JDK 1.3


/*
 * Copyright (c) 2011 Jeppetto and Jonathan Thompson
 *
 * 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.jeppetto.enhance;

/**
 * Utility for converting primitive types to objects.
 */
public class ReferenceUtil {

    //-------------------------------------------------------------
    // Constructor
    //-------------------------------------------------------------

    private ReferenceUtil() { /* do not instantiate */ }

    //-------------------------------------------------------------
    // Methods - Public - Static
    //-------------------------------------------------------------

    public static Object asObject(Object obj) {
        return obj;
    }

    public static Object asObject(boolean obj) {
        return obj;
    }

    public static Object asObject(byte obj) {
        return obj;
    }

    public static Object asObject(short obj) {
        return obj;
    }

    public static Object asObject(int obj) {
        return obj;
    }

    public static Object asObject(long obj) {
        return obj;
    }

    public static Object asObject(double obj) {
        return obj;
    }
}

/*
 * Copyright (c) 2011 Jeppetto and Jonathan Thompson
 *
 * 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.jeppetto.enhance;

/**
 * Utility for converting primitive types to objects.
 */
public class ReferenceUtil {

    //-------------------------------------------------------------
    // Constructor
    //-------------------------------------------------------------

    private ReferenceUtil() { /* do not instantiate */ }

    //-------------------------------------------------------------
    // Methods - Public - Static
    //-------------------------------------------------------------

    public static Object asObject(Object obj) {
        return obj;
    }

    public static Object asObject(boolean obj) {
        return obj;
    }

    public static Object asObject(byte obj) {
        return obj;
    }

    public static Object asObject(short obj) {
        return obj;
    }

    public static Object asObject(int obj) {
        return obj;
    }

    public static Object asObject(long obj) {
        return obj;
    }

    public static Object asObject(float obj) {
        return obj;
    }

    public static Object asObject(double obj) {
        return obj;
    }
}

Include a missing asObject(Float obj) method.


package edu.stuy.starlorn.upgrades;

public class ScatterShotUpgrade extends GunUpgrade {

    public ScatterShotUpgrade() {
        super();
        _name = "Scattershot";
        _description = "";
    }

    @Override
    public int getNumShots() {
        return 4;
    }

    @Override
    public double getAimAngle() {
        // Random angle going forwards
        return (Math.PI * Math.random());
    }

    @Override
    public int getShotSpeed(int shotspeed) {
        // Random speed, either 1, 2, or 3
        return (int) (Math.random() * 3) + shotspeed;
    }
}

package edu.stuy.starlorn.upgrades;

public class ScatterShotUpgrade extends GunUpgrade {

    public ScatterShotUpgrade() {
        super();
        _name = "Scattershot";
        _description = "";
    }

    @Override
    public int getNumShots() {
        return 4;
    }

    @Override
    public double getAimAngle() {
        // Random angle going forwards
        return (Math.PI * (Math.random() - .5));
    }

    @Override
    public int getShotSpeed(int shotspeed) {
        // Random speed, either 1, 2, or 3
        return (int) (Math.random() * 3) + shotspeed;
    }
}

Make ScatterShot not use derp angles


package id.kodekreatif.cordova.PDFDigiSign;

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

import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.cms.CMSObjectIdentifiers;
import org.spongycastle.cms.CMSException;
import org.spongycastle.cms.CMSTypedData;

class PDFDigiSignData implements CMSTypedData
{

  InputStream in;
  private static final int BUFFER_SIZE = 10240;
  private final ASN1ObjectIdentifier type;

  public PDFDigiSignData(ASN1ObjectIdentifier type,
          InputStream is)
  {
    this.type = type;
    in = is;
  }

  public PDFDigiSignData(InputStream is)
  {
    this(new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId()), is);
  }

  @Override
  public Object getContent()
  {
    return null;
  }

  @Override
  public void write(OutputStream out) throws IOException, CMSException
  {
    // read the content only one time
    byte[] buffer = new byte[BUFFER_SIZE];
    int c;
    while ((c = in.read(buffer)) != -1)
    {
      out.write(buffer, 0, c);
    }
    in.close();
  }

  @Override
  public ASN1ObjectIdentifier getContentType() {
    return type;
  }
}

package id.kodekreatif.cordova.PDFDigiSign;

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

import org.spongycastle.asn1.ASN1ObjectIdentifier;
import org.spongycastle.asn1.cms.CMSObjectIdentifiers;
import org.spongycastle.cms.CMSException;
import org.spongycastle.cms.CMSTypedData;

class PDFDigiSignData implements CMSTypedData
{

  InputStream in;
  private static final int BUFFER_SIZE = 10240;
  private final ASN1ObjectIdentifier type;

  public PDFDigiSignData(ASN1ObjectIdentifier type,
          InputStream is)
  {
    this.type = type;
    in = is;
  }

  public PDFDigiSignData(InputStream is)
  {
    this(new ASN1ObjectIdentifier(CMSObjectIdentifiers.data.getId()), is);
  }

  @Override
  public Object getContent()
  {
    return in;
  }

  @Override
  public void write(OutputStream out) throws IOException, CMSException
  {
    // read the content only one time
    byte[] buffer = new byte[BUFFER_SIZE];
    int c;
    while ((c = in.read(buffer)) != -1)
    {
      out.write(buffer, 0, c);
    }
    in.close();
  }

  @Override
  public ASN1ObjectIdentifier getContentType() {
    return type;
  }
}

Return back input stream in getContent


package com.zyeeda.framework.cxf;

import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.SerializationConfig.Feature;

public class JacksonJsonProvider extends JacksonJaxbJsonProvider {

	public JacksonJsonProvider() {
		ObjectMapper m = this._mapperConfig.getConfiguredMapper();
		if (m == null) {
			m = this._mapperConfig.getDefaultMapper();
		}
		m.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		m.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
	}

}

package com.zyeeda.framework.cxf;

import java.text.SimpleDateFormat;

import org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
import org.codehaus.jackson.map.annotate.JsonSerialize;
import org.codehaus.jackson.map.SerializationConfig.Feature;

public class JacksonJsonProvider extends JacksonJaxbJsonProvider {

	public JacksonJsonProvider() {
		ObjectMapper m = this._mapperConfig.getConfiguredMapper();
		if (m == null) {
			m = this._mapperConfig.getDefaultMapper();
		}
		SerializationConfig sc = m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
		sc.setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		sc.set(Feature.FAIL_ON_EMPTY_BEANS, false);
		m.setSerializationConfig(sc);
		/*
		m.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
		m.configure(Feature.FAIL_ON_EMPTY_BEANS, false);
		m.setSerializationConfig(m.getSerializationConfig().withDateFormat(new SimpleDateFormat("yyyy-MM-dd")));
		*/
	}

}

Make CXF serialize date type in pre-defined format.


package org.edx.mobile.view;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import org.edx.mobile.R;
import org.edx.mobile.base.BaseFragmentActivity;
import org.edx.mobile.util.AppConstants;
import org.edx.mobile.util.NetworkUtil;

public class FindCoursesActivity extends BaseFragmentActivity {

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

        // configure slider layout. This should be called only once and
        // hence is shifted to onCreate() function
        configureDrawer();

        try{
            segIO.screenViewsTracking(getString(R.string.find_courses_title));
        }catch(Exception e){
            logger.error(e);
        }

        if (!(NetworkUtil.isConnected(this))) {
            AppConstants.offline_flag = true;
        }else{
            AppConstants.offline_flag = false;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        setTitle(getString(R.string.find_courses_title));
    }

    @Override
    protected void onOffline() {
        AppConstants.offline_flag = true;
    }

    @Override
    protected void onOnline() {
        AppConstants.offline_flag = false;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        overridePendingTransition(R.anim.slide_in_from_left, R.anim.slide_out_to_right);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        MenuItem checkBox_menuItem = menu.findItem(R.id.delete_checkbox);
        checkBox_menuItem.setVisible(false);
        return true;
    }
}

package org.edx.mobile.view;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import org.edx.mobile.R;
import org.edx.mobile.base.BaseFragmentActivity;
import org.edx.mobile.util.AppConstants;
import org.edx.mobile.util.NetworkUtil;

public class FindCoursesActivity extends BaseFragmentActivity {

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

        // configure slider layout. This should be called only once and
        // hence is shifted to onCreate() function
        configureDrawer();

        try{
            segIO.screenViewsTracking(getString(R.string.find_courses_title));
        }catch(Exception e){
            logger.error(e);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        setTitle(getString(R.string.find_courses_title));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        MenuItem checkBox_menuItem = menu.findItem(R.id.delete_checkbox);
        checkBox_menuItem.setVisible(false);
        return true;
    }
}

Remove code which is already defined in base class


package net.kencochrane.raven;

import org.hamcrest.Matchers;
import org.testng.annotations.Test;

import java.util.ServiceLoader;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;

public class DefaultRavenFactoryTest {
    @Test
    public void checkServiceLoaderProvidesFactory() throws Exception {
        ServiceLoader<RavenFactory> ravenFactories = ServiceLoader.load(RavenFactory.class);

        assertThat(ravenFactories, Matchers.<RavenFactory>hasItem(instanceOf(DefaultRavenFactory.class)));
    }
}

package net.kencochrane.raven;

import org.testng.annotations.Test;

import java.util.ServiceLoader;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.instanceOf;

public class DefaultRavenFactoryTest {
    @Test
    public void checkServiceLoaderProvidesFactory() throws Exception {
        ServiceLoader<RavenFactory> ravenFactories = ServiceLoader.load(RavenFactory.class);

        assertThat(ravenFactories, contains(instanceOf(DefaultRavenFactory.class)));
    }
}

Fix RavenFactoryTest to match the servlet test


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

import com.antonjohansson.lprs.model.User;

/**
 * {@link ITokenSender} implementation that prints the token to the console.
 */
class ConsoleTokenSender implements ITokenSender
{
    @Override
    public void send(User user, String token)
    {
        System.out.println("Generated token '" + token + "'.");
    }
}

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

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

import com.antonjohansson.lprs.model.User;

/**
 * {@link ITokenSender} implementation that prints the token to the console.
 */
class ConsoleTokenSender implements ITokenSender
{
    private static final Logger LOGGER = LoggerFactory.getLogger(ConsoleTokenSender.class);

    @Override
    public void send(User user, String token)
    {
        LOGGER.info("Generated token '{}'", token);
    }
}

Use logger instead of system out


package com.codingchili.router;

import com.codingchili.router.configuration.ListenerSettings;
import com.codingchili.router.configuration.RouterContext;
import com.codingchili.router.controller.RouterHandler;
import com.codingchili.router.controller.transport.*;
import io.vertx.core.*;

import com.codingchili.core.protocol.ClusterNode;

/**
 * @author Robin Duda
 *         root game server, deploys realmName servers.
 */
public class Service extends ClusterNode {
    private RouterContext context;

    public Service(RouterContext context) {
        this.context = context;
    }

    @Override
    public void init(Vertx vertx, Context context) {
        super.init(vertx, context);

        if (context == null) {
            this.context = new RouterContext(vertx);
        }
    }

    @Override
    public void start(Future<Void> start) {
        for (int i = 0; i < settings.getHandlers(); i++) {

            for (ListenerSettings listener : context.transports()) {
                RouterHandler<RouterContext> handler = new RouterHandler<>(context);

                switch (listener.getType()) {
                    case UDP:
                        context.deploy(new UdpListener(handler));
                        break;
                    case TCP:
                        context.deploy(new TcpListener(handler));
                        break;
                    case WEBSOCKET:
                        context.deploy(new WebsocketListener(handler));
                        break;
                    case REST:
                        context.deploy(new RestListener(handler));
                        break;
                }
            }
        }
        start.complete();
    }
}

package com.codingchili.router;

import com.codingchili.router.configuration.ListenerSettings;
import com.codingchili.router.configuration.RouterContext;
import com.codingchili.router.controller.RouterHandler;
import com.codingchili.router.controller.transport.*;
import io.vertx.core.*;

import com.codingchili.core.protocol.ClusterNode;

/**
 * @author Robin Duda
 *         root game server, deploys realmName servers.
 */
public class Service extends ClusterNode {
    private RouterContext context;

    public Service(RouterContext context) {
        this.context = context;
    }

    @Override
    public void init(Vertx vertx, Context context) {
        super.init(vertx, context);

        if (context == null) {
            this.context = new RouterContext(vertx);
        }
    }

    @Override
    public void start(Future<Void> start) {
        for (ListenerSettings listener : context.transports()) {
            RouterHandler<RouterContext> handler = new RouterHandler<>(context);

            for (int i = 0; i < settings.getHandlers(); i++) {
                boolean singleHandlerOnly = false;
                Future<String> future = Future.future();

                switch (listener.getType()) {
                    case UDP:
                        context.deploy(new UdpListener(handler), future);
                        singleHandlerOnly = true;
                        break;
                    case TCP:
                        context.deploy(new TcpListener(handler));
                        break;
                    case WEBSOCKET:
                        context.deploy(new WebsocketListener(handler));
                        break;
                    case REST:
                        context.deploy(new RestListener(handler));
                        break;
                }
                if (singleHandlerOnly) {
                    break;
                }
            }
        }
        start.complete();
    }
}

Deploy a single listener for UDP as port reuse is not supported.


package com.intuso.housemate.client.v1_0.rest;

import com.intuso.housemate.client.v1_0.api.object.System;
import com.intuso.housemate.client.v1_0.rest.model.Page;

import javax.ws.rs.*;

/**
 * Created by tomc on 21/01/17.
 */
@Path("/power")
public interface PowerResource {

    @GET
    @Produces("application/json")
    Page<System.Data> list(@QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("20") int limit);

    @GET
    @Path("/{id}")
    boolean isOn(@PathParam("id") String id);

    @POST
    @Path("/{id}/on")
    void turnOn(@PathParam("id") String id);

    @POST
    @Path("/{id}/off")
    void turnOff(@PathParam("id") String id);
}

package com.intuso.housemate.client.v1_0.rest;

import com.intuso.housemate.client.v1_0.api.object.Device;
import com.intuso.housemate.client.v1_0.rest.model.Page;

import javax.ws.rs.*;

/**
 * Created by tomc on 21/01/17.
 */
@Path("/power")
public interface PowerResource {

    @GET
    @Produces("application/json")
    Page<Device.Data> list(@QueryParam("offset") @DefaultValue("0") int offset, @QueryParam("limit") @DefaultValue("20") int limit);

    @GET
    @Path("/{id}")
    boolean isOn(@PathParam("id") String id);

    @POST
    @Path("/{id}/on")
    void turnOn(@PathParam("id") String id);

    @POST
    @Path("/{id}/off")
    void turnOff(@PathParam("id") String id);
}

Add session utility functions. Re-implement power resource so it loads devices instead of systems


package com.chanryma.fetchtopactivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class ActivityB extends Activity {

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

    public void onButtonClick(View view) {
        Intent intent = new Intent(MyApplication.getInstance().getApplicationContext(), ActivityC.class);
        MyApplication.getInstance().getCurrentActivity().startActivity(intent);
    }
}

package com.chanryma.fetchtopactivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

public class ActivityB extends Activity {

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

    public void onButtonClick(View view) {
//        Intent intent = new Intent(MyApplication.getInstance().getApplicationContext(), ActivityC.class);
//        MyApplication.getInstance().getCurrentActivity().startActivity(intent);

        Intent intent = new Intent(ActivityB.this, ActivityC.class);
        startActivity(intent);
    }
}

Change the way to start ActivityC


package org.realityforge.arez.annotations;

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

/**
 * Methods marked with this annotation are invoked in an Arez transaction.
 */
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface Action
{
  /**
   * Does the action mutate state or not.
   *
   * @return true if method should be wrapped in READ_WRITE transaction, false if it should it should be wrapped in READ_ONLY transaction.
   */
  boolean mutation() default true;
}

package org.realityforge.arez.annotations;

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

/**
 * Methods marked with this annotation are invoked in an Arez transaction.
 */
@Retention( RetentionPolicy.RUNTIME )
@Target( ElementType.METHOD )
public @interface Action
{
  /**
   * Return the name of the Action relative to the container.
   *
   * @return the name of the Action relative to the container.
   */
  String name() default "";

  /**
   * Does the action mutate state or not.
   *
   * @return true if method should be wrapped in READ_WRITE transaction, false if it should it should be wrapped in READ_ONLY transaction.
   */
  boolean mutation() default true;
}

Add ability to name actions


/*
 * Copyright (c) 2014 Ushahidi.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program in the file LICENSE-AGPL. If not, see
 * https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.ui.view;

/**
 * @author Ushahidi Team <team@ushahidi.com>
 */
public interface IDeploymentListView {

}

/*
 * Copyright (c) 2014 Ushahidi.
 *
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program in the file LICENSE-AGPL. If not, see
 * https://www.gnu.org/licenses/agpl-3.0.html
 */

package com.ushahidi.android.ui.view;

import com.ushahidi.android.model.DeploymentModel;

import java.util.List;

/**
 * Renders deployment list views
 *
 * @author Ushahidi Team <team@ushahidi.com>
 */
public interface IDeploymentListView extends ILoadViewData {

    /**
     * Render a deployment list in the UI.
     *
     * @param deploymentModel The collection of {@link DeploymentModel} that will be shown.
     */
    void renderUserList(List<DeploymentModel> deploymentModel);
}

Define renderer for deployment list view


package org.neuralnetwork.synapse;

public abstract class AbstractSynapse<InputType, ValueType> {
	private final InputType input;

	public AbstractSynapse(InputType input) {
		this.input = input;
	}

	abstract protected ValueType readValueFrom(InputType input);

	public ValueType getValue() {
		return readValueFrom(input);
	}
}

package org.neuralnetwork.synapse;

public abstract class AbstractSynapse<InputType, ValueType> {
	private final InputType input;

	public AbstractSynapse(InputType input) {
		this.input = input;
	}

	abstract protected ValueType readValueFrom(InputType input);

	public ValueType getValue() {
		return readValueFrom(input);
	}

	public InputType getInput() {
		return input;
	}
}

Add a getter for the synapses input.


package cucumber.runtime.java.test;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

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

import static org.junit.Assert.assertEquals;

public class SubstitutionStepdefs {
    private static final Map<String, String> ROLES = new HashMap<String, String>() {{
        put("Manager", "now able to manage your employee accounts");
        put("Admin", "able to manage any user account on the system");
    }};

    private String name;
    private String role;
    private String details;

    @Given("^I have a user account with my name \"([^\"]*)\"$")
    public void I_have_a_user_account_with_my_name(String name) throws Throwable {
        this.name = name;
    }

    @When("^an Admin grants me (.+) rights$")
    public void an_Admin_grants_me_role_rights(String role) throws Throwable {
        this.role = role;
        this.details = ROLES.get(role);
    }

    @Then("^I should receive an email with the body:$")
    public void I_should_receive_an_email_with_the_body(String body) throws Throwable {
        String expected = String.format("Dear %s,\n" +
                "You have been granted %s rights.  You are %s. Please be responsible.\n" +
                "-The Admins", name, role, details);
        assertEquals(expected, body);
    }
}

package cucumber.runtime.java.test;

import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;

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

import static org.junit.Assert.assertEquals;

public class SubstitutionStepdefs {
    private static final Map<String, String> ROLES = new HashMap<String, String>() {{
        put("Manager", "now able to manage your employee accounts");
        put("Admin", "able to manage any user account on the system");
    }};

    private String name;
    private String role;
    private String details;

    @Given("^I have a user account with my name \"([^\"]*)\"$")
    public void I_have_a_user_account_with_my_name(String name) throws Throwable {
        this.name = name;
    }

    @When("^an Admin grants me (.+) rights$")
    public void an_Admin_grants_me_role_rights(String role) throws Throwable {
        this.role = role;
        this.details = ROLES.get(role);
    }

    @Then("^I should receive an email with the body:$")
    public void I_should_receive_an_email_with_the_body(String body) throws Throwable {
        String expected = String.format("Dear %s,%n" +
                "You have been granted %s rights.  You are %s. Please be responsible.%n" +
                "-The Admins", name, role, details);
        assertEquals(expected, body);
    }
}

Replace \n with %n so that tests work on Windows.


package ch.tkuhn.nanopub.server;

public class NanopubServerUtils extends org.nanopub.extra.server.NanopubServerUtils {

	// Version numbers have the form MAJOR.MINOR (for example, 0.12 is a newer version than 0.9!)

	public static final String protocolVersion = "0.3";
	public static final int protocolVersionValue = getVersionValue(protocolVersion);

	public static final String journalVersion = "0.3";
	public static final int journalVersionValue = getVersionValue(journalVersion);

}

package ch.tkuhn.nanopub.server;

public class NanopubServerUtils extends org.nanopub.extra.server.NanopubServerUtils {

	// Version numbers have the form MAJOR.MINOR (for example, 0.12 is a newer version than 0.9!)

	public static final String protocolVersion = "0.4";
	public static final int protocolVersionValue = getVersionValue(protocolVersion);

	public static final String journalVersion = "0.3";
	public static final int journalVersionValue = getVersionValue(journalVersion);

}

Increase protocol version number (enforcing UTF-8 now)


package com.gmail.nossr50.commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.player.UserManager;

public class McnotifyCommand implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        switch (args.length) {
            case 0:
                McMMOPlayer mcMMOPlayer = UserManager.getPlayer((Player) sender);

                if (mcMMOPlayer.useChatNotifications()) {
                    sender.sendMessage(LocaleLoader.getString("Commands.Notifications.Off"));
                }
                else {
                    sender.sendMessage(LocaleLoader.getString("Commands.Notifications.On"));
                }

                mcMMOPlayer.toggleChatNotifications();
                return true;

            default:
                return false;
        }
    }
}

package com.gmail.nossr50.commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;

import com.gmail.nossr50.datatypes.player.McMMOPlayer;
import com.gmail.nossr50.locale.LocaleLoader;
import com.gmail.nossr50.util.player.UserManager;

public class McnotifyCommand implements CommandExecutor {
    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        switch (args.length) {
            case 0:
                McMMOPlayer mcMMOPlayer = UserManager.getPlayer(sender.getName());

                if (mcMMOPlayer.useChatNotifications()) {
                    sender.sendMessage(LocaleLoader.getString("Commands.Notifications.Off"));
                }
                else {
                    sender.sendMessage(LocaleLoader.getString("Commands.Notifications.On"));
                }

                mcMMOPlayer.toggleChatNotifications();
                return true;

            default:
                return false;
        }
    }
}

Make /mcnotify match the process of the other commands for getting the mcMMOPlayer object.


package com.jayseeofficial.marvel.rest.model;

import org.apache.commons.lang3.builder.ToStringBuilder;

import java.io.Serializable;

public class Image implements Serializable {
    private String path;
    private String extension;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getExtension() {
        return extension;
    }

    public void setExtension(String extension) {
        this.extension = extension;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}

package com.jayseeofficial.marvel.rest.model;

import org.apache.commons.lang3.builder.ToStringBuilder;

import java.io.Serializable;

public class Image implements Serializable {

    public static final String NOT_FOUND_PATH="https://i.annihil.us/u/prod/marvel/i/mg/b/40/image_not_available";
    public static final String NOT_FOUND_EXTENTION="jpg";

    private String path;
    private String extension;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public String getExtension() {
        return extension;
    }

    public void setExtension(String extension) {
        this.extension = extension;
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }

}

Add constants that can be used for an image when there isn't one avalable.


package org.kefirsf.tk;

import twitter4j.Twitter;
import twitter4j.TwitterException;

/**
 * Utilities for twitter.
 * @author Vitalii Samolovskikh aka Kefir
 */
public final class TwitterUtils {
    public static boolean validate(Twitter twitter){
        boolean flag = false;
        if(twitter!=null){
            try {
                twitter.verifyCredentials();
                flag = true;
            } catch (TwitterException e) {
                // Nothing!
            }
        }
        return flag;
    }

    /**
     * Prevent class initialization.
     */
    private TwitterUtils() {
    }
}

package org.kefirsf.tk;

import twitter4j.Twitter;

/**
 * Utilities for twitter.
 * @author Vitalii Samolovskikh aka Kefir
 */
public final class TwitterUtils {
    public static boolean validate(Twitter twitter){
        boolean flag = false;
        if(twitter!=null){
            try {
                twitter.verifyCredentials();
                flag = true;
            } catch (Throwable e) {
                // Nothing!
            }
        }
        return flag;
    }

    /**
     * Prevent class initialization.
     */
    private TwitterUtils() {
    }
}

Resolve bug with twitter authorization.


package org.geotools.ysld.validate;

import org.geotools.filter.text.cql2.CQLException;
import org.geotools.filter.text.ecql.ECQL;
import org.opengis.filter.Filter;
import org.yaml.snakeyaml.events.ScalarEvent;

public class FilterValidator extends ScalarValidator {
    @Override
    protected String validate(String value, ScalarEvent evt, YsldValidateContext context) {
        try {
            ECQL.toFilter(value);
            return null;
        } catch (CQLException e) {
            return "Invalid filter: " + e.getMessage();
        }
    }
}

package org.geotools.ysld.validate;

import org.geotools.filter.text.cql2.CQLException;
import org.geotools.filter.text.ecql.ECQL;
import org.opengis.filter.Filter;
import org.yaml.snakeyaml.events.ScalarEvent;

public class FilterValidator extends ScalarValidator {
    @Override
    protected String validate(String value, ScalarEvent evt, YsldValidateContext context) {
        try {
            ECQL.toFilter(value);
            return null;
        } catch (CQLException e) {
            return e.getSyntaxError();
        }
    }
}

Use syntax error when validating


package me.nallar.patched;

import net.minecraft.network.TcpConnection;
import net.minecraft.server.ThreadMinecraftServer;
import net.minecraft.util.AxisAlignedBB;

public abstract class PatchTcpReaderThread extends ThreadMinecraftServer {
	final TcpConnection tcpConnection;

	public PatchTcpReaderThread(TcpConnection tcpConnection, String name) {
		super(null, name);
		this.tcpConnection = tcpConnection;
	}

	@Override
	public void run() {
		TcpConnection.field_74471_a.getAndIncrement();

		try {
			while (tcpConnection.isRunning()) {
				while (true) {
					if (!tcpConnection.readNetworkPacket()) {
						AxisAlignedBB.getAABBPool().cleanPool();
						try {
							sleep(2L);
						} catch (InterruptedException ignored) {
						}
					}
				}
			}
		} finally {
			TcpConnection.field_74471_a.getAndDecrement();
		}
	}
}

package me.nallar.patched;

import net.minecraft.network.TcpConnection;
import net.minecraft.server.ThreadMinecraftServer;
import net.minecraft.util.AxisAlignedBB;

public abstract class PatchTcpReaderThread extends ThreadMinecraftServer {
	int count;
	final TcpConnection tcpConnection;

	public PatchTcpReaderThread(TcpConnection tcpConnection, String name) {
		super(null, name);
		this.tcpConnection = tcpConnection;
	}

	@Override
	public void run() {
		TcpConnection.field_74471_a.getAndIncrement();

		try {
			while (tcpConnection.isRunning()) {
				while (true) {
					if (!tcpConnection.readNetworkPacket()) {
						try {
							sleep(2L);
						} catch (InterruptedException ignored) {
						}
					}
					if (count++ % 30 == 0) {
						AxisAlignedBB.getAABBPool().cleanPool();
					}
				}
			}
		} finally {
			TcpConnection.field_74471_a.getAndDecrement();
		}
	}
}

Change AABB pool cleanup timing


package org.springframework.security.ui;

import org.springframework.core.Ordered;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.FilterChain;
import javax.servlet.ServletResponse;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.Filter;
import java.io.IOException;

/**
 * Implements Ordered interface as required by security namespace configuration and implements unused filter
 * lifecycle methods and performs casting of request and response to http versions in doFilter method.
 *
 * @author Luke Taylor
 * @version $Id$
 */
public abstract class SpringSecurityFilter implements Filter, Ordered {

    /**
     * Does nothing. We use IoC container lifecycle services instead.
     *
     * @param filterConfig ignored
     * @throws ServletException ignored
     */
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * Does nothing. We use IoC container lifecycle services instead.
     */
    public void destroy() {
    }

    public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Do we really need the checks on the types in practice ?
        if (!(request instanceof HttpServletRequest)) {
            throw new ServletException("Can only process HttpServletRequest");
        }

        if (!(response instanceof HttpServletResponse)) {
            throw new ServletException("Can only process HttpServletResponse");
        }

        doFilterHttp((HttpServletRequest)request, (HttpServletResponse)response, chain);
    }

    protected abstract void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException;
}

package org.springframework.security.ui;

import org.springframework.core.Ordered;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import javax.servlet.FilterChain;
import javax.servlet.ServletResponse;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.Filter;
import java.io.IOException;

/**
 * Implements Ordered interface as required by security namespace configuration and implements unused filter
 * lifecycle methods and performs casting of request and response to http versions in doFilter method.
 *
 * @author Luke Taylor
 * @version $Id$
 */
public abstract class SpringSecurityFilter implements Filter, Ordered {

    /**
     * Does nothing. We use IoC container lifecycle services instead.
     *
     * @param filterConfig ignored
     * @throws ServletException ignored
     */
    public final void init(FilterConfig filterConfig) throws ServletException {
    }

    /**
     * Does nothing. We use IoC container lifecycle services instead.
     */
    public final void destroy() {
    }

    public final void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        // Do we really need the checks on the types in practice ?
        if (!(request instanceof HttpServletRequest)) {
            throw new ServletException("Can only process HttpServletRequest");
        }

        if (!(response instanceof HttpServletResponse)) {
            throw new ServletException("Can only process HttpServletResponse");
        }

        doFilterHttp((HttpServletRequest)request, (HttpServletResponse)response, chain);
    }

    protected abstract void doFilterHttp(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException;
}

Mark the unused Servlet Container callback methods as final to ensure subclasses do not rely upon them.


package com.scoopit.example;

import com.scoopit.client.ScoopApiExecutionException;
import com.scoopit.client.ScoopClient;
import com.scoopit.model.Post;
import com.scoopit.model.Topic;
import com.scoopit.model.User;

public class GetTopicAndUser {
    public static void main(String[] args) throws ScoopApiExecutionException {
        // get yours on https://www.scoop.it/dev/apps
        ScoopClient scoopit = new ScoopClient("<youapikey>", "<youapisecret>");

        System.out.println("============******===========");
        Topic t = scoopit.getTopic(9014);
        System.out.println(t);
        for (Post p : t.curatedPosts) {
            System.out.println(p);
        }
        System.out.println("============******===========");
        User u = scoopit.getUser(0l);
        System.out.println(u);

        System.out.println("============******===========");
        System.out.println(scoopit.resolveId("fixies", Type.Topic));
        try {
            System.out.println(scoopit.resolveId("some-topic-that-should-,not-exists", Type.Topic));
        } catch (ScoopApiExecutionException e) {
            if (e.response.getCode() == 404) {
                System.out.println("=> not found!");
            }
        }

    }
}

package com.scoopit.example;

import com.scoopit.client.ScoopApiExecutionException;
import com.scoopit.client.ScoopClient;
import com.scoopit.model.Post;
import com.scoopit.model.Topic;
import com.scoopit.model.User;

public class GetTopicAndUser {
    public static void main(String[] args) throws ScoopApiExecutionException {
        // get yours on https://www.scoop.it/dev/apps
        ScoopClient scoopit = new ScoopClient("<youapikey>", "<youapisecret>");

        System.out.println("============******===========");
        Topic t = scoopit.getTopic(9014);
        System.out.println(t);
        for (Post p : t.curatedPosts) {
            System.out.println(p);
        }
        System.out.println("============******===========");
        User u = scoopit.getUser(0l);
        System.out.println(u);

        System.out.println("============******===========");
        System.out.println(scoopit.resolveId("fixies", Type.Topic));
        try {
            System.out.println(scoopit.resolveId("some-topic-that-should-,not-exists", Type.Topic));
        } catch (ScoopApiExecutionException e) {
            if (e.response.getCode() == 404) {
                System.out.println("=> not found!");
            } else {
                throw e;
            }
        }

    }
}

Throw the execution error of not a 404


package com.inepex.ineFrame.client.page;

import java.util.Map;

import com.google.gwt.user.client.ui.Widget;
import com.inepex.ineFrame.client.misc.HandlerAwareLayoutPanel;
import com.inepex.ineFrame.client.navigation.InePlace;

public class LayoutPanelBasedPage extends HandlerAwareLayoutPanel implements InePage{

	protected InePlace currentPlace;

	public LayoutPanelBasedPage() {}

	@Override
	public void setCurrentPlace(InePlace place) {
		this.currentPlace = place;
	}

	@Override
	public void setUrlParameters(Map<String, String> urlParams,
			UrlParamsParsedCallback callback) throws Exception {
		callback.onUrlParamsParsed();
	}

	@Override
	public void onShow() {
		// TODO Auto-generated method stub

	}

	@Override
	public Widget asWidget() {
		return this;
	}

	public InePlace getCurrentPlace() {
		return currentPlace;
	}
}

package com.inepex.ineFrame.client.page;

import java.util.Map;

import org.apache.tools.ant.taskdefs.condition.IsFileSelected;

import com.google.gwt.user.client.ui.Widget;
import com.inepex.ineFrame.client.misc.HandlerAwareLayoutPanel;
import com.inepex.ineFrame.client.navigation.InePlace;

public class LayoutPanelBasedPage extends HandlerAwareLayoutPanel implements InePage{

	protected InePlace currentPlace;
	protected Boolean isFirstShow = true;

	public LayoutPanelBasedPage() {}

	@Override
	public void setCurrentPlace(InePlace place) {
		this.currentPlace = place;
	}

	@Override
	public void setUrlParameters(Map<String, String> urlParams,
			UrlParamsParsedCallback callback) throws Exception {
		callback.onUrlParamsParsed();
	}

	@Override
	public void onShow() {
		if(isFirstShow){
			isFirstShow = false;
			onShow(true);
		}else{
			onShow(false);
		}

	}

	@Override
	public Widget asWidget() {
		return this;
	}

	public InePlace getCurrentPlace() {
		return currentPlace;
	}
	public void onShow(boolean isfirstShow){

	}
}

Add method onShow(boolean) to LayoutPanelbased page. It indicates the first show of the page.


package org.kie.server.swarm.ml;

import java.util.Arrays;

import org.kie.server.swarm.AbstractKieServerMain;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.jaxrs.JAXRSArchive;

public class KieServerMain extends AbstractKieServerMain {

    public static void main(String[] args) throws Exception {
    	Swarm container = new Swarm();

        System.out.println("\tBuilding kie server deployable...");
        JAXRSArchive deployment = createDeployment(container);

        System.out.println("\tStaring Wildfly Swarm....");
        container.start();

        System.out.println("\tConfiguring kjars to be auto deployed to server " + Arrays.toString(args));
        installKJars(args);

        System.out.println("\tDeploying kie server ....");
        container.deploy(deployment);
    }
}

package org.kie.server.swarm.ml;

import java.util.Arrays;
import java.util.HashMap;

import org.kie.server.swarm.AbstractKieServerMain;
import org.wildfly.swarm.Swarm;
import org.wildfly.swarm.config.logging.Level;
import org.wildfly.swarm.jaxrs.JAXRSArchive;
import org.wildfly.swarm.logging.LoggingFraction;

public class KieServerMain extends AbstractKieServerMain {

    public static void main(String[] args) throws Exception {
    	Swarm container = new Swarm();

        System.out.println("\tBuilding kie server deployable...");
        JAXRSArchive deployment = createDeployment(container);

        container.fraction(
            new LoggingFraction()
                .consoleHandler("CONSOLE", c -> {
                    c.level(Level.INFO);
                    c.formatter("%d{HH:mm:ss,SSS} %-5p [%c] (%t) %s%e%n");
                })
                .rootLogger(Level.INFO, "CONSOLE")
        );

        System.out.println("\tStaring Wildfly Swarm....");
        container.start();

        System.out.println("\tConfiguring kjars to be auto deployed to server " + Arrays.toString(args));
        installKJars(args);

        System.out.println("\tDeploying kie server ....");
        container.deploy(deployment);
    }
}

Add Logging configuration into Kie-ML server


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

package org.elasticsearch.action;

import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;

public class DocWriteResponseTests extends ESTestCase {
    public void testGetLocation() {
        DocWriteResponse response = new DocWriteResponse(new ShardId("index", "uuid", 0), "type", "id", 0) {
            // DocWriteResponse is abstract so we have to sneak a subclass in here to test it.
        };
        assertEquals("/index/type/id", response.getLocation(null));
        assertEquals("/index/type/id?routing=test_routing", response.getLocation("test_routing"));
    }
}

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

package org.elasticsearch.action;

import org.elasticsearch.action.DocWriteResponse.Operation;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.test.ESTestCase;

public class DocWriteResponseTests extends ESTestCase {
    public void testGetLocation() {
        DocWriteResponse response = new DocWriteResponse(new ShardId("index", "uuid", 0), "type", "id", 0, Operation.CREATE) {
            // DocWriteResponse is abstract so we have to sneak a subclass in here to test it.
        };
        assertEquals("/index/type/id", response.getLocation(null));
        assertEquals("/index/type/id?routing=test_routing", response.getLocation("test_routing"));
    }
}

Fix unit test build failure


package carpentersblocks.renderer;

import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public class BlockHandlerCarpentersPressurePlate extends BlockHandlerBase {

    @Override
    public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderBlocks)
    {
        renderBlocks.setRenderBounds(0.0F, 0.4375F, 0.0F, 1.0F, 0.5625F, 1.0F);
        super.renderInventoryBlock(block, metadata, modelID, renderBlocks);
    }

}

package carpentersblocks.renderer;

import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.client.renderer.Tessellator;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;

@SideOnly(Side.CLIENT)
public class BlockHandlerCarpentersPressurePlate extends BlockHandlerBase {

    @Override
    public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderBlocks)
    {
        renderBlocks.setRenderBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F);
        Tessellator.instance.addTranslation(0.0F, 0.4365F, 0.0F);
        super.renderInventoryBlock(block, metadata, modelID, renderBlocks);
        Tessellator.instance.addTranslation(0.0F, -0.4365F, 0.0F);
    }

}

Tweak pressure plate inventory rendering.


package org.osgi.service.jaxrs.runtime.dto;

import org.osgi.dto.DTO;

/**
 * Represents information about a JAX-RS resource method.
 *
 * @NotThreadSafe
 * @author $Id$
 */
public class ResourceMethodInfoDTO extends DTO {

	/**
	 * The HTTP verb being handled, for example GET, DELETE, PUT, POST, HEAD,
	 * OPTIONS
	 */
	String	method;

	/**
	 * The mime-type(s) consumed by this resource method, null if not defined
	 */
	String[]	consumingMimeType;

	/**
	 * The mime-type(s) produced by this resource method, null if not defined
	 */
	String[]	producingMimeType;

	/**
	 * The URI of this sub-resource, null if this is not a sub-resource method
	 */
	String	uri;
}

package org.osgi.service.jaxrs.runtime.dto;

import org.osgi.dto.DTO;

/**
 * Represents information about a JAX-RS resource method.
 *
 * @NotThreadSafe
 * @author $Id$
 */
public class ResourceMethodInfoDTO extends DTO {

	/**
	 * The HTTP verb being handled, for example GET, DELETE, PUT, POST, HEAD,
	 * OPTIONS
	 */
	public String	method;

	/**
	 * The mime-type(s) consumed by this resource method, null if not defined
	 */
	public String[]	consumingMimeType;

	/**
	 * The mime-type(s) produced by this resource method, null if not defined
	 */
	public String[]	producingMimeType;

	/**
	 * The URI of this sub-resource, null if this is not a sub-resource method
	 */
	public String	uri;
}

Fix visibility of fields in the ResourceMethodInfo DTO


package org.redline_rpm.header;

public enum Architecture {

	NOARCH,
	I386,
	ALPHA,
	SPARC,
	MIPS,
	PPC,
	M68K,
	IP,
	RS6000,
	IA64,
	SPARC64,
	MIPSEL,
	ARM,
	MK68KMINT,
	S390,
	S390X,
	PPC64,
	SH,
	XTENSA,
	X86_64,
	PPC64LE
}

package org.redline_rpm.header;

public enum Architecture {

	NOARCH,
	I386,
	ALPHA,
	SPARC,
	MIPS,
	PPC,
	M68K,
	IP,
	RS6000,
	IA64,
	SPARC64,
	MIPSEL,
	ARM,
	MK68KMINT,
	S390,
	S390X,
	PPC64,
	SH,
	XTENSA,
	X86_64,
	PPC64LE,
	AARCH64
}

Add AARCH64 as an architecture to support Arm64 platform


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

package com.centurylink.cloud.sdk.tests.mocks;

import com.centurylink.cloud.sdk.tests.TestModule;
import org.mockito.Spy;

import java.lang.reflect.Field;
import java.util.stream.Stream;

/**
 * @author Ilya Drabenia
 */
public class BindSpiesModule extends TestModule {
    private final Object target;

    public BindSpiesModule(Object target) {
        this.target = target;
    }

    @Override
    protected void configure() {
        overrideSpyBinding();
    }

    private void overrideSpyBinding() {
        Stream
            .of(declaredFields())
            .filter(f -> f.isAnnotationPresent(Spy.class))
            .forEach(f ->
                bind(f.getType()).toProvider(new SpyProvider(f.getType())
            )
        );
    }

    private Field[] declaredFields() {
        return target
            .getClass()
            .getDeclaredFields();
    }

}

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

package com.centurylink.cloud.sdk.tests.mocks;

import com.centurylink.cloud.sdk.tests.TestModule;
import org.mockito.Spy;

import java.lang.reflect.Field;
import java.util.stream.Stream;

/**
 * @author Ilya Drabenia
 */
public class BindSpiesModule extends TestModule {
    private final Object target;

    public BindSpiesModule(Object target) {
        this.target = target;
    }

    @Override
    protected void configure() {
        overrideSpyBinding();
    }

    @SuppressWarnings("unchecked")
    private void overrideSpyBinding() {
        Stream
            .of(declaredFields())
            .filter(f -> f.isAnnotationPresent(Spy.class))
            .forEach(f ->
                bind(f.getType()).toProvider(new SpyProvider(f.getType())
            )
        );
    }

    private Field[] declaredFields() {
        return target
            .getClass()
            .getDeclaredFields();
    }

}

Fix compilation issue on not latest JDKs


package com.marklogic.hector;

import com.marklogic.spring.batch.columnmap.ColumnMapSerializer;
import org.apache.commons.lang3.StringEscapeUtils;

import java.util.Map;

public class XmlStringColumnMapSerializer implements ColumnMapSerializer {

    @Override
    public String serializeColumnMap(Map<String, Object> columnMap, String rootLocalName) {
        String content = "";
        String rootName = rootLocalName.length() == 0 ? "record" : rootLocalName;
        content = "<" + rootName + ">\n";

        for (Map.Entry<String, Object> entry : transformColumnMap(columnMap).entrySet()) {
            String elName = entry.getKey().replaceAll("[^A-Za-z0-9]", "");
            content += "<" + elName + ">" + StringEscapeUtils.escapeXml11(entry.getValue().toString()) + "</" + elName + ">\n";
        }

        content += "</" + rootName + ">";
        return content;
    }

    //The strategy is to extend this class and overwrite this method.
    protected Map<String, Object> transformColumnMap(Map<String, Object> columnMap) {
        return columnMap;
    }

}

package com.marklogic.hector;

import com.marklogic.spring.batch.columnmap.ColumnMapSerializer;
import org.apache.commons.lang3.StringEscapeUtils;

import java.util.Map;

public class XmlStringColumnMapSerializer implements ColumnMapSerializer {

    @Override
    public String serializeColumnMap(Map<String, Object> columnMap, String rootLocalName) {
        String content = "";
        String rootName = rootLocalName.length() == 0 ? "record" : rootLocalName;
        content = "<" + rootName + ">\n";

        for (Map.Entry<String, Object> entry : transformColumnMap(columnMap).entrySet()) {
            String elName = entry.getKey().replaceAll("[^A-Za-z0-9\\_\\-]", "");
            content += "<" + elName + ">" + StringEscapeUtils.escapeXml11(entry.getValue().toString()) + "</" + elName + ">\n";
        }

        content += "</" + rootName + ">";
        return content;
    }

    //The strategy is to extend this class and overwrite this method.
    protected Map<String, Object> transformColumnMap(Map<String, Object> columnMap) {
        return columnMap;
    }

}

Allow underscores and dashes in element names


package org.ingrahamrobotics.robottables.api;

public enum UpdateAction {
    /**
     * Used when a key is assigned a value for the first time in this client
     */
    NEW,
    /**
     * Used when a key is already known to the client, and is updated
     */
    UPDATE,
    /**
     * Used when a key is deleted
     */
    DELETE;
}

package org.ingrahamrobotics.robottables.api;

public enum UpdateAction {
    /**
     * Used when a key is assigned a value for the first time in this client
     */
    NEW,
    /**
     * Used when a key is already known to the client, and is updated
     */
    UPDATE,
    /**
     * Used when a key is deleted
     */
    DELETE,
}

Remove semicolon! minor, minor, and even more minor.


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

import com.intellij.openapi.actionSystem.DataContext;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Eugene Zhuravlev
 */
public abstract class PromptingMacro extends Macro{

  @Override
  public final String expand(@NotNull DataContext dataContext) throws ExecutionCancelledException {
    final String userInput = promptUser(dataContext);
    if (userInput == null) {
      throw new ExecutionCancelledException();
    }
    return userInput;
  }

  /**
   * Called from expand() method
   *
   * @param dataContext
   * @return user input. If null is returned, ExecutionCancelledException is thrown by expand() method
   */
  @Nullable
  protected abstract String promptUser(DataContext dataContext);
}

// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.macro;

import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Ref;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author Eugene Zhuravlev
 */
public abstract class PromptingMacro extends Macro{

  @Override
  public final String expand(@NotNull DataContext dataContext) throws ExecutionCancelledException {
    Ref<String> userInput = Ref.create();
    ApplicationManager.getApplication().invokeAndWait(() -> userInput.set(promptUser(dataContext)));
    if (userInput.isNull()) {
      throw new ExecutionCancelledException();
    }
    return userInput.get();
  }

  /**
   * Called from expand() method
   *
   * @param dataContext
   * @return user input. If null is returned, ExecutionCancelledException is thrown by expand() method
   */
  @Nullable
  protected abstract String promptUser(DataContext dataContext);
}

Support expanding prompting macro not from EDT (GO-9289)


// Copyright (c) 2012 Microsoft Corporation.  All rights reserved.

package tlc2.tool.fp;

import java.io.IOException;

import tlc2.tool.fp.DiskFPSet;
import tlc2.tool.fp.FPSet;
import tlc2.tool.fp.MSBDiskFPSet;

public class MultiThreadedMSBDiskFPSetTest extends MultiThreadedFPSetTest {

	/* (non-Javadoc)
	 * @see tlc2.tool.fp.AbstractFPSetTest#getFPSet(long)
	 */
	@Override
	protected FPSet getFPSet(long freeMemoryInBytes) throws IOException {
		long maxInMemoryCapacity = freeMemoryInBytes / (long) DiskFPSet.LongSize;
		return new MSBDiskFPSet(maxInMemoryCapacity >> 10);
	}
}

// Copyright (c) 2012 Microsoft Corporation.  All rights reserved.

package tlc2.tool.fp;

import java.io.IOException;

import tlc2.tool.fp.DiskFPSet;
import tlc2.tool.fp.FPSet;
import tlc2.tool.fp.MSBDiskFPSet;

public class MultiThreadedMSBDiskFPSetTest extends MultiThreadedFPSetTest {

	/* (non-Javadoc)
	 * @see tlc2.tool.fp.AbstractFPSetTest#getFPSet(long)
	 */
	@Override
	protected FPSet getFPSet(long freeMemoryInBytes) throws IOException {
		long maxInMemoryCapacity = freeMemoryInBytes / (long) DiskFPSet.LongSize;
		return new MSBDiskFPSet(maxInMemoryCapacity);
	}
}

Remove accidentally committed div by 1024 added for debugging purpose only


package com.basgeekball.awesomevalidation.utility;

public class RegexTemplate {

    public static final String TELEPHONE = "(^\\+)?[0-9()-]*";

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

package com.basgeekball.awesomevalidation.utility;

public class RegexTemplate {

    public static final String NOT_EMPTY = "^(?=\\s*\\S).*$";
    public static final String TELEPHONE = "(^\\+)?[0-9()-]*";

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

Add a regex constant for checking empty field.


package com.gh4a.model;

import io.reactivex.Single;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface GitHubFeedService {
    @GET("{url}")
    Single<Response<GitHubFeed>> getFeed(@Path(value = "url", encoded = true) String url);

    @GET("https://github.blog/feed/atom/")
    Single<Response<GitHubFeed>> getBlogFeed();
}

package com.gh4a.model;

import io.reactivex.Single;
import retrofit2.Response;
import retrofit2.http.GET;
import retrofit2.http.Path;

public interface GitHubFeedService {
    @GET("{url}")
    Single<Response<GitHubFeed>> getFeed(@Path(value = "url", encoded = true) String url);

    @GET("https://github.blog/all.atom")
    Single<Response<GitHubFeed>> getBlogFeed();
}

Revert "Update GitHub blog feed URL"


package net.squanchy.about;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;

import net.squanchy.R;
import net.squanchy.fonts.TypefaceStyleableActivity;
import net.squanchy.navigation.Navigator;

public class AboutActivity extends TypefaceStyleableActivity {

    private static final String SQUANCHY_WEBSITE = "https://squanchy.net";
    private static final String SQUANCHY_GITHUB = "https://github.com/rock3r/squanchy";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_about);

        setupToolbar();

        Navigator navigator = AboutInjector.obtain(this)
                .navigator();

        findViewById(R.id.website_button).setOnClickListener(
                view -> navigator.toExternalUrl(SQUANCHY_WEBSITE)
        );

        findViewById(R.id.github_button).setOnClickListener(
                view -> navigator.toExternalUrl(SQUANCHY_GITHUB)
        );

        findViewById(R.id.foss_button).setOnClickListener(
                view -> navigator.toFossLicenses()
        );
    }

    private void setupToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
}

package net.squanchy.about;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;

import net.squanchy.R;
import net.squanchy.fonts.TypefaceStyleableActivity;
import net.squanchy.navigation.Navigator;

public class AboutActivity extends TypefaceStyleableActivity {

    private static final String SQUANCHY_WEBSITE = "https://squanchy.net";
    private static final String SQUANCHY_GITHUB = "https://github.com/rock3r/squanchy";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_about);

        setupToolbar();

        Navigator navigator = AboutInjector.obtain(this)
                .navigator();

        findViewById(R.id.website_button).setOnClickListener(
                view -> navigator.toExternalUrl(SQUANCHY_WEBSITE)
        );

        findViewById(R.id.github_button).setOnClickListener(
                view -> navigator.toExternalUrl(SQUANCHY_GITHUB)
        );

        findViewById(R.id.foss_button).setOnClickListener(
                view -> navigator.toFossLicenses()
        );
    }

    private void setupToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Handle up button in about screen toolbar


package com.fabricio.vergal.RNWorkers;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class RNWorkersPackage implements ReactPackage {

    @Override
    public List<Class<? extends JavaScriptModule>> createJSModules() {
        return Collections.emptyList();
    }

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Arrays.<NativeModule>asList(
            new RNWorkersModule(reactContext)
        );
    }
}

package com.fabricio.vergal.RNWorkers;

import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;

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

public class RNWorkersPackage implements ReactPackage {

    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }

    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Arrays.<NativeModule>asList(
            new RNWorkersModule(reactContext)
        );
    }
}

Remove `@Override` of `createJSModules()`, removed in RN 0.47


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

package android.support.design.widget;

import android.content.Context;
import android.support.v7.widget.AppCompatImageButton;
import android.util.AttributeSet;

class VisibilityAwareImageButton extends AppCompatImageButton {

    private int mUserSetVisibility;

    public VisibilityAwareImageButton(Context context) {
        this(context, null);
    }

    public VisibilityAwareImageButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VisibilityAwareImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mUserSetVisibility = getVisibility();
    }

    @Override
    public void setVisibility(int visibility) {
        internalSetVisibility(visibility, true);
    }

    final void internalSetVisibility(int visibility, boolean fromUser) {
        super.setVisibility(visibility);
        if (fromUser) {
            mUserSetVisibility = visibility;
        }
    }

    final int getUserSetVisibility() {
        return mUserSetVisibility;
    }
}

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

package android.support.design.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageButton;

class VisibilityAwareImageButton extends ImageButton {

    private int mUserSetVisibility;

    public VisibilityAwareImageButton(Context context) {
        this(context, null);
    }

    public VisibilityAwareImageButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VisibilityAwareImageButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mUserSetVisibility = getVisibility();
    }

    @Override
    public void setVisibility(int visibility) {
        internalSetVisibility(visibility, true);
    }

    final void internalSetVisibility(int visibility, boolean fromUser) {
        super.setVisibility(visibility);
        if (fromUser) {
            mUserSetVisibility = visibility;
        }
    }

    final int getUserSetVisibility() {
        return mUserSetVisibility;
    }
}

Fix crash in FAB background tint am: 9d42ab847a


package edu.columbia.cs.psl.test.phosphor;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class LambdaIntTagITCase {
	@Test
	public void testCollectors() throws Exception{
		List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
		givenList.stream().collect(Collectors.toList());

	}
	@Test
	public void testEmptyLambda() throws Exception {
		Runnable r = () -> {
		};
	}

	@Test
	public void testIntStreamsDontCrash() throws Exception {
		int sum = IntStream.of(1, 2, 3, 4, 5).sum(); //creates a bunch of lambdas
	}

	@Test
	public void testSupplier() throws Exception {
		Supplier<double[]> supplier = () -> new double[3];
		double[] d = supplier.get();
	}
}

package edu.columbia.cs.psl.test.phosphor;

import org.junit.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class LambdaIntTagITCase {

	// This is known to not work correctly on int tags. It may never be possible to make it work completely on int tags, because
	// we need to add a fake parameter to every modified constructor to make sure that it is unique. But, we can't do that
	// for cases where INVOKEDYNAMIC binds a constructor to a non-constructor call (although maybe we can fix this, not enough
	// time to look into it now)
//	@Test
//	public void testCollectors() throws Exception{
//		List<String> givenList = Arrays.asList("a", "bb", "ccc", "dd");
//		givenList.stream().collect(Collectors.toList());
//
//	}
	@Test
	public void testEmptyLambda() throws Exception {
		Runnable r = () -> {
		};
	}

	@Test
	public void testIntStreamsDontCrash() throws Exception {
		int sum = IntStream.of(1, 2, 3, 4, 5).sum(); //creates a bunch of lambdas
	}

	@Test
	public void testSupplier() throws Exception {
		Supplier<double[]> supplier = () -> new double[3];
		double[] d = supplier.get();
	}
}

Disable int tag collectors test


package com.salvadordalvik.something;

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

/**
 * Created by matthewshepard on 1/31/14.
 */
public class LoginActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        setTitle(R.string.login_activity_title);
    }
}

package com.salvadordalvik.something;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;

/**
 * Created by matthewshepard on 1/31/14.
 */
public class LoginActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_activity);
        setTitle(R.string.login_activity_title);
    }
}

Update log inactivity to match fragment support.


package org.zalando.nakadi.service.subscription.state;

import org.zalando.nakadi.service.subscription.StreamingContext;

import javax.annotation.Nullable;
import java.io.IOException;

public class CleanupState extends State {
    private final Exception exception;

    public CleanupState(@Nullable final Exception e) {
        this.exception = e;
    }

    CleanupState() {
        this(null);
    }

    @Override
    public void onEnter() {
        try {
            getContext().unregisterAuthorizationUpdates();
        } catch (final RuntimeException ex) {
            getLog().error("Unexpected fail during removing callback for registration updates", ex);
        }
        try {
            if (null != exception) {
                getOut().onException(exception);
            }
        } finally {
            try {
                getContext().unregisterSession();

            } finally {
                switchState(StreamingContext.DEAD_STATE);
            }

            try {
                getContext().getZkClient().close();
            } catch (final IOException e) {
                getLog().error("Unexpected fail to release zk connection", e);
            }
            getContext().getCurrentSpan().finish();
        }
    }
}

package org.zalando.nakadi.service.subscription.state;

import org.zalando.nakadi.service.subscription.StreamingContext;

import javax.annotation.Nullable;
import java.io.IOException;

public class CleanupState extends State {
    private final Exception exception;

    public CleanupState(@Nullable final Exception e) {
        this.exception = e;
    }

    CleanupState() {
        this(null);
    }

    @Override
    public void onEnter() {
        try {
            getContext().unregisterAuthorizationUpdates();
        } catch (final RuntimeException ex) {
            getLog().error("Unexpected fail during removing callback for registration updates", ex);
        }
        try {
            if (null != exception) {
                getOut().onException(exception);
            }
        } finally {
            try {
                getContext().unregisterSession();

            } finally {
                if (null != exception) {
                    getContext().switchStateImmediately(StreamingContext.DEAD_STATE);
                } else{
                    switchState(StreamingContext.DEAD_STATE);
                }
            }

            try {
                getContext().getZkClient().close();
            } catch (final IOException e) {
                getLog().error("Unexpected fail to release zk connection", e);
            }
            getContext().getCurrentSpan().finish();
        }
    }
}

Switch state immediately to DEAD state/do not schedule it


package com.example.android.sunshine.app;

import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.widget.TextView;

public class MainActivity extends Activity {

    private TextView mTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub stub) {
                mTextView = (TextView) stub.findViewById(R.id.text);
            }
        });
    }
}

package com.example.android.sunshine.app;

import android.app.Activity;
import android.os.Bundle;
import android.support.wearable.view.WatchViewStub;
import android.widget.TextView;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MainActivity extends Activity {

    private TextView mTime;
    private TextView mDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
        stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
            @Override
            public void onLayoutInflated(WatchViewStub stub) {
                mTime = (TextView) stub.findViewById(R.id.time);
                mDate = (TextView) stub.findViewById(R.id.date);

                mTime.setText(getCurrentTime());
                mDate.setText(getCurrentDate());
            }
        });
    }

    private String getCurrentTime() {
        Calendar cal = Calendar.getInstance();
        DateFormat date = new SimpleDateFormat("HH:mm");
        date.setTimeZone(cal.getTimeZone());
        return date.format(cal.getTime());
    }

    private String getCurrentDate() {
        Calendar cal = Calendar.getInstance();
        DateFormat date = new SimpleDateFormat("EEE, MMM dd yyyy");
        date.setTimeZone(cal.getTimeZone());
        return date.format(cal.getTime()).toUpperCase();
    }
}

Set current time and date