package edu.stuy.commands;

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

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

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

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

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

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

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

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

package edu.stuy.commands;

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

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

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

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

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

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

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

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

Fix logic for operator pad

Fix logic for operator pad


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.afs.commands;

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

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

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

    }

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

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

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

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

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.afs.commands;

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

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

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

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

    }

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

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

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

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

Add shot range indication while driving manually.


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

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

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

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

    private ObjectMapper mapper = new ObjectMapper();

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

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

}

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

import com.fasterxml.jackson.databind.ObjectMapper;

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

@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

    private ObjectMapper mapper = new ObjectMapper();

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

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

}

Update JSON serialization date format

Update JSON serialization date format


package org.knowm.xchange.interceptor;

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

public class InterceptorProvider {

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

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

Add possibility to use custom Interceptors


package pl.komunikator.komunikator;

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import pl.komunikator.komunikator.entity.User;

/**
 * Created by adrian on 19.04.2017.
 */

public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> {

    private List<User> userList;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView name, email;
        public ImageView photo;

        public MyViewHolder(View view) {
            super(view);

            name = (TextView) view.findViewById(R.id.contactName);
            email = (TextView) view.findViewById(R.id.contactEmail);
            photo = (ImageView) view.findViewById(R.id.contactImageView);
        }
    }

    public SearchedUsersAdapter(List<User> userList) {
        this.userList = userList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {

    }

    @Override
    public int getItemCount() {
        return 0;
    }

}

package pl.komunikator.komunikator;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import pl.komunikator.komunikator.entity.User;

/**
 * Created by adrian on 19.04.2017.
 */

public class SearchedUsersAdapter extends RecyclerView.Adapter<SearchedUsersAdapter.MyViewHolder> {

    private List<User> userList;

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView name, email;
        public ImageView photo;

        public MyViewHolder(View view) {
            super(view);

            name = (TextView) view.findViewById(R.id.contactName);
            email = (TextView) view.findViewById(R.id.contactEmail);
            photo = (ImageView) view.findViewById(R.id.contactImageView);
        }
    }

    public SearchedUsersAdapter(List<User> userList) {
        this.userList = userList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_searched_user, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        User user = userList.get(position);
        holder.name.setText(user.getUsername());
        holder.email.setText(user.getEmail());
    }

    @Override
    public int getItemCount() {
        return userList.size();
    }

}

Implement the rest of the methods

Implement the rest of the methods


package rxbroadcast;

import nl.jqno.equalsverifier.EqualsVerifier;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;

@SuppressWarnings({"checkstyle:MagicNumber"})
public final class VectorTimestampTest {
    @Test
    public final void equalsContract() {
        EqualsVerifier.forClass(VectorTimestamp.class)
            .withCachedHashCode("hashCode", "computeHashCode", new VectorTimestamp(
                new Sender[]{new Sender(new byte[] {42}), new Sender(new byte[]{43})}, new long[]{1, 2}
            ))
            .verify();
    }

    @Test(expected = IllegalArgumentException.class)
    public final void timestampMustHaveEqualLengthFields() {
        final VectorTimestamp t = new VectorTimestamp(new Sender[0], new long[]{3, 4});
        Assert.assertThat(t, CoreMatchers.notNullValue());
    }
}

package rxbroadcast;

import nl.jqno.equalsverifier.EqualsVerifier;
import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Test;

@SuppressWarnings({"checkstyle:MagicNumber"})
public final class VectorTimestampTest {
    @Test
    public final void equalsContract() {
        EqualsVerifier.forClass(VectorTimestamp.class)
            .withCachedHashCode("hashCode", "computeHashCode", new VectorTimestamp(
                new Sender[]{new Sender(new byte[] {42}), new Sender(new byte[]{43})}, new long[]{1, 2}
            ))
            .verify();
    }

    @Test(expected = IllegalArgumentException.class)
    public final void timestampMustHaveEqualLengthFields() {
        Assert.assertThat(new VectorTimestamp(new Sender[0], new long[]{3, 4}), CoreMatchers.anything());
    }
}

Use CoreMatchers.anything where it makes sense


package rabbit;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class ApplicationStatusChecker {

    public HttpStatus checkStatus(String url) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<?> response = restTemplate.getForEntity(url, null);
        return response.getStatusCode();
    }
}

package rabbit;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class ApplicationStatusChecker {

    public String checkStatus(String url) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<?> response = restTemplate.getForEntity(url, String.class);
        return "statusCode: " + response.getStatusCode() +"\nbody: " + response.getBody();
    }

}

Return status code and body for HTTP request.


package cgeo.geocaching.sensors;

import static org.assertj.core.api.Assertions.assertThat;

import cgeo.geocaching.MainActivity;
import cgeo.geocaching.utils.AngleUtils;

import android.test.ActivityInstrumentationTestCase2;

public class SensorsTest extends ActivityInstrumentationTestCase2<MainActivity> {

    public SensorsTest() {
        super(MainActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
    }

    public static void testGetDirectionNow() {
        final float angle = AngleUtils.getDirectionNow(1.0f);
        assertThat(angle == 1.0f || angle == 91.0f || angle == 181.0f || angle == 271.0f).isTrue();
    }

}

package cgeo.geocaching.sensors;

import static org.assertj.core.api.Assertions.assertThat;

import cgeo.geocaching.MainActivity;
import cgeo.geocaching.utils.AngleUtils;

import rx.Observable;

import android.test.ActivityInstrumentationTestCase2;

import java.util.concurrent.TimeUnit;

public class SensorsTest extends ActivityInstrumentationTestCase2<MainActivity> {

    private Sensors sensors;

    public SensorsTest() {
        super(MainActivity.class);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        sensors = Sensors.getInstance();
    }

    public static void testGetDirectionNow() {
        final float angle = AngleUtils.getDirectionNow(1.0f);
        assertThat(angle == 1.0f || angle == 91.0f || angle == 181.0f || angle == 271.0f).isTrue();
    }

    private static <T> void testDataAvailability(final Observable<T> observable) {
        try {
            observable.timeout(200, TimeUnit.MILLISECONDS).first().toBlocking().single();
        } catch (final Exception ignored) {
            fail("timeout while waiting for sensor data");
        }
    }

    public void testDirectionObservable() {
        testDataAvailability(sensors.directionObservable());
    }

    public void testGeodataObservable() {
        testDataAvailability(sensors.geoDataObservable(false));
        testDataAvailability(sensors.geoDataObservable(true));
    }

}

Check that a position and an orientation are always immediately available


package com.hubspot.singularity;

import java.util.Objects;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;

public class SingularityUserSettings {
  private final Set<String> starredRequestIds;

  @JsonCreator
  public SingularityUserSettings(@JsonProperty("starredRequestIds") Set<String> starredRequestIds) {
    this.starredRequestIds = starredRequestIds;
  }

  public Set<String> getStarredRequestIds() {
    return starredRequestIds;
  }

  @Override
  public String toString() {
    return "SingularityUserSettings[" +
        "starredRequestIds=" + starredRequestIds +
        ']';
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    SingularityUserSettings that = (SingularityUserSettings) o;
    return Objects.equals(starredRequestIds, that.starredRequestIds);
  }

  @Override
  public int hashCode() {
    return Objects.hash(starredRequestIds);
  }
}

package com.hubspot.singularity;

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

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Objects;

public class SingularityUserSettings {
  private final String userId;
  private final Set<String> starredRequestIds;

  @JsonCreator
  public SingularityUserSettings(
      @JsonProperty("userId") String userId,
      @JsonProperty("starredRequestIds") Set<String> starredRequestIds) {
    this.userId = userId;
    this.starredRequestIds = Objects.firstNonNull(starredRequestIds, Collections.<String>emptySet());
  }

  public String getUserId() {
    return userId;
  }

  public Set<String> getStarredRequestIds() {
    return starredRequestIds;
  }

  public SingularityUserSettings addStarredRequestIds(Set<String> newStarredRequestIds) {
    starredRequestIds.addAll(newStarredRequestIds);
    return this;
  }

  public SingularityUserSettings deleteStarredRequestIds(Set<String> oldStarredRequestIds) {
    starredRequestIds.removeAll(oldStarredRequestIds);
    return this;
  }

  @Override
  public String toString() {
    return "SingularityUserSettings[" +
        "userId=" + userId +
        ", starredRequestIds=" + starredRequestIds +
        ']';
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    SingularityUserSettings that = (SingularityUserSettings) o;

    if (!Objects.equal(userId, that.userId)) {
      return false;
    }
    if (!Objects.equal(starredRequestIds, that.starredRequestIds)) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(userId, starredRequestIds);
  }
}

Add add/delete starred requests methods to UserSettings, add userId, fix deps


/*
 * Copyright 2011 Matthew Avery, mavery@advancedpwr.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.advancedpwr.record.methods;

public class StringBuilder extends AbstractPrimitiveBuilder
{

	public String resultBuilder()
	{
		return "\"" + result().replaceAll( "\n", "\\\\n" ).replaceAll( "\r", "\\\\r" ) + "\"";
	}

}

/*
 * Copyright 2011 Matthew Avery, mavery@advancedpwr.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.advancedpwr.record.methods;

public class StringBuilder extends AbstractPrimitiveBuilder
{

	public String resultBuilder()
	{
		return "\"" + result().replaceAll( "\n", "\\\\n" ).replaceAll( "\r", "\\\\r" ).replaceAll( "\"", "\\\\\"" ) + "\"";
	}

}

Support double quotes in strings.

Support double quotes in strings.


package interdroid.vdb.persistence.ui;

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

import interdroid.vdb.R;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class VdbPreferences extends PreferenceActivity {
	private static final Logger logger = LoggerFactory
			.getLogger(VdbPreferences.class);

    public static final String PREFERENCES_NAME = "interdroid.vdb_preferences";

    // If you change these change the android:key value in vdb_preferences.xml
    public static final String PREF_SHARING_ENABLED = "sharingEnabled";
    public static final String PREF_NAME = "name";
    public static final String PREF_EMAIL = "email";

    // TODO: Add listener to synch toggle and start and stop service based on that.

	@Override
    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.vdb_preferences);
            logger.debug("Storing preferences to: " + getPreferenceManager().getSharedPreferencesName());
    }
}

package interdroid.vdb.persistence.ui;

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

import interdroid.vdb.R;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceActivity;

public class VdbPreferences extends PreferenceActivity {
	private static final Logger logger = LoggerFactory.getLogger(VdbPreferences.class);

	public static final String PREFERENCES_NAME = "interdroid.vdb_preferences";

	// If you change these change the android:key value in vdb_preferences.xml
	public static final String PREF_SHARING_ENABLED = "sharingEnabled";
	public static final String PREF_NAME = "name";
	public static final String PREF_EMAIL = "email";

	// TODO: Add listener to synch toggle and start and stop service based on that.

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.vdb_preferences);
		logger.debug("Storing preferences to: " + getPreferenceManager().getSharedPreferencesName());
		SharedPreferences prefs = getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE);
		if (prefSet(prefs, PREF_NAME) && prefSet(prefs, PREF_EMAIL)) {
			setResult(RESULT_OK);
		} else {
			setResult(RESULT_CANCELED);
		}
	}

	private boolean prefSet(SharedPreferences prefs, String prefName) {
		// Has preference which is not null or the empty string
		return prefs.contains(prefName) &&
		null != prefs.getString(prefName, null) &&
		!"".equals(prefs.getString(prefName, ""));
	}
}

Return result and whitespace fixes.

Return result and whitespace fixes.


package com.maddenabbott.jenny;

/**
 * The main entry point for Jenny.
 */
public class Application {
  private static final String defaultCommand = "help";

  public static void main(String[] args) {
    String commandName = getCommandName(args, defaultCommand);
  }

  private static String getCommandName(final String[] args, final String defaultCommandName) {
    if (args.length > 0 && args[0] != null) {
      return args[0];
    } else {
      return defaultCommandName;
    }
  }
  }

package com.maddenabbott.jenny;

import java.util.Arrays;

/**
 * The main entry point for Jenny.
 */
public class Application {
  private static final String defaultCommand = "help";

  public static void main(String[] args) {
    String commandName = getCommandName(args, defaultCommand);
    String[] parameters = getParameters(args);
  }

  private static String getCommandName(final String[] args, final String defaultCommandName) {
    if (args.length > 0 && args[0] != null) {
      return args[0];
    } else {
      return defaultCommandName;
    }
  }

  private static String[] getParameters(final String[] args) {
    if (args.length > 1) {
      return Arrays.copyOfRange(args, 1, args.length);
    }
    return new String[]{ };
  }
  }

Add method to extract parameters from command line args.


package failchat.core;

import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MessageObjectCleaner implements MessageHandler {

    public static final Pattern pattern = Pattern.compile("\\{!\\d{1,3}\\}");
    private static volatile MessageObjectCleaner instance;

    private MessageObjectCleaner() {

    }

    public static MessageObjectCleaner getInstance() {
        MessageObjectCleaner localInstance = instance;
        if (localInstance == null) {
            synchronized (MessageObjectCleaner.class) {
                localInstance = instance;
                if (localInstance == null) {
                    instance = localInstance = new MessageObjectCleaner();
                }
            }
        }
        return localInstance;
    }

    private static final Logger logger = Logger.getLogger(MessageObjectCleaner.class.getName());

    @Override
    public void handleMessage(Message message) {
        Matcher m = pattern.matcher(message.getText());
        if (m.find()) {
            logger.fine("Message cleaned - " + message.getAuthor() + ": " + message.getText());
            message.setText(m.replaceAll(""));
        }
    }
}

package failchat.core;

import java.util.logging.Logger;
/**
 * Заменяет символы { и } на html entity
 * */
public class MessageObjectCleaner implements MessageHandler {
    private static volatile MessageObjectCleaner instance;
    private static final Logger logger = Logger.getLogger(MessageObjectCleaner.class.getName());

    private MessageObjectCleaner() {

    }

    public static MessageObjectCleaner getInstance() {
        MessageObjectCleaner localInstance = instance;
        if (localInstance == null) {
            synchronized (MessageObjectCleaner.class) {
                localInstance = instance;
                if (localInstance == null) {
                    instance = localInstance = new MessageObjectCleaner();
                }
            }
        }
        return localInstance;
    }

    @Override
    public void handleMessage(Message message) {
        String mes = message.getText();
        mes = mes.replaceAll("\\{", "{");
        mes = mes.replaceAll("}", "}");
        message.setText(mes);
    }
}

Replace characters { and } for html entities


package org.codehaus.modello.metadata;

/*
 * LICENSE
 */

import org.codehaus.modello.AbstractLogEnabled;
import org.codehaus.modello.Model;
import org.codehaus.modello.ModelClass;
import org.codehaus.modello.ModelField;
import org.codehaus.modello.ModelloException;

import java.util.Map;

/**
 * @author Trygve Laugstøl
 * @version $Id$
 */
public abstract class AbstractMetaDataPlugin
    extends AbstractLogEnabled
    implements MetaDataPlugin
{
    public MetaData getModelMetaData( Model model )
    {
        return null;
    }

    public MetaData getClassMetaData( ModelClass clazz )
    {
        return null;
    }

    public MetaData getFieldMetaData( ModelField field )
    {
        return null;
    }

    public Map getModelMap( Model model, MetaData metaData )
        throws ModelloException
    {
        return null;
    }

    public Map getClassMap( ModelClass clazz, MetaData metaData )
        throws ModelloException
    {
        return null;
    }

    public Map getFieldMap( ModelField field, MetaData metaData )
        throws ModelloException
    {
        return null;
    }
}

package org.codehaus.modello.metadata;

/*
 * LICENSE
 */

import org.codehaus.modello.AbstractLogEnabled;
import org.codehaus.modello.Model;
import org.codehaus.modello.ModelClass;
import org.codehaus.modello.ModelField;
import org.codehaus.modello.ModelloException;

import java.util.Map;

/**
 * @author Trygve Laugstøl
 * @version $Id$
 */
public abstract class AbstractMetaDataPlugin
    extends AbstractLogEnabled
    implements MetaDataPlugin
{
    public Map getModelMap( Model model, MetaData metaData )
        throws ModelloException
    {
        return null;
    }

    public Map getClassMap( ModelClass clazz, MetaData metaData )
        throws ModelloException
    {
        return null;
    }

    public Map getFieldMap( ModelField field, MetaData metaData )
        throws ModelloException
    {
        return null;
    }
}

Remove methods implementation that must be do in subclasses.


package es.ganchix.morphia.utils;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.mongodb.morphia.utils.ReflectionUtils;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.IOException;

/**
 * Created by Rafael Ríos on 5/05/17.
 */

@RunWith(PowerMockRunner.class)
@PrepareForTest(ReflectionUtils.class)
public class MorphiaFailUtilsTest {

    private final String PACKAGE_NAME = "es.ganchix.morphia.utils.context.normal";

    @Test(expected = Exception.class)
    public void testCallGetClassesWithFail_ShouldReturnAException() throws IOException, ClassNotFoundException {
        PowerMockito.mockStatic(ReflectionUtils.class);
        BDDMockito.given(ReflectionUtils.getClasses(PACKAGE_NAME, true)).willThrow(new Exception());
        MorphiaUtils.getClasses(PACKAGE_NAME);
    }

}

package es.ganchix.morphia.utils;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.mongodb.morphia.utils.ReflectionUtils;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.IOException;

/**
 * Created by Rafael Ríos on 5/05/17.
 */

@RunWith(PowerMockRunner.class)
@PrepareForTest(ReflectionUtils.class)
public class MorphiaFailUtilsTest {

    private final String PACKAGE_NAME = "es.ganchix.morphia.utils.context.normal";

    @Test(expected = Exception.class)
    public void testCallGetClassesWithFail_ShouldReturnAException() throws IOException, ClassNotFoundException {

        PowerMockito.mockStatic(ReflectionUtils.class);
        BDDMockito.given(ReflectionUtils.getClasses(PACKAGE_NAME, true)).willThrow(new RuntimeException());
        MorphiaUtils.getClasses(PACKAGE_NAME);
    }

}

Solve problem with test, method need to throws unchecked exception


package de.retest.recheck.persistence;

import de.retest.recheck.TestCaseFinder;

/**
 * The default implementation that derives test suite and test case name from the test class and test method, working
 * for both JUnit and TestNG.
 */
public class ClassAndMethodBasedNamingStrategy implements NamingStrategy {

	@Override
	public String getSuiteName() {
		return TestCaseFinder.getInstance() //
				.findTestCaseClassNameInStack() //
				.orElseThrow( () -> new IllegalStateException( "Couldn't identify test class in call stack.\n"
						+ "This is needed to dynamically name the Golden Master files.\n "
						+ "Please instantiate RecheckImpl with RecheckOptions, and provide a different FileNamerStrategy." ) );
	}

	@Override
	public String getTestName() {
		return TestCaseFinder.getInstance() //
				.findTestCaseMethodNameInStack() //
				.orElseThrow( () -> new IllegalStateException( "Couldn't identify test method in call stack.\n"
						+ "This is needed to dynamically name the Golden Master files.\n"
						+ "Please call `startTest(\"name\")`, giving an explicit name, "
						+ "or instantiate RecheckImpl with RecheckOptions, and provide a different FileNamerStrategy." ) );
	}
}

package de.retest.recheck.persistence;

import de.retest.recheck.TestCaseFinder;

/**
 * The default implementation that derives test suite and test case name from the test class and test method, working
 * for both JUnit and TestNG.
 */
public class ClassAndMethodBasedNamingStrategy implements NamingStrategy {

	@Override
	public String getSuiteName() {
		return TestCaseFinder.getInstance() //
				.findTestCaseClassNameInStack() //
				.orElseThrow( () -> new IllegalStateException( "Couldn't identify test class in call stack.\n"
						+ "This is needed to dynamically name the Golden Master files.\n "
						+ "Please call `suiteName(\"name\")` in RecheckImpl with RecheckOptions, giving an explicit name, "
						+ "or instantiate it in a method, and provide a different NamingStrategy." ) );
	}

	@Override
	public String getTestName() {
		return TestCaseFinder.getInstance() //
				.findTestCaseMethodNameInStack() //
				.orElseThrow( () -> new IllegalStateException( "Couldn't identify test method in call stack.\n"
						+ "This is needed to dynamically name the Golden Master files.\n"
						+ "Please call `startTest(\"name\")`, giving an explicit name, "
						+ "or instantiate RecheckImpl with RecheckOptions, and provide a different NamingStrategy." ) );
	}
}

Update exception msg and add suiteName hint


package com.github.aureliano.achmed.resources.types;

public enum OperatingSystemFamily {

	DEBIAN,
	RPM,
	APP
}

package com.github.aureliano.achmed.resources.types;

public enum OperatingSystemFamily {

	DEBIAN,
	UBUNTU,
	RPM,
	APP
}

Add Ubuntu operating system family.

Add Ubuntu operating system family.


package org.springframework.security.core;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.SpringVersion;

/**
 * Internal class used for checking version compatibility in a deployed application.
 *
 * @author Luke Taylor
 */
public class SpringSecurityCoreVersion {
    private static final Log logger = LogFactory.getLog(SpringSecurityCoreVersion.class);

    static {
        // Check Spring Compatibility
        String springVersion = SpringVersion.getVersion();
        String version = getVersion();

        if (springVersion != null) {
            // TODO: Generate version class and information dynamically from a template in the build file
            logger.info("You are running with Spring Security Core " + version);
            if (!springVersion.startsWith("3")) {
                logger.error("Spring Major version '3' expected, but you are running with version: " + springVersion);
            }

            if (springVersion.compareTo("3.0.5") < 0) {
                logger.warn("You are advised to use Spring 3.0.5 or later with this version. You are running: " +
                    springVersion);
            }
        }
    }

    public static String getVersion() {
        Package pkg = SpringSecurityCoreVersion.class.getPackage();
        return (pkg != null ? pkg.getImplementationVersion() : null);
    }
}

package org.springframework.security.core;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.SpringVersion;

/**
 * Internal class used for checking version compatibility in a deployed application.
 *
 * @author Luke Taylor
 */
public class SpringSecurityCoreVersion {
    private static final Log logger = LogFactory.getLog(SpringSecurityCoreVersion.class);

    static {
        // Check Spring Compatibility
        String springVersion = SpringVersion.getVersion();
        String version = getVersion();

        if (springVersion != null) {
            // TODO: Generate version class and information dynamically from a template in the build file
            logger.info("You are running with Spring Security Core " + version);
            if (!springVersion.startsWith("3")) {
                logger.error("Spring Major version '3' expected, but you are running with version: "
                        + springVersion + ". Please check your classpath for unwanted jar files.");
            }

            if (springVersion.compareTo("3.0.5") < 0) {
                logger.warn("You are advised to use Spring 3.0.5 or later with this version. You are running: " +
                    springVersion);
            }
        }
    }

    public static String getVersion() {
        Package pkg = SpringSecurityCoreVersion.class.getPackage();
        return (pkg != null ? pkg.getImplementationVersion() : null);
    }
}

Expand message on incorrect Spring version to suggest checking the classpath for unwanted jars.


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

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

/**
 * A class annotated with {@link @Service} can have fields
 * annotated with <code>@Reference</code> in which case matching
 * services will be retrieved from the
 * {@link org.apache.karaf.shell.api.console.Registry} and
 * injected.
 *
 * If a field has a {@link java.util.List} type, it will be injected
 * with a list containing all matching services.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Reference {

    boolean optional() default false;

}

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

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

/**
 * A class annotated with {@link @Service} can have fields
 * annotated with <code>@Service</code> in which case matching
 * services will be retrieved from the
 * {@link org.apache.karaf.shell.api.console.Registry} and
 * injected.
 *
 * If a field has a {@link java.util.List} type, it will be injected
 * with a list containing all matching services.
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD})
public @interface Reference {

    boolean optional() default false;

}

Revert "Fixed typo in javadoc"

Revert "Fixed typo in javadoc"

This reverts commit b95fda354b618a5fa75b57f0400719e47cb7f91f.


package link.infra.simpleprocessors;

import link.infra.simpleprocessors.items.DuctTape;
import link.infra.simpleprocessors.items.SolderingIron;
import link.infra.simpleprocessors.items.processor.Processor;
import link.infra.simpleprocessors.util.SPItem;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class ModItems {
	public static final CreativeTabs tab = new CreativeTabs(SimpleProcessors.MODID) {
	    @Override public ItemStack getTabIconItem() {
	        return new ItemStack(ModItems.processor); // TODO change to computer
	    }
	};

	@GameRegistry.ObjectHolder("simpleprocessors:processor")
    public static Processor processor;

	@GameRegistry.ObjectHolder("simpleprocessors:solderingiron")
    public static SolderingIron solderingiron;
	@GameRegistry.ObjectHolder("simpleprocessors:screwdriver")
    public static SPItem screwdriver;
	@GameRegistry.ObjectHolder("simpleprocessors:ducttape")
    public static DuctTape ducttape;

	@SideOnly(Side.CLIENT)
    public static void initModels() {
		processor.initModel();
		solderingiron.initModel();
		screwdriver.initModel();
		ducttape.initModel();
	}

}

package link.infra.simpleprocessors;

import link.infra.simpleprocessors.items.DuctTape;
import link.infra.simpleprocessors.items.SolderingIron;
import link.infra.simpleprocessors.items.processor.Processor;
import link.infra.simpleprocessors.util.SPItem;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.common.registry.GameRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

public class ModItems {
	public static final CreativeTabs tab = new CreativeTabs(SimpleProcessors.MODID) {
	    @Override
	    public ItemStack getTabIconItem() {
	        return new ItemStack(ModItems.processor, 1, 1);
	    }
	};

	@GameRegistry.ObjectHolder("simpleprocessors:processor")
    public static Processor processor;

	@GameRegistry.ObjectHolder("simpleprocessors:solderingiron")
    public static SolderingIron solderingiron;
	@GameRegistry.ObjectHolder("simpleprocessors:screwdriver")
    public static SPItem screwdriver;
	@GameRegistry.ObjectHolder("simpleprocessors:ducttape")
    public static DuctTape ducttape;

	@SideOnly(Side.CLIENT)
    public static void initModels() {
		processor.initModel();
		solderingiron.initModel();
		screwdriver.initModel();
		ducttape.initModel();
	}

}

Change to meta 1 (iron) for creative tab icon


/**
 * Copyright (c) 2014, 2015 Inocybe Technologies, and others. All rights reserved.
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
 * and is available at http://www.eclipse.org/legal/epl-v10.html
 */

package org.opendaylight.dlux.web;

import org.osgi.util.tracker.ServiceTracker;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.BundleActivator;
import org.osgi.service.http.HttpService;

public class Activator implements BundleActivator {
  private ServiceTracker httpTracker;

  public void start(BundleContext context) throws Exception {
    httpTracker = new ServiceTracker(context, HttpService.class.getName(), null) {
      public void removedService(ServiceReference reference, Object service) {

        try {
           ((HttpService) service).unregister("/dlux");
        } catch (IllegalArgumentException exception) {
           // Ignore; servlet registration probably failed earlier on...
        }
      }

      public Object addingService(ServiceReference reference) {
        // HTTP service is available, register our servlet...
        HttpService httpService = (HttpService) this.context.getService(reference);
        try {
          httpService.registerResources("/dlux", "/pages",  null);
        } catch (Exception exception) {
          exception.printStackTrace();
        }
        return httpService;
      }
    };
    httpTracker.open();
  }

  public void stop(BundleContext context) throws Exception {
    httpTracker.close();
  }
}

Add missing license header in dlux-web

Add missing license header in dlux-web

Change-Id: I50ee01654cb01028b6541d9f80203ca1f803820a
Signed-off-by: Thanh Ha <09ea4d3a79c8bee41a16519f6a431f6bc0fd8d6f@linuxfoundation.org>


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

package com.cloudera.director.google.compute;

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

// TODO(duftler): Externalize these defaults.
public class GoogleComputeProviderDefaults {
  public static Map<String, String> IMAGE_ALIAS_TO_RESOURCE_MAP = new HashMap<String, String>();

  static {
    // TODO(duftler): Populate this map with appropriate choices.
    IMAGE_ALIAS_TO_RESOURCE_MAP.put(
        "ubuntu",
        "https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/ubuntu-1404-trusty-v20150316");
  }
}

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

package com.cloudera.director.google.compute;

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

// TODO(duftler): Externalize these defaults.
// https://github.com/cloudera/director-google-plugin/issues/2
public class GoogleComputeProviderDefaults {
  public static Map<String, String> IMAGE_ALIAS_TO_RESOURCE_MAP = new HashMap<String, String>();

  static {
    // TODO(duftler): Populate this map with appropriate choices.
    IMAGE_ALIAS_TO_RESOURCE_MAP.put(
        "ubuntu",
        "https://www.googleapis.com/compute/v1/projects/ubuntu-os-cloud/global/images/ubuntu-1404-trusty-v20150316");
  }
}

Add link to issue regarding loading defaults via Launcher.initialize().


Fix VTFMS protocol unit tests

Fix VTFMS protocol unit tests


package com.coding4people.mosquitoreport.api.factories;

import java.util.Optional;

import javax.inject.Inject;

import org.glassfish.hk2.api.Factory;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.coding4people.mosquitoreport.api.Env;

public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> {
    DynamoDBMapper mapper;

    @Inject
    public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) {
        mapper = new DynamoDBMapper(client,
                new DynamoDBMapperConfig.Builder()
                        .withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional
                                .ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost.")))
                .build());
    }

    @Override
    public void dispose(DynamoDBMapper mapper) {
    }

    @Override
    public DynamoDBMapper provide() {
        return mapper;
    }
}

package com.coding4people.mosquitoreport.api.factories;

import java.util.Optional;

import javax.inject.Inject;

import org.glassfish.hk2.api.Factory;

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapper;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig;
import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBMapperConfig.TableNameOverride;
import com.coding4people.mosquitoreport.api.Env;

public class DynamoDBMapperFactory implements Factory<DynamoDBMapper> {
    DynamoDBMapper mapper;

    @Inject
    public DynamoDBMapperFactory(AmazonDynamoDB client, Env env) {
        mapper = new DynamoDBMapper(client,
                new DynamoDBMapperConfig.Builder()
                        .withTableNameOverride(TableNameOverride.withTableNamePrefix(Optional
                                .ofNullable(env.get("MOSQUITO_REPORT_DYNAMODB_TABLE_PREFIX")).orElse("localhost") + "."))
                .build());
    }

    @Override
    public void dispose(DynamoDBMapper mapper) {
    }

    @Override
    public DynamoDBMapper provide() {
        return mapper;
    }
}

Add dot also to env prefix

Add dot also to env prefix


package de.markusfisch.android.shadereditor.app;

import de.markusfisch.android.shadereditor.database.DataSource;
import de.markusfisch.android.shadereditor.preference.Preferences;
import de.markusfisch.android.shadereditor.BuildConfig;

import android.app.Application;
import android.os.StrictMode;

public class ShaderEditorApplication extends Application {
	public static final Preferences preferences = new Preferences();
	public static final DataSource dataSource = new DataSource();

	@Override
	public void onCreate() {
		super.onCreate();

		preferences.init(this);
		dataSource.openAsync(this);

		if (BuildConfig.DEBUG) {
			StrictMode.setThreadPolicy(
					new StrictMode.ThreadPolicy.Builder()
							.detectAll()
							.penaltyLog()
							.build());

			StrictMode.setVmPolicy(
					new StrictMode.VmPolicy.Builder()
							.detectLeakedSqlLiteObjects()
							.penaltyLog()
							.penaltyDeath()
							.build());
		}
	}
}

package de.markusfisch.android.shadereditor.app;

import de.markusfisch.android.shadereditor.database.DataSource;
import de.markusfisch.android.shadereditor.preference.Preferences;
import de.markusfisch.android.shadereditor.BuildConfig;

import android.app.Application;
import android.os.StrictMode;

public class ShaderEditorApplication extends Application {
	public static final Preferences preferences = new Preferences();
	public static final DataSource dataSource = new DataSource();

	@Override
	public void onCreate() {
		super.onCreate();

		if (BuildConfig.DEBUG) {
			StrictMode.setThreadPolicy(
					new StrictMode.ThreadPolicy.Builder()
							.detectAll()
							.penaltyLog()
							.build());

			StrictMode.setVmPolicy(
					new StrictMode.VmPolicy.Builder()
							.detectLeakedSqlLiteObjects()
							.penaltyLog()
							.penaltyDeath()
							.build());
		}

		preferences.init(this);
		dataSource.openAsync(this);
	}
}

Initialize strict mode before anything else


package com.mijecu25.sqlplus.compiler.core.statement;

import java.sql.SQLException;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Test StatementUseDatabase
 *
 * @author Miguel Velez - miguelvelezmj25
 * @version 0.1.0.1
 */
public class TestStatementUseDatabase extends TestStatement {

    protected static StatementUseDatabase statement;

    @BeforeClass
    public static void initialize() throws SQLException {
        TestStatement.initialize();
        // TODO this might not work in all computers since they might not have this database
        TestStatementUseDatabase.statement = new StatementUseDatabase("sys");
    }

    @AfterClass
    public static void terminate() throws SQLException {
        TestStatement.terminate();
    }

    @Test
    public void testStatementUseDatabase() {
        StatementUseDatabase statement = new StatementUseDatabase("sys");

        Assert.assertNotNull(statement);
    }

    @Test
    public void testExecute() throws SQLException {
        TestStatementUseDatabase.statement.execute(TestStatementUseDatabase.connection);
    }
}

package com.mijecu25.sqlplus.compiler.core.statement;

import java.sql.SQLException;

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;

/**
 * Test StatementUseDatabase
 *
 * @author Miguel Velez - miguelvelezmj25
 * @version 0.1.0.2
 */
public class TestStatementUseDatabase extends TestStatement {

    protected static StatementUseDatabase statement;

    @BeforeClass
    public static void initialize() throws SQLException {
        TestStatement.initialize();
        // TODO this might not work in all computers since they might not have this database
        TestStatementUseDatabase.statement = new StatementUseDatabase("information_schema");
    }

    @AfterClass
    public static void terminate() throws SQLException {
        TestStatement.terminate();
    }

    @Test
    public void testStatementUseDatabase() {
        StatementUseDatabase statement = new StatementUseDatabase("information_schema");

        Assert.assertNotNull(statement);
    }

    @Test
    public void testExecute() throws SQLException {
        TestStatementUseDatabase.statement.execute(TestStatementUseDatabase.connection);
    }
}

Change database in test because Travis was failing


class Test {
    private int a;
    private final int b;
    private int c;
    private final int d;

    public Test(int a, int b, int c, int d) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }
}

class Test {
    private int a;
    private final int b;
    private int c;
    private final int d;

    public Test(int b, int d) {
        this.b = b;
        this.d = d;
    }
}

Revert "IDEA-228014 updated test data: all non implicitly written fields are preselected"

This reverts commit 4fae1e04

GitOrigin-RevId: 602735cfed173e4071b12065cceb49453845eba2


package com.karateca.ddescriber.model;

import com.intellij.find.FindResult;
import com.karateca.ddescriber.BaseTestCase;

import junit.framework.Assert;

import java.util.List;

/**
 * @author Andres Dominguez.
 */
public class TestFindResultTest extends BaseTestCase {

  private TestFindResult testFindResult;

  @Override
  public void setUp() throws Exception {
    super.setUp();
    prepareScenarioWithTestFile("jasmineTestCaretTop.js");
    jasmineFinder.findAll();
    List<FindResult> findResults = jasmineFinder.getFindResults();

    testFindResult = new TestFindResult(document, findResults.get(0));
  }

  public void testToString() throws Exception {
    Assert.assertEquals("top describe", testFindResult.toString());
  }
}

package com.karateca.ddescriber.model;

import com.intellij.find.FindResult;
import com.karateca.ddescriber.BaseTestCase;

import junit.framework.Assert;

import java.util.List;

/**
 * @author Andres Dominguez.
 */
public class TestFindResultTest extends BaseTestCase {

  private TestFindResult testFindResult;

  @Override
  public void setUp() throws Exception {
    super.setUp();
    prepareScenarioWithTestFile("jasmine1/jasmineTestCaretTop.js");
    jasmineFinder.findAll();
    List<FindResult> findResults = jasmineFinder.getFindResults();

    testFindResult = new TestFindResult(document, findResults.get(0));
  }

  public void testToString() throws Exception {
    assertEquals("top describe", testFindResult.toString());
  }
}

Add scenarios for jasmine 1, 2

Add scenarios for jasmine 1, 2


package io.github.lasercar.simplemention;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;

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

public class Events implements Listener {

    @EventHandler
    public void onChat(AsyncPlayerChatEvent event) {
        String message = event.getMessage();

        if (MessageParser.hasMentions(message)) {

            Pattern pattern = Pattern.compile("@(\\w+)");
            Matcher matcher = pattern.matcher(message);
            StringBuffer messageBuffer = new StringBuffer();

            while (matcher.find()) {
                String mention = matcher.group(1);

                Player[] playersMatched = PlayerMatcher.findAllByName(mention);

                if (playersMatched.length > 0) {
                    matcher.appendReplacement(messageBuffer, MessageParser.highlightMention(mention));

                    SoundManager.pingPlayers(playersMatched);
                }
            }
            matcher.appendTail(messageBuffer);

            event.setMessage(messageBuffer.toString());
        }
    }

    @EventHandler
    public void onTabComplete(PlayerChatTabCompleteEvent event) {
        Bukkit.getLogger().info(event.toString());
    }

}

package io.github.lasercar.simplemention;

import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerChatTabCompleteEvent;

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

public class Events implements Listener {

    @EventHandler
    public void onChat(AsyncPlayerChatEvent event) {
        String message = event.getMessage();

        if (MessageParser.hasMentions(message)) {

            Pattern pattern = Pattern.compile("@(\\w+)");
            Matcher matcher = pattern.matcher(message);
            StringBuffer messageBuffer = new StringBuffer();

            while (matcher.find()) {
                String mention = matcher.group(1);

                Player[] playersMatched = PlayerMatcher.findAllByName(mention);

                if (playersMatched.length > 0) {
                    matcher.appendReplacement(messageBuffer, MessageParser.highlightMention(mention));

                    SoundManager.pingPlayers(playersMatched);
                }
            }
            matcher.appendTail(messageBuffer);

            event.setMessage(messageBuffer.toString());
        }
    }

    @EventHandler
    public void onTabComplete(PlayerChatTabCompleteEvent event) {
//        if (event.getLastToken().equals("@")) {
//            event.getTabCompletions().push(Bukkit.getOnlinePlayers());
//        }

        //DEBUG
        Bukkit.getLogger().info(event.getTabCompletions().toString());
        event.getTabCompletions().clear();
        Bukkit.getLogger().info(event.getTabCompletions().toString());
    }

}

Test changing tab complete list

Test changing tab complete list


// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).

package com.twitter.intellij.pants.service.project.wizard;

import com.intellij.ide.util.PropertiesComponent;
import icons.PantsIcons;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.bsp.project.importing.BspProjectImportProvider;

import javax.swing.Icon;
import java.util.Optional;

public class FastpassProjectImportProvider extends BspProjectImportProvider {
  static private String label() {
    return Optional
      .ofNullable(PropertiesComponent.getInstance().getValue("fastpass.import.provider.label"))
      .orElse("Pants (Fastpass)");
  }

  @Override
  public @Nullable Icon getIcon() {
    return PantsIcons.Icon;
  }

  @Override
  public @NotNull
  @Nls(capitalization = Nls.Capitalization.Sentence) String getName() {
    return label();
  }
}

// Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
// Licensed under the Apache License, Version 2.0 (see LICENSE).

package com.twitter.intellij.pants.service.project.wizard;

import com.intellij.ide.util.PropertiesComponent;
import icons.PantsIcons;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.bsp.project.importing.BspProjectImportProvider;

import javax.swing.Icon;
import java.util.Optional;

public class FastpassProjectImportProvider extends BspProjectImportProvider {
  static private String label() {
    return Optional
      .ofNullable(PropertiesComponent.getInstance().getValue("fastpass.import.provider.label"))
      .orElse("Pants (Fastpass)");
  }

  @Override
  public @Nullable Icon getIcon() {
    return PantsIcons.Icon;
  }

  @NotNull
  @Override
  public String getId() {
    return "Fastpass";
  }

  @Override
  public @NotNull
  @Nls(capitalization = Nls.Capitalization.Sentence) String getName() {
    return label();
  }
}

Set Fastpass Import provider ID to 'Fastpass'


package htmlflow;

import java.io.PrintStream;

public interface ModelBinder<T>{
	void bind(PrintStream out, T model);
}

package htmlflow;

import java.io.PrintStream;

@FunctionalInterface
public interface ModelBinder<T>{
	void bind(PrintStream out, T model);
}

Declare ModelBiinder as FunctionalInterface Java 8 style programming


package com.vaadin.polymer.elemental;

import com.google.gwt.core.client.js.JsProperty;
import com.google.gwt.core.client.js.JsType;

@JsType
public interface NodeList<T> {

    @JsProperty
    int getLength();

    T item(int index);
}

package com.vaadin.polymer.elemental;

import com.google.gwt.core.client.js.JsProperty;
import com.google.gwt.core.client.js.JsType;

@JsType
public interface NodeList {

    @JsProperty
    int getLength();

    <T extends Node> T item(int index);
}

Move generic from class to method

Move generic from class to method


package org.jaxen.javabean;

import junit.framework.TestCase;

public class DocumentNavigatorTest
    extends TestCase
{

    public void testNothing()
        throws Exception
    {
        JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" );

        Person bob = new Person( "bob", 30 );

        bob.addBrother( new Person( "billy", 34 ) );
        bob.addBrother( new Person( "seth", 29 ) );
        bob.addBrother( new Person( "dave", 32 ) );
        bob.addBrother( new Person( "jim", 29 ) );
        bob.addBrother( new Person( "larry", 42 ) );
        bob.addBrother( new Person( "ted", 22 ) );

        System.err.println( xpath.evaluate( bob ) );
    }

}

package org.jaxen.javabean;

import junit.framework.TestCase;
import org.jaxen.saxpath.helpers.XPathReaderFactory;

public class DocumentNavigatorTest
    extends TestCase
{

    protected void setUp() throws Exception
    {
        System.setProperty( XPathReaderFactory.DRIVER_PROPERTY,
                            "" );
    }

    public void testNothing()
        throws Exception
    {
        JavaBeanXPath xpath = new JavaBeanXPath( "brother[position()<4]/name" );

        Person bob = new Person( "bob", 30 );

        bob.addBrother( new Person( "billy", 34 ) );
        bob.addBrother( new Person( "seth", 29 ) );
        bob.addBrother( new Person( "dave", 32 ) );
        bob.addBrother( new Person( "jim", 29 ) );
        bob.addBrother( new Person( "larry", 42 ) );
        bob.addBrother( new Person( "ted", 22 ) );

        System.err.println( xpath.evaluate( bob ) );
    }

}

Set property in case it has been set wrong previously


package com.johnstarich.moviematcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Handles all requests sent to the root ("/") of this server.
 * Created by johnstarich on 1/30/16.
 */
public class RootServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html; charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getWriter().println("
Hey there!

This is our EE461L design project

This is the request path we received: " + request.getPathInfo() + "
");
		System.out.println("Request was = GET " + request.getPathInfo());
	}
}

package com.johnstarich.moviematcher;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Handles all requests sent to the root ("/") of this server.
 * Created by johnstarich on 1/30/16.
 */
public class RootServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html; charset=utf-8");
		response.setStatus(HttpServletResponse.SC_OK);
		response.getWriter().println("
Hey there!

This is Movie Matcher

This is the request path we received: " + request.getPathInfo() + "
");
		System.out.println("Request was = GET " + request.getPathInfo());
	}
}

Refactor response page to say project title.


package seedu.address.logic.commands;

/**
 * Lists all persons in the address book to the user.
 */
public class ListCommand extends Command {

    public static final String COMMAND_WORD = "list";

    public static final String MESSAGE_SUCCESS = "Listed all persons";

    @Override
    public CommandResult execute() {
        model.updateFilteredListToShowAll();
        return new CommandResult(MESSAGE_SUCCESS);
    }
}

package seedu.address.logic.commands;

//@@author A0164466X
/**
 * Lists all tasks in the task manager to the user.
 */
public class ListCommand extends Command {

    public static final String COMMAND_WORD = "list";

    public static final String MESSAGE_SUCCESS = "Listed all tasks";

    @Override
    public CommandResult execute() {
        model.updateFilteredListToShowAll();
        return new CommandResult(MESSAGE_SUCCESS);
    }
}

Correct List command to display "tasks" instead of "persons"


package com.stripe.functional;

import com.stripe.BaseStripeFunctionalTest;
import com.stripe.exception.StripeException;
import com.stripe.model.ApplicationFee;
import org.junit.Test;

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

import static org.junit.Assert.assertEquals;

public class ApplicationFeeTest extends BaseStripeFunctionalTest {
	@Test
	public void testApplicationFeeList() throws StripeException {
		Map<String, Object> listParams = new HashMap<String, Object>();
		listParams.put("count", 0);
		List<ApplicationFee> fees = ApplicationFee.all(listParams).getData();
		assertEquals(fees.size(), 0);
	}
}

package com.stripe.functional;

import com.stripe.BaseStripeFunctionalTest;
import com.stripe.exception.StripeException;
import com.stripe.model.ApplicationFee;
import com.stripe.model.ApplicationFeeCollection;
import org.junit.Test;

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

import static org.junit.Assert.assertEquals;

public class ApplicationFeeTest extends BaseStripeFunctionalTest {
	@Test
	public void testApplicationFeeList() throws StripeException {
		Map<String, Object> listParams = new HashMap<String, Object>();
		ApplicationFeeCollection fees = ApplicationFee.list(listParams);
		assertEquals("/v1/application_fees", fees.getURL());
	}
}

Fix a failing test case in stripe-java's build

This test case seems to have been trying to fetch zero items of a
collection and then comparing against the returned `data`'s count.
Unfortunately for our build's reliability, for one the parameter is
actually called `limit`, and two it only supports numbers of one or
more [1].

I believe that the only thing keeping this build running until now is
that the collection of application fees for the account could be
reliably assumed to be zero.

This patch changes what we assert on for the return list -- we move over
to a stable value; in this case the collection's URL.

[1] https://stripe.com/docs/api/curl#list_application_fees-limit


package pro.cucumber;

import org.junit.Before;
import org.junit.Test;
import pro.cucumber.gitcli.GitCliRevisionProvider;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.regex.Pattern;

import static org.junit.Assert.assertTrue;

public abstract class RevisionProviderContract {
    private Path rootPath;

    @Before
    public void createScm() throws IOException {
        rootPath = Files.createTempDirectory("GitWC");
        Path subfolder = rootPath.resolve("subfolder");
        Files.createDirectory(subfolder);
        Files.createFile(subfolder.resolve("file"));
        Exec.cmd("git init", rootPath);
        Exec.cmd("git add -A", rootPath);
        Exec.cmd("git commit -am \"files\"", rootPath);
    }

    @Test
    public void findsRev() {
        String sha1Pattern = "^[a-f0-9]{40}$";
        RevisionProvider revisionProvider = makeRevisionProvider(rootPath);
        String rev = revisionProvider.getRev();
        assertTrue("Expected a sha1, got: "+rev, Pattern.matches(sha1Pattern, rev));
    }

    protected abstract RevisionProvider makeRevisionProvider(Path rootPath);

}

package pro.cucumber;

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

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

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

public abstract class RevisionProviderContract {
    private Path rootPath;

    @Before
    public void createScm() throws IOException {
        rootPath = Files.createTempDirectory("GitWC");
        Path subfolder = rootPath.resolve("subfolder");
        Files.createDirectory(subfolder);
        Files.createFile(subfolder.resolve("file"));
        Exec.cmd("git init", rootPath);
        Exec.cmd("git add -A", rootPath);
        Exec.cmd("git commit -am \"files\"", rootPath);
        List<String> status = Exec.cmd("git status --porcelain", rootPath);
        assertEquals(new ArrayList<String>(), status);
    }

    @Test
    public void findsRev() {
        String sha1Pattern = "^[a-f0-9]{40}$";
        RevisionProvider revisionProvider = makeRevisionProvider(rootPath);
        String rev = revisionProvider.getRev();
        assertTrue("Expected a sha1, got: " + rev, Pattern.matches(sha1Pattern, rev));
    }

    protected abstract RevisionProvider makeRevisionProvider(Path rootPath);

}

Check the test repo is created correctly


package mklib.hosseini.com.vinci.Main;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import java.io.ByteArrayInputStream;

public class Vinci {

    private static Context context;

    public Vinci(Context context){
        Vinci.context = context;
    }

    public synchronized Drawable PhotoFromDB(byte[] imageByte){

        ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByte);
        Bitmap image = BitmapFactory.decodeStream(imageStream);

        return new BitmapDrawable(context.getResources(), image);
    }

    public synchronized byte[] PhotoInDB(String Url) throws Exception {

        return new PhotoProcess.logger(Url).call();

    }

}

package mklib.hosseini.com.vinci.Main;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;

import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

public class Vinci {

    private static Context context;

    public Vinci(Context context){
        Vinci.context = context;
    }

    public synchronized Drawable PhotoFromDB(byte[] imageByte){

        ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByte);
        Bitmap image = BitmapFactory.decodeStream(imageStream);

        return new BitmapDrawable(context.getResources(), image);
    }

    public synchronized byte[] PhotoInDB(String Url) throws Exception {

        ExecutorService service =  Executors.newSingleThreadExecutor();
        PhotoProcess.logger sumTask = new PhotoProcess.logger(Url);
        Future<byte[]> future = service.submit(sumTask);
        service.shutdown();
        service.awaitTermination(5, TimeUnit.SECONDS);

        return future.get();

    }

}

Add concurrent library to it .

Add concurrent library to it .


package protocolsupport.protocol.types;

import protocolsupport.protocol.utils.EnumConstantLookups;

public enum BlockDirection {

	DOWN(-1), UP(-1),
	NORTH(2), SOUTH(0),
	WEST(1), EAST(3);

	protected int id2d;

	public static final EnumConstantLookups.EnumConstantLookup<BlockDirection> CONSTANT_LOOKUP = new EnumConstantLookups.EnumConstantLookup<>(BlockDirection.class);

	BlockDirection(int id2d) {
		this.id2d = id2d;
	}

	public int get2DId() {
		return id2d;
	}

}

package protocolsupport.protocol.types;

import protocolsupport.protocol.utils.EnumConstantLookups;

public enum BlockDirection {

	DOWN(0), UP(0),
	NORTH(2), SOUTH(0),
	WEST(1), EAST(3);

	protected int id2d;

	public static final EnumConstantLookups.EnumConstantLookup<BlockDirection> CONSTANT_LOOKUP = new EnumConstantLookups.EnumConstantLookup<>(BlockDirection.class);

	BlockDirection(int id2d) {
		this.id2d = id2d;
	}

	public int get2DId() {
		return id2d;
	}

}

Change 2d id to south 2d id.

Change 2d id to south 2d id.

Fixes < 1.8 crashing when seeing item frames with unsupported
directions.


/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertTrue("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

/*
 * This Java source file was generated by the Gradle 'init' task.
 */
import org.junit.Test;
import static org.junit.Assert.*;

public class LibraryTest {
    @Test public void testSomeLibraryMethod() {
        Library classUnderTest = new Library();
        assertFalse("someLibraryMethod should return 'true'", classUnderTest.someLibraryMethod());
    }
}

Make test fail to test Travis

Make test fail to test Travis


package com.msgilligan.bitcoin;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;

/**
 * Utility class for converting from satoshis (BigInteger) to bitcoins (BigDecimal) and vice-versa
 */
public class BTC  {
    public static final long satoshisPerBitcoin = 100000000;
    public static final BigInteger satoshisPerBTC = BigInteger.valueOf(satoshisPerBitcoin);
    public static final BigDecimal satoshisPerBTCDecimal = new BigDecimal(satoshisPerBTC);

    public static BigDecimal satoshisToBTC(BigInteger satoshis) {
        BigDecimal decimalSatoshis = new BigDecimal(satoshis);
        return decimalSatoshis.divide(satoshisPerBTCDecimal);
    }
    public static BigInteger btcToSatoshis(BigDecimal btc) {
        BigDecimal satoshisDecimal = btc.multiply(BTC.satoshisPerBTCDecimal);
        return satoshisDecimal.toBigInteger();
    }
}

package com.msgilligan.bitcoin;

import org.bitcoinj.core.Coin;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;

/**
 * Utility class for converting from satoshis (BigInteger) to bitcoins (BigDecimal) and vice-versa
 */
public class BTC  {
    public static final long satoshisPerBitcoin = 100000000;
    public static final BigInteger satoshisPerBTC = BigInteger.valueOf(satoshisPerBitcoin);
    public static final BigDecimal satoshisPerBTCDecimal = new BigDecimal(satoshisPerBTC);

    public static BigDecimal satoshisToBTC(BigInteger satoshis) {
        BigDecimal decimalSatoshis = new BigDecimal(satoshis);
        return decimalSatoshis.divide(satoshisPerBTCDecimal);
    }
    public static BigInteger btcToSatoshis(BigDecimal btc) {
        BigDecimal satoshisDecimal = btc.multiply(BTC.satoshisPerBTCDecimal);
        return satoshisDecimal.toBigInteger();
    }
    public static Coin btcToCoin(BigDecimal btc) {
        return Coin.valueOf(BTC.btcToSatoshis(btc).longValue());
    }
    public static BigDecimal coinToBTC(Coin coin) {
        BigInteger satoshis = BigInteger.valueOf(coin.longValue());
        return BTC.satoshisToBTC(satoshis);
    }
}

Add conversions between BigDecimal & bitcoinj Coin


package ca.antonious.viewcelladapter.sections;

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

import ca.antonious.viewcelladapter.viewcells.AbstractViewCell;
import ca.antonious.viewcelladapter.utils.ViewCellUtils;

/**
 * Created by George on 2016-12-17.
 */

public class CompositeSection extends AbstractSection {
    private List<AbstractSection> sections;

    public CompositeSection() {
        this.sections = new ArrayList<>();
    }

    @Override
    public AbstractViewCell get(int position) {
        return ViewCellUtils.getViewCell(sections, position);
    }

    @Override
    public void remove(int position) {
        int sectionIndex = ViewCellUtils.getSectionIndex(sections, position);
        int viewCellIndex = ViewCellUtils.getViewCellIndex(sections, position);

        sections.get(sectionIndex).remove(viewCellIndex);
    }

    @Override
    public int getItemCount() {
        return ViewCellUtils.getTotalCount(sections);
    }

    public CompositeSection addSection(AbstractSection section) {
        sections.add(section);
        return this;
    }

    public CompositeSection removeSection(AbstractSection section) {
        sections.remove(section);
        return this;
    }
}

package ca.antonious.viewcelladapter.sections;

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

import ca.antonious.viewcelladapter.internal.SectionObserver;
import ca.antonious.viewcelladapter.viewcells.AbstractViewCell;
import ca.antonious.viewcelladapter.utils.ViewCellUtils;

/**
 * Created by George on 2016-12-17.
 */

public class CompositeSection extends AbstractSection implements SectionObserver {
    private List<AbstractSection> sections;

    public CompositeSection() {
        this.sections = new ArrayList<>();
    }

    @Override
    public AbstractViewCell get(int position) {
        return ViewCellUtils.getViewCell(sections, position);
    }

    @Override
    public void remove(int position) {
        int sectionIndex = ViewCellUtils.getSectionIndex(sections, position);
        int viewCellIndex = ViewCellUtils.getViewCellIndex(sections, position);

        sections.get(sectionIndex).remove(viewCellIndex);
    }

    @Override
    public int getItemCount() {
        return ViewCellUtils.getTotalCount(sections);
    }

    public CompositeSection addSection(AbstractSection section) {
        section.addObserver(this);
        sections.add(section);
        return this;
    }

    public CompositeSection removeSection(AbstractSection section) {
        section.removeObserver(this);
        sections.remove(section);
        return this;
    }

    @Override
    public void onDataChanged() {
        notifyDataChanged();
    }
}

Update composite section to handle notifications


package org.androplus.wedymod;

import android.os.Build;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;

public class SettingActivity extends PreferenceActivity {

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

        getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingFragment()).commit();
	}

	public static class SettingFragment extends PreferenceFragment{

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

			addPreferencesFromResource(R.xml.settings);
		}

	}

}

package org.androplus.wedymod;

import android.os.Build;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.preference.PreferenceScreen;

public class SettingActivity extends PreferenceActivity {

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

        getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingFragment()).commit();
	}

	public static class SettingFragment extends PreferenceFragment{

		@Override
		public void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_READABLE);
			addPreferencesFromResource(R.xml.settings);
		}

	}

}

Fix permission of pref file

Fix permission of pref file


package com.sample.database.room;

import android.arch.persistence.room.Room;
import android.content.Context;

import java.util.List;

/**
 * Created by anandgaurav on 12/02/18.
 */

public class UserDBHelper {

    private final AppDatabase appDatabase;
    private final AppDatabase inMemoryAppDatabase;

    public UserDBHelper(Context context) {
        appDatabase = Room.databaseBuilder(context, AppDatabase.class, "User-Database")
                .allowMainThreadQueries()
                .build();
        inMemoryAppDatabase = Room.inMemoryDatabaseBuilder(context, AppDatabase.class).build();
    }

    public void insertUser(List<User> userList) {
        appDatabase.userDao().insertAll(userList);
    }

    public void insertUserInMemory(List<User> userList) {
        inMemoryAppDatabase.userDao().insertAll(userList);
    }

    public int count() {
        return appDatabase.userDao().loadAll().size();
    }

    public int countInMemory() {
        return inMemoryAppDatabase.userDao().loadAll().size();
    }

}

package com.sample.database.room;

import android.arch.persistence.room.Room;
import android.content.Context;

import java.util.List;

/**
 * Created by anandgaurav on 12/02/18.
 */

public class UserDBHelper {

    private final AppDatabase appDatabase;
    private final AppDatabase inMemoryAppDatabase;

    public UserDBHelper(Context context) {
        appDatabase = Room.databaseBuilder(context, AppDatabase.class, "User-Database")
                .allowMainThreadQueries()
                .build();
        inMemoryAppDatabase = Room.inMemoryDatabaseBuilder(context, AppDatabase.class)
                .allowMainThreadQueries()
                .build();
    }

    public void insertUser(List<User> userList) {
        appDatabase.userDao().insertAll(userList);
    }

    public void insertUserInMemory(List<User> userList) {
        inMemoryAppDatabase.userDao().insertAll(userList);
    }

    public int count() {
        return appDatabase.userDao().loadAll().size();
    }

    public int countInMemory() {
        return inMemoryAppDatabase.userDao().loadAll().size();
    }

}

Add example for inMemory room database

Add example for inMemory room database


package com.slugterra.render;

import com.slugterra.entity.EntitySlug;
import com.slugterra.render.protoform.RenderSlug;

import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraftforge.fml.client.registry.IRenderFactory;

public class SlugRenderFactory implements IRenderFactory<EntitySlug> {

	private ModelBase model;
	private String slugName;
	private float shadow = 0.3f;

	public SlugRenderFactory(ModelBase model, String name) {
		this.model = model;
		this.slugName = name;
	}

	@Override
	public Render<? super EntitySlug> createRenderFor(RenderManager manager) {
		return new RenderSlug(manager, this.slugName, this.model, this.shadow);
	}

}

package com.slugterra.render;

import com.slugterra.entity.EntitySlug;

import net.minecraft.client.model.ModelBase;
import net.minecraft.client.renderer.entity.Render;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraftforge.fml.client.registry.IRenderFactory;

public class SlugRenderFactory implements IRenderFactory<EntitySlug> {

	private ModelBase model;
	private String slugName;
	private float shadow = 0.3f;

	public SlugRenderFactory(ModelBase model, String name) {
		this.model = model;
		this.slugName = name;
	}

	@Override
	public Render<? super EntitySlug> createRenderFor(RenderManager manager) {
		return new RenderSlug(manager, this.slugName, this.model, this.shadow);
	}

}

Fix import in render factory

Fix import in render factory


package orc.trace.values;

import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;

import xtc.util.Utilities;

/**
 * Constant (not just immutable, but atomic) value,
 * such as a String, Number, Boolean, or Character.
 * @author quark
 */
public class ConstantValue extends AbstractValue {
	public final Serializable constant;
	public ConstantValue(final Serializable constant) {
		super();
		this.constant = constant;
	}
	public void prettyPrint(Writer out, int indent) throws IOException {
		if (constant instanceof String) {
			out.write('"' + Utilities.escape((String)constant, Utilities.JAVA_ESCAPES) + '"');
		} else out.write(constant.toString());
	}
	public boolean equals(Object that) {
		return that instanceof ConstantValue
				&& ((ConstantValue)that).constant.equals(constant);
	}
}

package orc.trace.values;

import java.io.IOException;
import java.io.Serializable;
import java.io.Writer;

import xtc.util.Utilities;

/**
 * Constant (not just immutable, but atomic) value,
 * such as a String, Number, Boolean, Character, or null.
 * @author quark
 */
public class ConstantValue extends AbstractValue {
	public final Serializable constant;
	public ConstantValue(final Serializable constant) {
		super();
		this.constant = constant;
	}
	public void prettyPrint(Writer out, int indent) throws IOException {
		out.write(orc.runtime.values.Value.write(constant));
	}
	public boolean equals(final Object that) {
		if (that == null) return false;
		if (!(that instanceof ConstantValue)) return false;
		final ConstantValue cv = (ConstantValue)that;
		if (cv.constant == null) return constant == null;
		return cv.constant.equals(constant);
	}
}

Fix bug with displaying/comparing null values in traces.


/*
 * This file is part of libbluray
 * Copyright (C) 2010  William Hahne
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see
 * <http://www.gnu.org/licenses/>.
 */
package javax.tv.graphics;

import java.awt.Container;
import javax.tv.xlet.XletContext;
import org.havi.ui.HScene;
import org.havi.ui.HSceneFactory;

public class TVContainer {
    public static Container getRootContainer(XletContext context)
    {
        if (context == null) {
            throw new NullPointerException();
        }

        HScene scene = HSceneFactory.getInstance().getDefaultHScene();
        return scene;
    }
}

/*
 * This file is part of libbluray
 * Copyright (C) 2010  William Hahne
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library. If not, see
 * <http://www.gnu.org/licenses/>.
 */
package javax.tv.graphics;

import java.awt.Container;
import javax.tv.xlet.XletContext;
import org.havi.ui.HSceneFactory;

import org.videolan.BDJXletContext;

public class TVContainer {
    public static Container getRootContainer(XletContext context)
    {
        if (context == null) {
            throw new NullPointerException();
        }

        if (!(context instanceof BDJXletContext) || (BDJXletContext)context != BDJXletContext.getCurrentContext()) {
            org.videolan.Logger.getLogger(TVContainer.class.getName()).error("wrong context");
        }

        /* GEM: return instance of org.havi.ui.HScene or NULL */
        HSceneFactory sf = HSceneFactory.getInstance();
        if (sf != null) {
            return sf.getDefaultHScene();
        }
        return null;
    }
}

Fix possible null pointer dereference

Fix possible null pointer dereference

Also log error if context does not match


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

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import com.allegient.candidate.stockquote.app.QuoteFinderTest;
import com.allegient.candidate.stockquote.http.QuoteControllerTest;

@RunWith(Suite.class)
@SuiteClasses({ QuoteFinderTest.class, QuoteControllerTest.class })
/**
 * This class lets us run all the tests easily so we can verify coverage in
 * Eclipse
 *
 * @author Jeff Butler
 *
 */
public class RunAllTests {
}

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

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import com.allegient.candidate.stockquote.app.QuoteFinderTest;
import com.allegient.candidate.stockquote.datasource.FakeQuoteGeneratorTest;
import com.allegient.candidate.stockquote.datasource.InMemoryDataSourceTest;
import com.allegient.candidate.stockquote.datasource.RandomPriceGeneratorTest;
import com.allegient.candidate.stockquote.http.QuoteControllerTest;

@RunWith(Suite.class)
@SuiteClasses({
    QuoteFinderTest.class,
    FakeQuoteGeneratorTest.class,
    InMemoryDataSourceTest.class,
    RandomPriceGeneratorTest.class,
    QuoteControllerTest.class
})
/**
 * This class lets us run all the tests easily so we can verify coverage in
 * Eclipse
 *
 * @author Jeff Butler
 *
 */
public class RunAllTests {
}

Add all tests to the suite

Add all tests to the suite


package fi.helsinki.cs.tmc.cli.command;

import static org.junit.Assert.assertTrue;

import fi.helsinki.cs.tmc.cli.Application;

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

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class TestCommandTest {

    Application app;
    OutputStream os;

    @Before
    public void setUp() {
        app = new Application();

        os = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(os);
        System.setOut(ps);
    }

    @Test
    public void runWorksRightWithoutOption() {
        String[] args = {"EasterEgg"};
        app.run(args);
        assertTrue(os.toString().contains("Let's run easter egg."));
    }

    @Test
    public void runWorksRightWithOption() {
        String[] args = {"EasterEgg", "-a"};
        app.run(args);
        assertTrue(os.toString().contains("Let's run easter egg with -a"));
    }

}

package fi.helsinki.cs.tmc.cli.command;

import static org.junit.Assert.assertTrue;

import fi.helsinki.cs.tmc.cli.Application;

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

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;

public class TestCommandTest {

    Application app;
    OutputStream os;

    @Before
    public void setUp() {
        app = new Application();

        os = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(os);
        System.setOut(ps);
    }

    @Test
    public void runWorksRightWithoutOption() {
        String[] args = {"easter-egg"};
        app.run(args);
        assertTrue(os.toString().contains("Let's run easter egg."));
    }

    @Test
    public void runWorksRightWithOption() {
        String[] args = {"easter-egg", "-a"};
        app.run(args);
        assertTrue(os.toString().contains("Let's run easter egg with -a"));
    }

}

Fix the easter-egg command name in tests.


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

package test.base;

import static org.junit.jupiter.api.Assertions.assertLinesMatch;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.List;
import org.junit.jupiter.api.Test;

class SwallowSystemTests {

  @Test
  @SwallowSystem
  void empty(SwallowSystem.Streams streams) {
    assertTrue(streams.lines().isEmpty());
    assertTrue(streams.errors().isEmpty());
  }

  @Test
  @SwallowSystem
  void normalAndErrorOutput(SwallowSystem.Streams streams) {
    System.out.println("out");
    System.err.println("err");
    assertLinesMatch(List.of("out"), streams.lines());
    assertLinesMatch(List.of("err"), streams.errors());
  }
}

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

package test.base;

import static org.junit.jupiter.api.Assertions.assertLinesMatch;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.List;
import org.junit.jupiter.api.Test;

class SwallowSystemTests {

  @Test
  @SwallowSystem
  void empty(SwallowSystem.Streams streams) {
    assertTrue(streams.lines().isEmpty());
    assertTrue(streams.errors().isEmpty());
  }

  @Test
  @SwallowSystem
  void normalAndErrorOutput() {
    System.out.println("out");
    System.err.println("err");
  }

  @Test
  @SwallowSystem
  void normalAndErrorOutput(SwallowSystem.Streams streams) {
    System.out.println("out");
    System.err.println("err");
    assertLinesMatch(List.of("out"), streams.lines());
    assertLinesMatch(List.of("err"), streams.errors());
  }
}

Add test variant without parameters

Add test variant without parameters


package de.wak_sh.client;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
	public static String match(String pattern, String subject) {
		Matcher matcher = Pattern.compile(pattern).matcher(subject);
		matcher.find();
		return matcher.group(1);
	}

	public static List<String[]> matchAll(String pattern, String subject) {
		List<String[]> matches = new ArrayList<String[]>();
		Matcher matcher = Pattern.compile(pattern).matcher(subject);
		while (matcher.find()) {
			int count = matcher.groupCount();
			String[] match = new String[count];
			for (int i = 0; i < count; i++) {
				match[i] = matcher.group(i + 1);
			}
			matches.add(match);
		}
		return matches;
	}
}

package de.wak_sh.client;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {
	public static String match(String pattern, String subject) {
		Matcher matcher = Pattern.compile(pattern, Pattern.DOTALL).matcher(
				subject);
		matcher.find();
		return matcher.group(1);
	}

	public static List<String[]> matchAll(String pattern, String subject) {
		List<String[]> matches = new ArrayList<String[]>();
		Matcher matcher = Pattern.compile(pattern, Pattern.DOTALL).matcher(
				subject);
		while (matcher.find()) {
			int count = matcher.groupCount();
			String[] match = new String[count];
			for (int i = 0; i < count; i++) {
				match[i] = matcher.group(i + 1);
			}
			matches.add(match);
		}
		return matches;
	}
}

Fix regex utils for long messages

Fix regex utils for long messages