package seedu.ezdo.commons.util;

import seedu.ezdo.model.todo.ReadOnlyTask;

//@@author A0139177W
/**
 * Utility method for Recur
 */
public class RecurUtil {

    /**
     * Checks if a recurring status is valid with at least a start date and/or
     * due date present in a task. Floating tasks should not have a recurring
     * status.
     * @param task
     * @return false if the task is a floating task
     * @return true otherwise
     */
    public static boolean isRecurValid(ReadOnlyTask task) {
        assert task != null;
        String taskStartDate = task.getStartDate().toString();
        String taskDueDate = task.getDueDate().toString();

        final boolean isStartDateMissing = taskStartDate.isEmpty();
        final boolean isDueDateMissing = taskDueDate.isEmpty();
        final boolean isBothDatesMissing = isStartDateMissing && isDueDateMissing;

        final boolean isRecurring = task.getRecur().isRecur();

        if (isBothDatesMissing && isRecurring) {
            return false;
        }

        return true;
    }

}

Remove trailing whitespace in line 27

Remove trailing whitespace in line 27


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

import org.gradle.launcher.daemon.protocol.Stop;

/**
 * If the command is a Stop, asks the daemon to stop asynchronously and does not proceed with execution.
 */
public class HandleStop implements DaemonCommandAction {
    public void execute(DaemonCommandExecution execution) {
        if (execution.getCommand() instanceof Stop) {
            /*
                When the daemon was started through the DaemonMain entry point, this will cause the entire
                JVM to exit with code 1 (which is what we want) because the call to requestStopOnIdleTimeout() in
                DaemonMain#doAction will throw a DaemonStoppedException. Note that at this point we will also
                immediately tear down the client connection and remove the daemon from the registry.
            */
            execution.getDaemonStateControl().requestForcefulStop();
        } else {
            execution.proceed();
        }
    }
}

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

import org.gradle.launcher.daemon.protocol.Stop;
import org.gradle.launcher.daemon.protocol.Success;

/**
 * If the command is a Stop, asks the daemon to stop asynchronously and does not proceed with execution.
 */
public class HandleStop implements DaemonCommandAction {
    public void execute(DaemonCommandExecution execution) {
        if (execution.getCommand() instanceof Stop) {
            /*
                When the daemon was started through the DaemonMain entry point, this will cause the entire
                JVM to exit with code 1 (which is what we want) because the call to requestStopOnIdleTimeout() in
                DaemonMain#doAction will throw a DaemonStoppedException. Note that at this point we will also
                immediately tear down the client connection and remove the daemon from the registry.
            */
            execution.getDaemonStateControl().requestForcefulStop();
            execution.getConnection().dispatch(new Success(null));
        } else {
            execution.proceed();
        }
    }
}

Send a Success message back to client when handling a Stop request.


package com.saintsrobotics.frc.subsystems;

import com.saintsrobotics.frc.RobotMap;
import edu.wpi.first.wpilibj.Jaguar;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.command.Subsystem;

/**
 *
 * @author Saints Robotics
 */
public class DriveTrain extends Subsystem {
    private final RobotDrive drive;

    public DriveTrain() {
        SpeedController leftMotor = new Jaguar(RobotMap.LEFT_MOTOR);
        SpeedController rightMotor = new Jaguar(RobotMap.RIGHT_MOTOR);
        drive = new RobotDrive(leftMotor, rightMotor);
    }

    public void arcadeDrive(double moveValue, double rotateValue) {
        drive.arcadeDrive(moveValue, rotateValue);
    }

    public void stop() {
        drive.stopMotor();
    }

    public void setSafetyEnabled(boolean enabled) {
        drive.setSafetyEnabled(enabled);
    }

    protected void initDefaultCommand() {
    }
}

package com.saintsrobotics.frc.subsystems;

import com.saintsrobotics.frc.RobotMap;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.Victor;
import edu.wpi.first.wpilibj.command.Subsystem;

/**
 *
 * @author Saints Robotics
 */
public class DriveTrain extends Subsystem {
    private final RobotDrive drive;

    public DriveTrain() {
        SpeedController leftMotor = new Victor(RobotMap.LEFT_MOTOR);
        SpeedController rightMotor = new Victor(RobotMap.RIGHT_MOTOR);
        drive = new RobotDrive(leftMotor, rightMotor);
    }

    public void arcadeDrive(double moveValue, double rotateValue) {
        drive.arcadeDrive(moveValue, rotateValue);
    }

    public void stop() {
        drive.stopMotor();
    }

    public void setSafetyEnabled(boolean enabled) {
        drive.setSafetyEnabled(enabled);
    }

    protected void initDefaultCommand() {
    }
}

Use Victor instead of Jaguar

Use Victor instead of Jaguar


package com.oce.springboot.training.d02.s04.repository;

import com.oce.springboot.training.d02.s04.model.Product;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ProductRepository {

    // an in-memory list of products
    private List<Product> products = new ArrayList<>(1);

    @PostConstruct
    public void init() {
        products.add(getDefaultProduct());
    }

    @SuppressWarnings("unused")
    public Product get(int id) {
        return getDefaultProduct();
    }

    public List<Product> getAll() {
        return products;
    }

    public void create(final Product product) {
        products.add(product);
    }

    public void update(final int id, final Product product) {
        final Product currentProduct = products.get(id < products.size() ? id : 0);
        currentProduct.setName(product.getName());
    }

    public void delete(final int id) {
        products.remove(id < products.size() ? id : 0);
    }

    private Product getDefaultProduct() {
        final Product product = new Product();
        product.setId(24);
        product.setName("Dell XPS 9360");

        return product;
    }
}

package com.oce.springboot.training.d02.s04.repository;

import com.oce.springboot.training.d02.s04.model.Product;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@Repository
public class ProductRepository {

    // an in-memory list of products
    private List<Product> products = new ArrayList<>(1);

    @PostConstruct
    public void init() {
        products.add(getDefaultProduct());
    }

    @SuppressWarnings("unused")
    public Product get(int id) {
        return id < products.size() ? products.get(id) : null;
    }

    public List<Product> getAll() {
        return products;
    }

    public void create(final Product product) {
        products.add(product);
    }

    public void update(final int id, final Product product) {
        final Product currentProduct = products.get(id < products.size() ? id : 0);
        currentProduct.setName(product.getName());
    }

    public void delete(final int id) {
        products.remove(id < products.size() ? id : 0);
    }

    private Product getDefaultProduct() {
        final Product product = new Product();
        product.setId(24);
        product.setName("Dell XPS 9360");

        return product;
    }
}

[improve] Return a null product if there isn't a saved one


package hex.tree.xgboost.remote;

import water.server.ServletMeta;
import water.server.ServletProvider;

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

public class RemoteXGBoostServletProvider implements ServletProvider {

    private static final List<ServletMeta> SERVLETS = Collections.unmodifiableList(Arrays.asList(
        new ServletMeta("/3/XGBoostExecutor.upload", RemoteXGBoostUploadServlet.class)
    ));

    @Override
    public List<ServletMeta> servlets() {
        return SERVLETS;
    }

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

}

package hex.tree.xgboost.remote;

import water.server.ServletMeta;
import water.server.ServletProvider;

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

public class RemoteXGBoostServletProvider implements ServletProvider {

    private static final List<ServletMeta> SERVLETS = Collections.singletonList(
            new ServletMeta.Builder("/3/XGBoostExecutor.upload", RemoteXGBoostUploadServlet.class)
                    .withAlwaysEnabled(true) // for external XGBoost on K8s (when LeaderNodeRequestFilter is enabled)
                    .build()
    );

    @Override
    public List<ServletMeta> servlets() {
        return SERVLETS;
    }

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

}

PUBDEV-8671: Allow matrix to be uploaded to any node in external XGB on K8S


package stroom.kafka.api;

import stroom.kafka.shared.KafkaConfigDoc;

import java.util.Objects;

public class KafkaProducerSupplierKey {
    private final String uuid;
    private final String version;

    public KafkaProducerSupplierKey(final KafkaConfigDoc kafkaConfigDoc) {
        Objects.requireNonNull(kafkaConfigDoc);
        this.uuid = Objects.requireNonNull(kafkaConfigDoc.getUuid());
        this.version = Objects.requireNonNull(kafkaConfigDoc.getVersion());
    }

    public KafkaProducerSupplierKey(final String uuid, final String version) {
        this.uuid = Objects.requireNonNull(uuid);
        this.version = Objects.requireNonNull(version);
    }

    public String getUuid() {
        return uuid;
    }

    public String getVersion() {
        return version;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        final KafkaProducerSupplierKey that = (KafkaProducerSupplierKey) o;
        return uuid.equals(that.uuid) &&
                version.equals(that.version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(uuid, version);
    }

    @Override
    public String toString() {
        return "KafkaProducerSupplierKey{" +
                "uuid='" + uuid + '\'' +
                ", version='" + version + '\'' +
                '}';
    }
}

package stroom.kafka.api;

import stroom.kafka.shared.KafkaConfigDoc;

import java.util.Objects;

public class KafkaProducerSupplierKey {
    private final String uuid;
    private final String version;

    public KafkaProducerSupplierKey(final KafkaConfigDoc kafkaConfigDoc) {
        Objects.requireNonNull(kafkaConfigDoc);
        this.uuid = Objects.requireNonNull(kafkaConfigDoc.getUuid(), "KafkaConfigDoc is missing a UUID");
        this.version = Objects.requireNonNull(kafkaConfigDoc.getVersion(), "KafkaConfigDoc is missing a version");
    }

    public KafkaProducerSupplierKey(final String uuid, final String version) {
        this.uuid = Objects.requireNonNull(uuid);
        this.version = Objects.requireNonNull(version);
    }

    public String getUuid() {
        return uuid;
    }

    public String getVersion() {
        return version;
    }

    @Override
    public boolean equals(final Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        final KafkaProducerSupplierKey that = (KafkaProducerSupplierKey) o;
        return uuid.equals(that.uuid) &&
                version.equals(that.version);
    }

    @Override
    public int hashCode() {
        return Objects.hash(uuid, version);
    }

    @Override
    public String toString() {
        return "KafkaProducerSupplierKey{" +
                "uuid='" + uuid + '\'' +
                ", version='" + version + '\'' +
                '}';
    }
}

Add msgs to null check

Add msgs to null check


package io.scalecube.services.benchmarks.service;

import io.scalecube.services.api.ServiceMessage;
import java.util.concurrent.Callable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

public class BenchmarkServiceImpl implements BenchmarkService {

  @Override
  public Mono<Void> requestVoid(ServiceMessage request) {
    return Mono.empty();
  }

  @Override
  public Mono<ServiceMessage> requestOne(ServiceMessage message) {
    Callable<ServiceMessage> callable =
        () -> {
          long value = System.currentTimeMillis();
          return ServiceMessage.from(message)
              .header(SERVICE_RECV_TIME, value)
              .header(SERVICE_SEND_TIME, value)
              .build();
        };
    return Mono.fromCallable(callable);
  }

  @Override
  public Flux<ServiceMessage> infiniteStream(ServiceMessage message) {
    Callable<ServiceMessage> callable =
        () ->
            ServiceMessage.from(message)
                .header(SERVICE_SEND_TIME, System.currentTimeMillis())
                .build();
    return Mono.fromCallable(callable)
        .subscribeOn(Schedulers.newSingle("infiniteStream"))
        .repeat()
        .onBackpressureDrop();
  }
}

package io.scalecube.services.benchmarks.service;

import io.scalecube.services.api.ServiceMessage;
import java.util.concurrent.Callable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;

public class BenchmarkServiceImpl implements BenchmarkService {

  @Override
  public Mono<Void> requestVoid(ServiceMessage request) {
    return Mono.empty();
  }

  @Override
  public Mono<ServiceMessage> requestOne(ServiceMessage message) {
    Callable<ServiceMessage> callable =
        () -> {
          long value = System.currentTimeMillis();
          return ServiceMessage.from(message)
              .header(SERVICE_RECV_TIME, value)
              .header(SERVICE_SEND_TIME, value)
              .build();
        };
    return Mono.fromCallable(callable);
  }

  @Override
  public Flux<ServiceMessage> infiniteStream(ServiceMessage message) {
    Callable<ServiceMessage> callable =
        () ->
            ServiceMessage.from(message)
                .header(SERVICE_SEND_TIME, System.currentTimeMillis())
                .build();
    return Mono.fromCallable(callable)
        .subscribeOn(Schedulers.parallel())
        .repeat()
        .onBackpressureDrop();
  }
}

Set final version of stream scenario

Set final version of stream scenario


/*
 * Copyright 2018-present Facebook, 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.facebook.buck.config;

import com.facebook.buck.util.randomizedtrial.WithProbability;

/**
 * Incremental action graph mode with A/B experiment support.
 *
 * <p>Note that only a stable experiment makes sense here, as incrementality requires at least two
 * runs in a row with the feature enabled to show any effect.
 */
public enum IncrementalActionGraphMode implements WithProbability {
  ENABLED(0.5),
  DISABLED(0.5),
  EXPERIMENT(0.0),
  ;

  public static final IncrementalActionGraphMode DEFAULT = DISABLED;

  private final double probability;

  IncrementalActionGraphMode(double probability) {
    this.probability = probability;
  }

  @Override
  public double getProbability() {
    return probability;
  }
}

/*
 * Copyright 2018-present Facebook, 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.facebook.buck.config;

import com.facebook.buck.util.randomizedtrial.WithProbability;

/**
 * Incremental action graph mode with A/B experiment support.
 *
 * <p>Note that only a stable experiment makes sense here, as incrementality requires at least two
 * runs in a row with the feature enabled to show any effect.
 */
public enum IncrementalActionGraphMode implements WithProbability {
  ENABLED(0.1),
  DISABLED(0.9),
  EXPERIMENT(0.0),
  ;

  public static final IncrementalActionGraphMode DEFAULT = DISABLED;

  private final double probability;

  IncrementalActionGraphMode(double probability) {
    this.probability = probability;
  }

  @Override
  public double getProbability() {
    return probability;
  }
}

Change incremental action graph experiment back to 90/10

Summary: 50/50 was a bit too aggressive. Will incrementally increase this.

Reviewed By: bobyangyf

fbshipit-source-id: 02330da


package org.xcolab.view.pages.proposals.view.contest;

import org.xcolab.client.proposals.pojo.Proposal;
import org.xcolab.commons.CsvResponseWriter;

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

import javax.servlet.http.HttpServletResponse;

public class ContestProposalsCsvWriter extends CsvResponseWriter {

    private static final List<String> COLUMN_NAMES = Arrays.asList(
            "Author name", "Description", "Name", "Proposal review", "Rating comment", "Team"
    );
    private static final Function<Proposal, List<String>> COLUMN_EXTRACTION_FUNCTION
            = (proposal -> Arrays.asList(
            proposal.getAuthorName(),
            proposal.getDescription(),
            proposal.getName(),
            proposal.getProposalReview(),
            proposal.getRatingComment(),
            proposal.getTeam()
    ));

    public ContestProposalsCsvWriter(HttpServletResponse response) throws IOException {
        super("proposalList", COLUMN_NAMES, response);
    }

    public void writeMembers(List<Proposal> proposals) {
        proposals.stream()
                .map(COLUMN_EXTRACTION_FUNCTION)
                .forEach(this::writeRow);
    }
}

package org.xcolab.view.pages.proposals.view.contest;

import org.xcolab.client.proposals.pojo.Proposal;
import org.xcolab.commons.CsvResponseWriter;

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

import javax.servlet.http.HttpServletResponse;

public class ContestProposalsCsvWriter extends CsvResponseWriter {

    private static final List<String> COLUMN_NAMES = Arrays.asList(
            "Name",
            "Author Name",
            "Author Full Name",
            "Team",
            "Description",
            "Clean Pitch",
            "Pitch",
            "Proposal Review",
            "Rating Comment",
            "Fellow Action Comment",
            "Impact Comment Author",
            "Impact Comment Iaf",
            "All Judges finished Reviews",
            "Vote Count",
            "Supporter Count",
            "Absolute Proposal URL"
    );
    private static final Function<Proposal, List<String>> COLUMN_EXTRACTION_FUNCTION
            = (proposal -> Arrays.asList(
            proposal.getName(),
            proposal.getAuthorName(),
            proposal.getAuthor().getFullName(),
            proposal.getTeam(),
            proposal.getDescription(),
            proposal.getCleanPitch(),
            proposal.getPitch(),
            proposal.getProposalReview(),
            proposal.getRatingComment(),
            proposal.getFellowActionComment(),
            proposal.getImpactCommentAuthor(),
            proposal.getImpactCommentIaf(),
            String.valueOf(proposal.getAllJudgesReviewFinished()),
            String.valueOf(proposal.getVotesCount()),
            String.valueOf(proposal.getSupportersCount()),
            proposal.getAbsoluteProposalUrl()
    ));

    public ContestProposalsCsvWriter(HttpServletResponse response) throws IOException {
        super("proposalList", COLUMN_NAMES, response);
    }

    public void writeMembers(List<Proposal> proposals) {
        proposals.stream()
                .map(COLUMN_EXTRACTION_FUNCTION)
                .forEach(this::writeRow);
    }
}

Add additional fields to csv export

Add additional fields to csv export


package org.jenkinsci.plugins.radargun.utils;

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

import org.jenkinsci.plugins.radargun.model.Node;
import org.jenkinsci.plugins.radargun.model.NodeList;

public class ParseUtils {

    private static final String EOL_REG_EXP = "\\r?\\n";

    /**
     *
     * Parse node list. Expected format is
     * <ul>
     *   <li> Each line is one machine </li>
     *   <li> The first line is master, others are slaves </li>
     *   <li> The first sequence of the line is machine name or its IP address, eventually can continue with space and JVM options for process started on this machine </li>
     *   <li> Additional JVM option are added to default JVM option, not overwrite them </li>
     * </ul>
     *
     */
    public static NodeList parseNodeList(String nodeList) {
        String[] lines = nodeList.split(EOL_REG_EXP);
        Node master = Node.parseNode(lines[0]);
        List<Node> slaves = new ArrayList<>();
        for(int i = 1; i < lines.length; i++) {
            slaves.add(Node.parseNode(lines[i]));
        }
        return new NodeList(master, slaves);
    }

}

package org.jenkinsci.plugins.radargun.utils;

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

import org.jenkinsci.plugins.radargun.model.Node;
import org.jenkinsci.plugins.radargun.model.NodeList;

public class ParseUtils {

    /**
     *
     * Parse node list. Expected format is
     * <ul>
     *   <li> Each line is one machine </li>
     *   <li> The first line is master, others are slaves </li>
     *   <li> The first sequence of the line is machine name or its IP address, eventually can continue with space and JVM options for process started on this machine </li>
     *   <li> Additional JVM option are added to default JVM option, not overwrite them </li>
     * </ul>
     *
     */
    public static NodeList parseNodeList(String nodeList) {
        String[] lines = nodeList.split(System.lineSeparator());
        Node master = Node.parseNode(lines[0]);
        List<Node> slaves = new ArrayList<>();
        for(int i = 1; i < lines.length; i++) {
            slaves.add(Node.parseNode(lines[i]));
        }
        return new NodeList(master, slaves);
    }

}

Switch to JDK7 method for new line

Switch to JDK7 method for new line


package com.choonster.chiselfacades;

import net.minecraftforge.common.config.Configuration;

public class Config {
	public static Configuration config;

	public static boolean debugOutputEnabled;

	public static void refreshConfig() {
		debugOutputEnabled = config.getBoolean("debugOutputEnabled", "general", false, "If true, prints debug info to ChiselFacadesDebug.txt");

		if (config.hasChanged()) {
			config.save();
		}
	}
}

package com.choonster.chiselfacades;

import net.minecraftforge.common.config.Configuration;

public class Config {
	public static Configuration config;

	public static boolean debugOutputEnabled;

	public static void refreshConfig() {
		debugOutputEnabled = config.getBoolean("debugOutputEnabled", "general", false, "If true, prints debug info to ChiselFacades<Client/Server>Debug.txt");

		if (config.hasChanged()) {
			config.save();
		}
	}
}

Update config comment with proper file name


package org.canthack.tris.android.media;

import android.content.Context;
import android.media.MediaPlayer;

public class SoundEffects {
	private static MediaPlayer mp = null;

	public static void playEffect(Context context, int resource) {
		playSound(context, resource, false);
	}

	public static void playMusic(Context context, int resource) {
		playSound(context, resource, true);
	}

	public static void stop() {
		if (mp != null) {
			mp.stop();
			mp.release();
			mp = null;
		}
	}

	private static void playSound(Context context, int resource, boolean loop) {
		stop();
		mp = MediaPlayer.create(context, resource);
		mp.setLooping(loop);
		mp.start();
	}
}

package org.canthack.tris.android.media;

import android.content.Context;
import android.media.MediaPlayer;

public class SoundEffects {
	private static MediaPlayer mp = null;

	public static void playEffect(Context context, int resource) {
		playSound(context, resource, false);
	}

	public static void playMusic(Context context, int resource) {
		playSound(context, resource, true);
	}

	public static void stop() {
		if (mp != null) {
			mp.stop();
			mp.reset();
			mp.release();
			mp = null;
		}
	}

	private static void playSound(Context context, int resource, boolean loop) {
		stop();
		mp = MediaPlayer.create(context, resource);
		mp.setLooping(loop);
		mp.start();
	}
}

Fix media player log warnings.

Fix media player log warnings.


/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.answer.params;

@SuppressWarnings({"WeakerAccess", "unused"})
public enum GetResourcesParams {
    Filter,
    FirstResult,
    Ids,
    MaxResults,
    Sort,
    SystemName,
    Type;

    public static GetResourcesParams fromValue(final String value) {
        for (final GetResourcesParams param : values()) {
            if (param.name().equalsIgnoreCase(value)) {
                return param;
            }
        }

        throw new IllegalArgumentException("Unknown parameter " + value);
    }
}

/*
 * Copyright 2015 Hewlett-Packard Development Company, L.P.
 * Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
 */

package com.hp.autonomy.types.requests.idol.actions.answer.params;

@SuppressWarnings({"WeakerAccess", "unused"})
public enum GetResourcesParams {
    ExcludedIds,
    Filter,
    FirstResult,
    Ids,
    MaxResults,
    Sort,
    SystemName,
    Type;

    public static GetResourcesParams fromValue(final String value) {
        for (final GetResourcesParams param : values()) {
            if (param.name().equalsIgnoreCase(value)) {
                return param;
            }
        }

        throw new IllegalArgumentException("Unknown parameter " + value);
    }
}

Add ExcludeIds parameter to AnswerServer GetResources action

[rev. matthew.gordon]


package eic.beike.projectx.busdata;

import com.google.gson.annotations.SerializedName;

/**
 * Small data class used by gson, comparation on timestamp
 * Created by alex on 9/22/15.
 */
public class ResponseEntry implements Comparable<ResponseEntry>{
    @SerializedName("resourceSpec")
    String resource;

    @SerializedName("timestamp")
    Integer timestamp;

    @SerializedName("value")
    String value;

    @SerializedName("gatewayId")
    String busVin;

    @Override
    public int compareTo(ResponseEntry other){
        return this.timestamp - other.timestamp;
    }
}

package eic.beike.projectx.busdata;

/**
 * Small data class used by gson, comparation on timestamp
 * Created by alex on 9/22/15.
 */
public class ResponseEntry implements Comparable<ResponseEntry>{
    /**
     * The name of the resource in the api.
     */
    String resourceSpec;

    /**
     * The timestamp of when the event was recorded on the bus.
     */
    long timestamp;

    /**
     * The value of the sensor.
     */
    String value;

    /**
     * The vin number of the bus on which the sensor recorded data.
     */
    String gatewayId;

    @Override
    public int compareTo(ResponseEntry other){
        return (int) (this.timestamp - other.timestamp);
    }
}

Clean up intermidieate data class.

Clean up intermidieate data class.


// Copyright 2011 The Apache Software Foundation
//
// 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.apache.tapestry5.internal.services;

import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.internal.InternalConstants;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.annotations.Contribute;
import org.apache.tapestry5.ioc.services.ApplicationDefaults;
import org.apache.tapestry5.ioc.services.SymbolProvider;

public class ForceDevelopmentModeModule
{
    @Contribute(SymbolProvider.class)
    @ApplicationDefaults
    public static void enableDevelopmentMode(MappedConfiguration<String, Object> configuration)
    {
        configuration.add(SymbolConstants.PRODUCTION_MODE, false);
        configuration.add(InternalConstants.TAPESTRY_APP_PACKAGE_PARAM, "app.root.package");
    }
}

// Copyright 2011, 2012 The Apache Software Foundation
//
// 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.apache.tapestry5.internal.services;

import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.internal.InternalConstants;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.annotations.Contribute;
import org.apache.tapestry5.ioc.services.ApplicationDefaults;
import org.apache.tapestry5.ioc.services.SymbolProvider;

public class ForceDevelopmentModeModule
{
    @Contribute(SymbolProvider.class)
    @ApplicationDefaults
    public static void enableDevelopmentMode(MappedConfiguration<String, Object> configuration)
    {
        configuration.add(SymbolConstants.PRODUCTION_MODE, false);
        configuration.add(InternalConstants.TAPESTRY_APP_PACKAGE_PARAM, "app.root.package");
        configuration.add(SymbolConstants.HMAC_PASSPHRASE, "hmac passphrase for testing");
    }
}

Add configuration for the HMAC passphrase, to prevent service initialization errors inside unit tests that use the ClientDateEncoder service


package io.quarkus.deployment;

import java.time.Duration;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigRoot;

/**
 * This is used currently only to suppress warnings about unknown properties
 * when the user supplies something like: -Dquarkus.test.native-image-profile=someProfile
 *
 * TODO refactor code to actually use these values
 */
@ConfigRoot
public class TestConfig {

    /**
     * Duration to wait for the native image to built during testing
     */
    @ConfigItem(defaultValue = "PT5M")
    Duration nativeImageWaitTime;

    /**
     * The profile to use when testing the native image
     */
    @ConfigItem(defaultValue = "prod")
    String nativeImageProfile;
}

package io.quarkus.deployment;

import java.time.Duration;

import io.quarkus.runtime.annotations.ConfigItem;
import io.quarkus.runtime.annotations.ConfigRoot;

/**
 * This is used currently only to suppress warnings about unknown properties
 * when the user supplies something like: -Dquarkus.test.profile=someProfile or -Dquarkus.test.native-image-profile=someProfile
 *
 * TODO refactor code to actually use these values
 */
@ConfigRoot
public class TestConfig {

    /**
     * Duration to wait for the native image to built during testing
     */
    @ConfigItem(defaultValue = "PT5M")
    Duration nativeImageWaitTime;

    /**
     * The profile to use when testing the native image
     */
    @ConfigItem(defaultValue = "prod")
    String nativeImageProfile;

    /**
     * The profile to use when testing using @QuarkusTest
     */
    @ConfigItem(defaultValue = "test")
    String profile;
}

Remove false warning when quarkus.test.profile is used

Fixes: #8345


package com.andela.notelib.note;

import com.andela.notelib.R;

public enum Folders {
    GENERAL_NOTE(R.string.general_note);

    private final int folder;
    public static final int STATIC_PAPER_NOTE = 0;
    public static final int STATIC_TODO_NOTE = 1;
    public static final int STATIC_AUDIO_NOTE = 2;
    public static final int STATIC_DRAW_NOTE = 3;
    public static final int STATIC_GENERAL_NOTE = 4;

    Folders(int folder){
        this.folder = folder;
    }

    public int getFolder() {
        return folder;
    }
}

package com.andela.notelib.note;

import com.andela.notelib.R;

public enum Folders {
    ID("id"),
    FOLDERID("folderid"),
    TRASH("trash"),
    NOTEBLOCK("noteblock"),
    GENERAL_NOTE(R.string.general_note);

    private int folder;
    private String columns;

    public static final int STATIC_PAPER_NOTE = 0;
    public static final int STATIC_TODO_NOTE = 1;
    public static final int STATIC_AUDIO_NOTE = 2;
    public static final int STATIC_DRAW_NOTE = 3;
    public static final int STATIC_GENERAL_NOTE = 4;

    Folders(int folder){
        this.folder = folder;
    }
    Folders(String columns){
        this.columns = columns;
    }

    public int getFolder() {
        return folder;
    }

    public String getColumns() {
        return this.columns;
    }
}

Add columns to Folder class

Add columns to Folder class


// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;

import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;

import java.time.Duration;
import java.util.logging.Level;

/**
 * Removes expired sessions
 * <p>
 * Note: Unit test is in ApplicationRepositoryTest
 *
 * @author hmusum
 */
public class SessionsMaintainer extends ConfigServerMaintainer {
    private final boolean hostedVespa;

    SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
        super(applicationRepository, curator, flagSource, applicationRepository.clock().instant(), interval);
        this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
    }

    @Override
    protected double maintain() {
        log.log(Level.FINE, () -> "Running " + SessionsMaintainer.class.getSimpleName());
        applicationRepository.deleteExpiredLocalSessions();

        if (hostedVespa) {
            Duration expiryTime = Duration.ofMinutes(90);
            int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
            log.log(Level.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
        }

        return 1.0;
    }

}

// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.config.server.maintenance;

import com.yahoo.vespa.config.server.ApplicationRepository;
import com.yahoo.vespa.curator.Curator;
import com.yahoo.vespa.flags.FlagSource;

import java.time.Duration;
import java.util.logging.Level;

/**
 * Removes expired sessions
 * <p>
 * Note: Unit test is in ApplicationRepositoryTest
 *
 * @author hmusum
 */
public class SessionsMaintainer extends ConfigServerMaintainer {
    private final boolean hostedVespa;

    SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval, FlagSource flagSource) {
        super(applicationRepository, curator, flagSource, applicationRepository.clock().instant(), interval);
        this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
    }

    @Override
    protected double maintain() {
        applicationRepository.deleteExpiredLocalSessions();

        if (hostedVespa) {
            Duration expiryTime = Duration.ofMinutes(90);
            int deleted = applicationRepository.deleteExpiredRemoteSessions(expiryTime);
            log.log(Level.FINE, () -> "Deleted " + deleted + " expired remote sessions older than " + expiryTime);
        }

        return 1.0;
    }

}

Remove log line, already sone in superclass


package com.pseudo_sudo.openstorage;

public class OpenStorage {

}

package com.pseudo_sudo.openstorage;

import cpw.mods.fml.common.Mod;

@Mod(modid=OpenStorage.ID, name=OpenStorage.NAME, version=OpenStorage.VERSION)
public class OpenStorage {
    public static final String ID = "openstorage";
    public static final String NAME = "OpenStorage";
    public static final String VERSION = "1.7.10-0.1";
}

Add basic mod class structure.

Add basic mod class structure.


package uk.ac.ebi.quickgo.annotation.validation;

import java.util.stream.Stream;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Validate the reference values used to filter annotations.
 * There is a limited list of databases that can be used as the database portion of the identifier, defined within
 * this class.
 *
 * @author Tony Wardell
 * Date: 10/11/2016
 * Time: 13:22
 * Created with IntelliJ IDEA.
 */
class ReferenceValuesValidation implements ConstraintValidator<ReferenceValidator, String[]> {

    @Autowired
    private ReferenceDBXRefEntityValidation validator;

    @Override public void initialize(ReferenceValidator constraintAnnotation) {}

    @Override public boolean isValid(String[] values, ConstraintValidatorContext context) {
        return values == null || Stream.of(values).allMatch(validator::isValid);
    }
}

package uk.ac.ebi.quickgo.annotation.validation;

import com.google.common.base.Preconditions;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;

import static uk.ac.ebi.quickgo.annotation.validation.IdValidation.db;

/**
 * Validate the reference values used to filter annotations.
 * There is a limited list of databases that can be used as the database portion of the identifier, defined within
 * this class.
 *
 * @author Tony Wardell
 * Date: 10/11/2016
 * Time: 13:22
 * Created with IntelliJ IDEA.
 */
class ReferenceValuesValidation implements ConstraintValidator<ReferenceValidator, String[]> {

    @Autowired
    DBXRefEntityValidation validator;
    private List<String> referenceDatabases = Arrays.asList("pmid","doi","go_ref","reactome");

    @Override public void initialize(ReferenceValidator constraintAnnotation) {}

    @Override public boolean isValid(String[] values, ConstraintValidatorContext context) {
        return values == null || Stream.of(values).allMatch(this::isValid);
    }

    private boolean isValid(String value){
        Preconditions.checkArgument(Objects.nonNull(value), "The value for id cannot be null");

        if (value.trim().isEmpty()) {
            return false;
        }

        if (!value.contains(":")) {
            return true;
        }

        if (!referenceDatabases.contains(db(value))) {
            return false;
        }

        return validator.isValid(value);
    }
}

Add logic for reference validation directly to this class.


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

import com.intellij.openapi.wm.WelcomeScreen;
import com.intellij.openapi.wm.WelcomeScreenProvider;
import com.intellij.util.PlatformUtils;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * @author Konstantin Bulenkov
 */
public class DarculaWelcomeScreenProvider implements WelcomeScreenProvider {
  @Nullable
  @Override
  public WelcomeScreen createWelcomeScreen(JRootPane rootPane) {
    return new DarculaIntelliJWelcomeScreen();
  }

  @Override
  public boolean isAvailable() {
    return UIUtil.isUnderDarcula() && PlatformUtils.isIntelliJ();
  }
}

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

import com.intellij.openapi.wm.WelcomeScreen;
import com.intellij.openapi.wm.WelcomeScreenProvider;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;

/**
 * @author Konstantin Bulenkov
 */
public class DarculaWelcomeScreenProvider implements WelcomeScreenProvider {
  @Nullable
  @Override
  public WelcomeScreen createWelcomeScreen(JRootPane rootPane) {
    return new DarculaIntelliJWelcomeScreen();
  }

  @Override
  public boolean isAvailable() {
    return false; // UIUtil.isUnderDarcula() && PlatformUtils.isIntelliJ();
  }
}

Disable Darcula special welcome screen

Disable Darcula special welcome screen


class Main {
    public static void main(String[] args) {
        Foo f = new Foo();
        int[] a = new int[4];
        System.out.println(f.getMeaningOfLife());
        int i = 0;
        while (i < 4) {
            System.out.println(a[i]);
            i = i + 1;
        }
    }
}

class Foo {

    int life;

    public int getMeaningOfLife() {
        life = 42;
        return life;
    }

}

class Main {
    public static void main(String[] args) {
        int ignored = 0;
        Printer p = new Printer();
        char[] s = new char[12];
        s[0] = 'H';
        s[1] = 'e';
        s[2] = 'l';
        s[3] = 'l';
        s[4] = 'o';
        s[5] = ' ';
        s[6] = 'W';
        s[7] = 'o';
        s[8] = 'r';
        s[9] = 'l';
        s[10] = 'd';
        s[11] = '!';
        ignored = p.printString(s, 12);

        int i = 0;
        Fib f = new Fib();
        ignored = f.init();
        /* Computer Fibonacci Sequence computing each value directly. */
        while( i < 10 ) {
            System.out.println(f.fib(i));
            i = i + 1;
        }
        i = 0;
        /* Use Fibonacci Sequence iterator. */
        while( i < 10 ) {
            System.out.println(f.next());
            i = i + 1;
        }
    }
}

class Fib {
    int current;
    int previous;

    public int init() {
        current = 0;
        previous = 0;
        return 0;
    }

    public int next(){
        int val = 0;
        if (current == 0) {
            val = 1;
        } else {
            val = current + previous;
        }
        previous = current;
        current = val;
        return current;
    }

    public int fib(int n) {
        int val = 0;
        if (n < 2) {
            val = 1;
        } else {
            val = this.fib(n - 1) + this.fib(n - 2);
        }
        return val;
    }
}

class Printer {
    public int printString(char[] s, int length) {
        int i = 0;
        while (i < length) {
            System.out.print(s[i]);
            i = i + 1;
        }
        System.out.print('\n');
        return 0;
    }
}

Add example program for demo

Add example program for demo


package de.retest.recheck.ignore;

import java.util.List;

import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.diff.AttributeDifference;

public class CompoundFilter implements Filter {

	private final List<Filter> filters;

	public CompoundFilter( final List<Filter> filters ) {
		this.filters = filters;
	}

	@Override
	public boolean matches( final Element element ) {
		for ( final Filter filter : filters ) {
			if ( filter.matches( element ) ) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean matches( final Element element, final AttributeDifference attributeDifference ) {
		for ( final Filter filter : filters ) {
			if ( filter.matches( element, attributeDifference ) ) {
				return true;
			}
		}
		return false;
	}

}

package de.retest.recheck.ignore;

import java.util.List;

import de.retest.recheck.ui.descriptors.Element;
import de.retest.recheck.ui.diff.AttributeDifference;

public class CompoundFilter implements Filter {

	private final List<Filter> filters;

	public CompoundFilter( final List<Filter> filters ) {
		this.filters = filters;
	}

	@Override
	public boolean matches( final Element element ) {
		for ( final Filter filter : filters ) {
			if ( filter.matches( element ) ) {
				return true;
			}
		}
		return false;
	}

	@Override
	public boolean matches( final Element element, final AttributeDifference attributeDifference ) {
		for ( final Filter filter : filters ) {
			if ( filter.matches( element, attributeDifference ) ) {
				return true;
			}
		}
		return false;
	}

	public List<Filter> getFilters() {
		return filters;
	}

}

Add getter for enclosed filters

Add  getter for enclosed filters


package org.buddycloud.channelserver.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.xmpp.packet.Packet;

public abstract class QueueConsumer {

    private static final Logger LOGGER = Logger.getLogger(QueueConsumer.class);

    private ExecutorService executorService = Executors.newFixedThreadPool(1);
    private final BlockingQueue<Packet> queue;

    public QueueConsumer(BlockingQueue<Packet> queue) {
        this.queue = queue;
    }

    public void start() {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Packet packet = queue.take();
                        consume(packet);
                    } catch (InterruptedException e) {
                        LOGGER.error(e);
                    }
                }
            }
        });
    }

    protected abstract void consume(Packet p);

}

package org.buddycloud.channelserver.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;
import org.xmpp.packet.Packet;

public abstract class QueueConsumer {

    private static final Logger LOGGER = Logger.getLogger(QueueConsumer.class);

    private ExecutorService executorService = Executors.newFixedThreadPool(5);
    private final BlockingQueue<Packet> queue;

    public QueueConsumer(BlockingQueue<Packet> queue) {
        this.queue = queue;
    }

    public void start() {
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Packet packet = queue.take();
                        consume(packet);
                    } catch (InterruptedException e) {
                        LOGGER.error(e);
                    }
                }
            }
        });
    }

    protected abstract void consume(Packet p);

}

Increase pool size to 5, later this should be DB POOL SIZE / 2


package org.zstack.header.storage.backup;

import org.zstack.header.identity.Action;
import org.zstack.header.image.ImageConstant;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;

@Action(category = ImageConstant.ACTION_CATEGORY)
public class APIExportImageFromBackupStorageMsg extends APIMessage implements BackupStorageMessage {
    @APIParam(resourceType = BackupStorageVO.class, checkAccount = true, operationTarget = true)
    private String backupStorageUuid;

    @APIParam(nonempty = true, maxLength = 2048)
    private String installPath;

    @Override
    public String getBackupStorageUuid() {
        return backupStorageUuid;
    }

    public void setBackupStorageUuid(String backupStorageUuid) {
        this.backupStorageUuid = backupStorageUuid;
    }

    public String getInstallPath() {
        return installPath;
    }

    public void setInstallPath(String installPath) {
        this.installPath = installPath;
    }
}

package org.zstack.header.storage.backup;

import org.zstack.header.identity.Action;
import org.zstack.header.image.ImageConstant;
import org.zstack.header.message.APIMessage;
import org.zstack.header.message.APIParam;

@Action(category = ImageConstant.ACTION_CATEGORY)
public class APIExportImageFromBackupStorageMsg extends APIMessage implements BackupStorageMessage {
    @APIParam(resourceType = BackupStorageVO.class, checkAccount = true, operationTarget = true)
    private String backupStorageUuid;

    @APIParam(nonempty = true, maxLength = 2048)
    private String imageUuid;

    @Override
    public String getBackupStorageUuid() {
        return backupStorageUuid;
    }

    public void setBackupStorageUuid(String backupStorageUuid) {
        this.backupStorageUuid = backupStorageUuid;
    }

    public String getImageUuid() {
        return imageUuid;
    }

    public void setImageUuid(String imageUuid) {
        this.imageUuid = imageUuid;
    }
}

Use imageUuid instead of installPath

Use imageUuid instead of installPath

Signed-off-by: David Lee <15c338f3b79a63a0d5423e9c6562cd312918fe74@gmail.com>


package uk.ac.ebi.quickgo.index.annotation.coterms;

import java.io.IOException;
import org.junit.ClassRule;
import org.junit.rules.ExternalResource;
import org.junit.rules.TemporaryFolder;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

/**
 * Provide a temporary location for files to be output during co-occurring terms calculation.
 * Created 12/10/16
 * @author Edd
 */
public class CoTermTemporaryDataStore extends ExternalResource {

    @ClassRule
    public static TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Override
    public void before() throws IOException {
        temporaryFolder.create();
    }

    @Override
    public void after() {
        temporaryFolder.delete();
    }

    public static class Config {
        @Bean
        public Resource manualCoTermsResource() throws IOException {
            String manualCoTermsPath = temporaryFolder.newFile().getAbsolutePath();
            return new FileSystemResource(manualCoTermsPath);
        }

        @Bean
        public Resource allCoTermsResource() throws IOException {
            String allCoTermsLocation = temporaryFolder.newFile().getAbsolutePath();
            return new FileSystemResource(allCoTermsLocation);
        }
    }
}

package uk.ac.ebi.quickgo.index.annotation.coterms;

import java.io.IOException;
import org.junit.ClassRule;
import org.junit.rules.ExternalResource;
import org.junit.rules.TemporaryFolder;

/**
 * Provide a temporary location for files to be output during co-occurring terms calculation.
 * Created 12/10/16
 * @author Edd
 */
public class CoTermTemporaryDataStore extends ExternalResource {

    @ClassRule
    public static TemporaryFolder temporaryFolder = new TemporaryFolder();

    @Override
    public void before() throws IOException {
        temporaryFolder.create();
    }

    @Override
    public void after() {
        temporaryFolder.delete();
    }

    public static class Config {
    }
}

Remove specification of temporary locations for CoTerms ouput.


/*
 * Copyright (c) 2002-2020 "Neo4j,"
 * Neo4j Sweden AB [http://neo4j.com]
 *
 * This file is part of Neo4j.
 *
 * 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.neo4j.driver.net;

import java.util.Set;

/**
 * A resolver function used by the routing driver to resolve the initial address used to create the driver.
 */
@FunctionalInterface
public interface ServerAddressResolver
{
    /**
     * Resolve the given address to a set of other addresses.
     * Exceptions thrown by this method will be logged and driver will continue using the original address.
     *
     * @param address the address to resolve.
     * @return new set of addresses.
     */
    Set<ServerAddress> resolve( ServerAddress address );
}

/*
 * Copyright (c) 2002-2020 "Neo4j,"
 * Neo4j Sweden AB [http://neo4j.com]
 *
 * This file is part of Neo4j.
 *
 * 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.neo4j.driver.net;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * A resolver function used by the routing driver to resolve the initial address used to create the driver.
 */
@FunctionalInterface
public interface ServerAddressResolver
{
    /**
     * Resolve the given address to a set of other addresses.
     * It is highly recommended to shuffle the addresses returned to prevent the driver from
     * always retrying servers in a specific order.
     * Considering returning a {@link LinkedHashSet} to reserve the iteration order of a set.
     * Exceptions thrown by this method will be logged and driver will continue using the original address.
     *
     * @param address the address to resolve.
     * @return new set of addresses.
     */
    Set<ServerAddress> resolve( ServerAddress address );
}

Improve the javadoc for resolver API To suggest user defined resolver func to shuffle addresses order before returning.


package nom.bdezonia.zorbage.procedure;

public interface Procedure<U> {

	@SuppressWarnings("unchecked")
	void call(U result, U... inputs);

}

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

/**
 *
 * @author Barry DeZonia
 *
 */
public interface Procedure<U> {

	@SuppressWarnings("unchecked")
	void call(U result, U... inputs);

}

Add file header and author tag to file that needs it


public class EqualsComparison {
	void badEqualsComparision() {
		String s = "Hi there";
		Boolean b = Boolean.TRUE;

		System.out.println("equals() returned " + s.equals(b));
	}

	boolean literalStringEqualsDoNotReport(String s) {
		return "Uh huh".equals(s);
	}
}

// vim:ts=3

public class EqualsComparison {
	public interface A {}
	public interface B {}

	void badEqualsComparision() {
		String s = "Hi there";
		Boolean b = Boolean.TRUE;

		System.out.println("equals() returned " + s.equals(b));
	}

	boolean literalStringEqualsDoNotReport(String s) {
		return "Uh huh".equals(s);
	}

	boolean unrelatedInterfaceComparison(A a, B b) {
		// This should be a medium priority warning
		return a.equals(b);
	}
}

// vim:ts=3

Add test for comparing unrelated interfaces

git-svn-id: e7d6bde23f017c9ff4efd468d79d66def666766b@2645 eae3c2d3-9b19-0410-a86e-396b6ccb6ab3


package net.i2p.router;
/*
 * free (adj.): unencumbered; not under the control of others
 * Written by jrandom in 2003 and released into the public domain
 * with no warranty of any kind, either expressed or implied.
 * It probably won't make your computer catch on fire, or eat
 * your children, but it might.  Use at your own risk.
 *
 */

import net.i2p.CoreVersion;

/**
 * Expose a version string
 *
 */
public class RouterVersion {
    public final static String ID = "$Revision: 1.548 $ $Date: 2008-06-07 23:00:00 $";
    public final static String VERSION = "0.6.5";
    public final static long BUILD = 1;
    public static void main(String args[]) {
        System.out.println("I2P Router version: " + VERSION + "-" + BUILD);
        System.out.println("Router ID: " + RouterVersion.ID);
        System.out.println("I2P Core version: " + CoreVersion.VERSION);
        System.out.println("Core ID: " + CoreVersion.ID);
    }
}

package net.i2p.router;
/*
 * free (adj.): unencumbered; not under the control of others
 * Written by jrandom in 2003 and released into the public domain
 * with no warranty of any kind, either expressed or implied.
 * It probably won't make your computer catch on fire, or eat
 * your children, but it might.  Use at your own risk.
 *
 */

import net.i2p.CoreVersion;

/**
 * Expose a version string
 *
 */
public class RouterVersion {
    public final static String ID = "$Revision: 1.548 $ $Date: 2008-06-07 23:00:00 $";
    public final static String VERSION = "0.6.5";
    public final static long BUILD = 2;
    public static void main(String args[]) {
        System.out.println("I2P Router version: " + VERSION + "-" + BUILD);
        System.out.println("Router ID: " + RouterVersion.ID);
        System.out.println("I2P Core version: " + CoreVersion.VERSION);
        System.out.println("Core ID: " + CoreVersion.ID);
    }
}

BUMP to -2 for bug reporting.

BUMP to -2 for bug reporting.


/**
 * Copyright (c) 2016-2020 by the respective copyright holders.
 *
 * 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 de.csdev.ebus.core;

/**
 * Invalid controller state, thread interrupted
 *
 * @author Christian Sowada - Initial contribution
 *
 */
public class EBusControllerException extends Exception {

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

}

/**
 * Copyright (c) 2016-2020 by the respective copyright holders.
 *
 * 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 de.csdev.ebus.core;

/**
 * Invalid controller state, thread interrupted
 *
 * @author Christian Sowada - Initial contribution
 *
 */
public class EBusControllerException extends Exception {

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

    public EBusControllerException() {
        super();
    }

    public EBusControllerException(String message, Throwable cause) {
        super(message, cause);
    }

    public EBusControllerException(String message) {
        super(message);
    }

    public EBusControllerException(Throwable cause) {
        super(cause);
    }

}

Enhance the Exception to allow messages

Enhance the Exception to allow messages


package org.hummingbirdlang.nodes;

import com.oracle.truffle.api.frame.VirtualFrame;

import org.hummingbirdlang.types.realize.InferenceVisitor;

public class HBAssignmentNode extends HBExpressionNode {
  @Child private HBExpressionNode targetNode;
  @Child private HBExpressionNode valueNode;

  public HBAssignmentNode(HBExpressionNode targetNode, HBExpressionNode valueNode) {
    this.targetNode = targetNode;
    this.valueNode = valueNode;
  }

  public void accept(InferenceVisitor visitor) {
    return;
  }

  @Override
  public Object executeGeneric(VirtualFrame frame) {
    return null;
  }
}

package org.hummingbirdlang.nodes;

import com.oracle.truffle.api.frame.VirtualFrame;

import org.hummingbirdlang.types.realize.InferenceVisitor;

public class HBAssignmentNode extends HBExpressionNode {
  @Child private HBExpressionNode targetNode;
  @Child private HBExpressionNode valueNode;

  public HBAssignmentNode(HBExpressionNode targetNode, HBExpressionNode valueNode) {
    this.targetNode = targetNode;
    this.valueNode = valueNode;
  }

  public void accept(InferenceVisitor visitor) {
    return;
  }

  @Override
  public Object executeGeneric(VirtualFrame frame) {
    return null;
  }

  @Override
  public String toString() {
    StringBuilder result = new StringBuilder("HBAssignmentNode");
    result.append("(");
    result.append(this.targetNode.toString());
    result.append(" = ");
    result.append(this.valueNode.toString());
    result.append(")");
    return result.toString();
  }
}

Add custom `toString` for assignment node


package com.airhacks.nano;

import java.nio.file.Path;
import java.nio.file.Paths;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

/**
 *
 * @author airhacks.com
 */
public class ContextsTest {

    @Test
    public void extractContext() {
        Path path = Paths.get("./src/test/js/hello/duke.js");
        String actual = Contexts.extractContext(path);
        assertThat(actual, is("/src/test/js/hello/duke"));
    }

}

package com.airhacks.nano;

import java.nio.file.Path;
import java.nio.file.Paths;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;

/**
 *
 * @author airhacks.com
 */
public class ContextsTest {

    @Test
    public void extractContext() {
        Path path = Paths.get("./src/test/js/hello/duke.js");
        String actual = Contexts.extractContext(path);
        Path actualPath = Paths.get(actual);
        Path expectedPath = Paths.get("/src/test/js/hello/duke");
        assertThat(actualPath, is(expectedPath));
    }

}

Test compares path objects, not string -> should be OS-independent


package protocolsupportpocketstuff.metadata;

import protocolsupport.api.unsafe.pemetadata.PEMetaProvider;
import protocolsupport.protocol.utils.types.NetworkEntity;
import protocolsupportpocketstuff.api.util.PocketUtils;

public class MetadataProvider extends PEMetaProvider {

	@Override
	public float getEntitySize(NetworkEntity networkEntity) {
		return PocketUtils.hasCustomScale(networkEntity.getId()) ? PocketUtils.getCustomScale(networkEntity.getId()) : 1;
	}

	@Override
	public String getInteractText(NetworkEntity entity) {
		return "Interact";
	}
}

package protocolsupportpocketstuff.metadata;

import java.util.UUID;

import org.bukkit.entity.EntityType;

import protocolsupport.api.unsafe.pemetadata.PEMetaProvider;
import protocolsupportpocketstuff.api.util.PocketUtils;

public class MetadataProvider extends PEMetaProvider {

	@Override
	public String getUseText(UUID uuid, int id, EntityType entitytype) {
		return "Interact";
	}

	@Override
	public float getSizeScale(UUID uuid, int id, EntityType entitytype) {
		return PocketUtils.hasCustomScale(id) ? PocketUtils.getCustomScale(id) : 1;
	}

}

Update to latest Unsafe api.

Update to latest Unsafe api.


package ru.ydn.orienteer.junit;

import org.apache.wicket.util.tester.WicketTester;
import org.junit.runners.model.InitializationError;

import ru.ydn.orienteer.services.OrienteerModule;
import ru.ydn.orienteer.standalone.StartStandalone;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.util.Modules;

public class OrienteerTestRunner extends GuiceTestRunner
{
	private static final Injector STATIC_INJECTOR;
	static
	{
		System.out.println("Using embedded mode");
		System.setProperty(StartStandalone.PROPERTIES_FILE_NAME, StartStandalone.class.getResource("standalone.properties").toString());
		STATIC_INJECTOR = Guice.createInjector(Modules.override(new OrienteerModule()).with(new TestOrieenteerModule()));
	}

	public OrienteerTestRunner(Class<?> classToRun) throws InitializationError
	{
		super(classToRun, STATIC_INJECTOR);
	}

	@Override
	public Object createTest() {
		//Ensure that wicket tester and corresponding application started
		getInjector().getInstance(WicketTester.class);
		return super.createTest();
	}

}

package ru.ydn.orienteer.junit;

import org.apache.wicket.util.tester.WicketTester;
import org.junit.runners.model.InitializationError;

import ru.ydn.orienteer.services.OrienteerModule;
import ru.ydn.orienteer.standalone.StartStandalone;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.util.Modules;

public class OrienteerTestRunner extends GuiceTestRunner
{
	private static final Injector STATIC_INJECTOR;
	static
	{
		System.out.println("Using embedded mode");
		System.setProperty(StartStandalone.PROPERTIES_FILE_NAME, StartStandalone.class.getResource("standalone.properties").toString());
		STATIC_INJECTOR = Guice.createInjector(Modules.override(new OrienteerModule()).with(new TestOrieenteerModule()));
		Runtime.getRuntime().addShutdownHook(new Thread()
		{
			@Override
			public void run() {
				WicketTester wicketTester = STATIC_INJECTOR.getInstance(WicketTester.class);
				wicketTester.destroy();
			}
		});
	}

	public OrienteerTestRunner(Class<?> classToRun) throws InitializationError
	{
		super(classToRun, STATIC_INJECTOR);
	}

	@Override
	public Object createTest() {
		//Ensure that wicket tester and corresponding application started
		getInjector().getInstance(WicketTester.class);
		return super.createTest();
	}

}

Make shutdown of tests gracefully

Make shutdown of tests gracefully


// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

import java.io.*;
import org.xbill.DNS.utils.*;

/**
 * Key - contains a cryptographic public key for use by DNS.
 * The data can be converted to objects implementing
 * java.security.interfaces.PublicKey
 * @see DNSSEC
 *
 * @author Brian Wellington
 */

public class DNSKEYRecord extends KEYBase {

public static class Protocol {
	private Protocol() {}

	/** Key will be used for DNSSEC */
	public static final int DNSSEC = 3;
}

public static class Flags {
	private Flags() {}

	/** Key is a zone key */
	public static final int ZONE_KEY = 0x100;

	/** Key is a secure entry point key */
	public static final int SEP_KEY = 0x1;
}

DNSKEYRecord() {}

Record
getObject() {
	return new DNSKEYRecord();
}

/**
 * Creates a KEY Record from the given data
 * @param flags Flags describing the key's properties
 * @param proto The protocol that the key was created for
 * @param alg The key's algorithm
 * @param key Binary data representing the key
 */
public
DNSKEYRecord(Name name, int dclass, long ttl, int flags, int proto, int alg,
	     byte [] key)
{
	super(name, Type.KEY, dclass, ttl, flags, proto, alg, key);
}

}

// Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org)

package org.xbill.DNS;

import java.io.*;
import org.xbill.DNS.utils.*;

/**
 * Key - contains a cryptographic public key for use by DNS.
 * The data can be converted to objects implementing
 * java.security.interfaces.PublicKey
 * @see DNSSEC
 *
 * @author Brian Wellington
 */

public class DNSKEYRecord extends KEYBase {

public static class Protocol {
	private Protocol() {}

	/** Key will be used for DNSSEC */
	public static final int DNSSEC = 3;
}

public static class Flags {
	private Flags() {}

	/** Key is a zone key */
	public static final int ZONE_KEY = 0x100;

	/** Key is a secure entry point key */
	public static final int SEP_KEY = 0x1;
}

DNSKEYRecord() {}

Record
getObject() {
	return new DNSKEYRecord();
}

/**
 * Creates a DNSKEY Record from the given data
 * @param flags Flags describing the key's properties
 * @param proto The protocol that the key was created for
 * @param alg The key's algorithm
 * @param key Binary data representing the key
 */
public
DNSKEYRecord(Name name, int dclass, long ttl, int flags, int proto, int alg,
	     byte [] key)
{
	super(name, Type.DNSKEY, dclass, ttl, flags, proto, alg, key);
}

}

Set the type correctly (noticed by David Blacka).


package org.ovirt.engine.core.bll;

import org.ovirt.engine.core.compat.*;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.queries.*;
import org.ovirt.engine.core.vdsbroker.vdsbroker.SysprepHandler;

public class GetDefualtTimeZoneQuery<P extends VdcQueryParametersBase> extends QueriesCommandBase<P> {
    public GetDefualtTimeZoneQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        String timezone = Config.<String> GetValue(ConfigValues.DefaultTimeZone);
        getQueryReturnValue().setReturnValue(new KeyValuePairCompat<String, String>(SysprepHandler.getTimezoneKey(timezone),
                timezone));
    }
}

package org.ovirt.engine.core.bll;

import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.compat.KeyValuePairCompat;
import org.ovirt.engine.core.vdsbroker.vdsbroker.SysprepHandler;

public class GetDefualtTimeZoneQuery<P extends VdcQueryParametersBase> extends QueriesCommandBase<P> {
    public GetDefualtTimeZoneQuery(P parameters) {
        super(parameters);
    }

    @Override
    protected void executeQueryCommand() {
        String timezone = Config.<String> GetValue(ConfigValues.DefaultTimeZone);
        getQueryReturnValue().setReturnValue(new KeyValuePairCompat<String, String>(SysprepHandler.getTimezoneKey(timezone),
                timezone));
    }
}

core: Clean up imports on GetDefaultTimeZoneQuery

Replaced * imports with FQCNs.

Change-Id: I23ab2fe33408ef7dc05ef4048f7c1418d3e4ef3e


package fault.java.singlewriter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by timbrooks on 11/16/14.
 */
public class ResilientPromise<T> {
    public T result;
    public Throwable error;
    private Status status = Status.PENDING;
    private CountDownLatch latch = new CountDownLatch(1);

    public void deliverResult(T result) {
        this.result = result;
        status = Status.SUCCESS;
        latch.countDown();
    }

    public void deliverError(Throwable error) {
        this.error = error;
        status = Status.ERROR;
        latch.countDown();
    }

    public void await() throws InterruptedException {
        latch.await();
    }

    public T getResult() {
        return result;
    }

    public void setTimedOut() {
        status = Status.TIMED_OUT;
        latch.countDown();
    }

    public boolean isSuccessful() {
        return status == Status.SUCCESS;
    }

    public boolean isDone() {
        return status != Status.PENDING;
    }

    public boolean isError() {
        return status == Status.ERROR;
    }

    public boolean isTimedOut() {
        return status == Status.TIMED_OUT;
    }

    public enum Status {SUCCESS, ERROR, PENDING, TIMED_OUT}
}

package fault.java.singlewriter;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by timbrooks on 11/16/14.
 */
public class ResilientPromise<T> {
    public T result;
    public Throwable error;
    private Status status = Status.PENDING;
    // TODO The CountDownLatch on POSIX is leading to very high await latency. Should look at blocking in FutureTask
    // TODO which does not have the same issue. There is probably some spin and park strategy work in that case.
    private CountDownLatch latch = new CountDownLatch(1);

    public void deliverResult(T result) {
        this.result = result;
        status = Status.SUCCESS;
        latch.countDown();
    }

    public void deliverError(Throwable error) {
        this.error = error;
        status = Status.ERROR;
        latch.countDown();
    }

    public void await() throws InterruptedException {
        latch.await();
    }

    public T getResult() {
        return result;
    }

    public void setTimedOut() {
        status = Status.TIMED_OUT;
        latch.countDown();
    }

    public boolean isSuccessful() {
        return status == Status.SUCCESS;
    }

    public boolean isDone() {
        return status != Status.PENDING;
    }

    public boolean isError() {
        return status == Status.ERROR;
    }

    public boolean isTimedOut() {
        return status == Status.TIMED_OUT;
    }

    public enum Status {SUCCESS, ERROR, PENDING, TIMED_OUT}
}

Add comment about blocking work to be done


package com.dumbster.smtp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketWrapper implements IOSource {
    private Socket socket;

    public SocketWrapper(Socket socket)  {
        this.socket = socket;
    }

    public BufferedReader getInputStream() throws IOException {
        return new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
    }

    public PrintWriter getOutputStream() throws IOException {
        return new PrintWriter(socket.getOutputStream());
    }

    public void close() throws IOException {
        socket.close();
    }

}

package com.dumbster.smtp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketWrapper implements IOSource {
    private Socket socket;

    public SocketWrapper(Socket socket) throws IOException {
        this.socket = socket;
        this.socket.setSoTimeout(10000); // protects against hanged clients
    }

    public BufferedReader getInputStream() throws IOException {
        return new BufferedReader(
                new InputStreamReader(socket.getInputStream()));
    }

    public PrintWriter getOutputStream() throws IOException {
        return new PrintWriter(socket.getOutputStream());
    }

    public void close() throws IOException {
        socket.close();
    }

}

Set the socket timeout so clients can't DoS. Thank you, vladimirdyuzhev!


package org.mcupdater.ravenbot.features;

import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;

public class InfoHandler extends ListenerAdapter {

    @Override
    public void onMessage(final MessageEvent event) {
        if (event.getMessage().startsWith(".info")) {
            String[] splitMessage = event.getMessage().split(" ");
            if (splitMessage.length == 1) {

            }
        }
    }
}

package org.mcupdater.ravenbot.features;

import org.apache.commons.lang3.StringUtils;
import org.mcupdater.ravenbot.RavenBot;
import org.pircbotx.Colors;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;

import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class InfoHandler extends ListenerAdapter
{

	@Override
	public void onMessage(final MessageEvent event) {
		if (event.getMessage().startsWith(".info")) {
			String[] splitMessage = event.getMessage().split(" ");
			if (splitMessage.length == 1) {
				event.respond("No key specified.");
				return;
			}
			if (splitMessage.length == 2) {
				String key = splitMessage[1];
				try {
					PreparedStatement getInfo = RavenBot.getInstance().getPreparedStatement("getInfo");
					getInfo.setString(1, key);
					ResultSet results = getInfo.executeQuery();
					if (results.next()) {
						event.respond(Colors.BOLD + key + Colors.NORMAL + " - " + results.getString(1));
					} else {
						event.respond("No information found for: " + key);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (splitMessage.length > 2) {
				String key = splitMessage[1];
				String data = StringUtils.join(splitMessage, " ", 2, splitMessage.length);
				try {
					PreparedStatement updateInfo = RavenBot.getInstance().getPreparedStatement("updateInfo");
					updateInfo.setString(1, key);
					updateInfo.setString(2, data);
					if (updateInfo.executeUpdate() > 0) {
						event.respond("Value set.");
					} else {
						event.respond("An error occurred while trying to set the value.");
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}

Handle .info. Still needs .ilist

Handle .info.  Still needs .ilist


package com.atg.openssp.common.cache.broker;

import com.atg.openssp.common.configuration.ContextCache;
import com.atg.openssp.common.configuration.ContextProperties;
import com.atg.openssp.common.exception.EmptyHostException;

import restful.client.JsonDataProviderConnector;
import restful.context.PathBuilder;
import restful.exception.RestException;

/**
 * Generic Broker to connect to a remote webservice.
 *
 * @author André Schmer
 *
 */
public abstract class AbstractDataBroker<T> extends DataBrokerObserver {

	protected T connect(final Class<T> clazz) throws RestException, EmptyHostException {
		return new JsonDataProviderConnector<>(clazz).connectDataProvider(getRestfulContext());
	}

	protected PathBuilder getDefaulPathBuilder() {
		final PathBuilder pathBuilder = new PathBuilder();
		pathBuilder.setMaster_pw(ContextCache.instance.get(ContextProperties.MASTER_PW));
		pathBuilder.setMaster_user(ContextCache.instance.get(ContextProperties.MASTER_USER));
		pathBuilder.setServer(ContextCache.instance.get(ContextProperties.DATA_PROVIDER_URL));
		return pathBuilder;
	}
}

package com.atg.openssp.common.cache.broker;

import com.atg.openssp.common.configuration.ContextCache;
import com.atg.openssp.common.configuration.ContextProperties;
import com.atg.openssp.common.exception.EmptyHostException;

import restful.client.JsonDataProviderConnector;
import restful.context.PathBuilder;
import restful.exception.RestException;

/**
 * Generic Broker to connect to a remote webservice.
 *
 * @author André Schmer
 *
 */
public abstract class AbstractDataBroker<T> extends DataBrokerObserver {

	protected T connect(final Class<T> clazz) throws RestException, EmptyHostException {
		return new JsonDataProviderConnector<>(clazz).connectDataProvider(getRestfulContext());
	}

	protected PathBuilder getDefaulPathBuilder() {
		final PathBuilder pathBuilder = new PathBuilder();
		pathBuilder.setMaster_pw(ContextCache.instance.get(ContextProperties.MASTER_PW));
		pathBuilder.setMaster_user(ContextCache.instance.get(ContextProperties.MASTER_USER));
		pathBuilder.setServer(ContextCache.instance.get(ContextProperties.DATA_PROVIDER_URL));
		return pathBuilder;
	}

	/**
	 * @return the context of the restful service to connect with {see PathBuilder}.
	 * @throws EmptyHostException
	 */
	public abstract PathBuilder getRestfulContext() throws EmptyHostException;
}

Move getRestfulContext() from superclass to this.


package me.jacobcrofts.simplestructureloader.api;

import me.jacobcrofts.simplestructureloader.util.Selection;

public final class StructureAPI {

	private StructureAPI() {}

	public static void writeToFile(String path, Selection selection) {

	}

}

package me.jacobcrofts.simplestructureloader.api;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

import me.jacobcrofts.simplestructureloader.util.Selection;

public final class StructureAPI {

	private StructureAPI() {}

	public static void writeToFile(String path, Selection selection) throws IOException {
		FileWriter writer = new FileWriter(path);
		writer.write(selection.toJSON().toJSONString());
		writer.close();
	}

//	playerData = (JSONObject) new JSONParser().parse(new FileReader(f));

}

Add feature: API class that writes selection to file


package org.gbif.checklistbank.service.mybatis.model;

import org.gbif.checklistbank.model.RawUsage;

import java.util.Date;
import java.util.UUID;

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

public class RawUsageTest {

  @Test
  public void testEquals() throws Exception {
    final int key = 100000001;
    final String json = "xeghwax542tgld@";
    final UUID dkey = UUID.randomUUID();

    RawUsage raw = new RawUsage();
    raw.setUsageKey(key);
    raw.setDatasetKey(dkey);
    raw.setLastCrawled(new Date());
    raw.setJson(json);

    RawUsage raw2 = new RawUsage();
    raw2.setUsageKey(key);
    raw2.setDatasetKey(dkey);
    raw2.setLastCrawled(new Date());
    raw2.setJson(json);

    Assert.assertEquals(raw, raw2);

    raw.setLastCrawled(null);
    Assert.assertNotEquals(raw, raw2);

    raw2.setLastCrawled(null);
    Assert.assertEquals(raw, raw2);
  }
}

package org.gbif.checklistbank.service.mybatis.model;

import org.gbif.checklistbank.model.RawUsage;
import org.junit.Assert;
import org.junit.Test;

import java.util.Date;
import java.util.UUID;

public class RawUsageTest {

  @Test
  public void testEquals() throws Exception {
    final int key = 100000001;
    final String json = "xeghwax542tgld@";
    final UUID dkey = UUID.randomUUID();
    final Date now = new Date();

    RawUsage raw = new RawUsage();
    raw.setUsageKey(key);
    raw.setDatasetKey(dkey);
    raw.setLastCrawled(now);
    raw.setJson(json);

    RawUsage raw2 = new RawUsage();
    raw2.setUsageKey(key);
    raw2.setDatasetKey(dkey);
    raw2.setLastCrawled(now);
    raw2.setJson(json);

    Assert.assertEquals(raw, raw2);

    raw.setLastCrawled(null);
    Assert.assertNotEquals(raw, raw2);

    raw2.setLastCrawled(null);
    Assert.assertEquals(raw, raw2);
  }
}

Fix bad test that sometimes fails on slow jenkins


package org.ale.app;

import static org.junit.Assert.assertEquals;

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

public class TwitterLinkCreatorTest {

    private String twitterAddress;

    @Before
    public void setup(){
        twitterAddress = "@foobar", result);
	}

	@Test
	public void shouldProcessSeveralTwitterNames() {
		String result = TwitterLinkCreator.process("@foo, @bar");

        assertEquals(twitterAddress +"foo\">@foo, @bar", result);
	}

	@Test
	public void shouldProcessNameWithUnderscore() {
		String result = TwitterLinkCreator.process("@foo_bar");

        assertEquals(twitterAddress +"foo_bar\">@foo_bar", result);
	}
}

package org.ale.app;

import static org.junit.Assert.assertEquals;

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

public class TwitterLinkCreatorTest {

    private String twitterAddress;

    @Before
    public void setup(){
        twitterAddress = "@foobar", result);
	}

	@Test
	public void shouldProcessSeveralTwitterNames() {
		String result = TwitterLinkCreator.process("@foo, @bar");

        assertEquals(twitterAddress +"foo\">@foo, "+twitterAddress+"bar\">@bar", result);
	}

	@Test
	public void shouldProcessNameWithUnderscore() {
		String result = TwitterLinkCreator.process("@foo_bar");

        assertEquals(twitterAddress +"foo_bar\">@foo_bar", result);
	}
}

Refactor tests: extracted the last twitter address to the field


package dmillerw.quadrum.common.lib.data;

import cpw.mods.fml.common.registry.GameData;
import net.minecraft.item.Item;
import net.minecraft.util.MathHelper;

import java.util.Random;

/**
 * @author dmillerw
 */
public class Drop {

    private static Random random = new Random();

    private Item dropItem;

    public String item;
    public int damage = 0;
    public String amount = "1";

    public Item getDrop() {
        if (dropItem == null) {
            dropItem = GameData.getItemRegistry().getRaw(item);
        }
        return dropItem;
    }

    public int getDropAmount() {
        if (!amount.contains("-")) {
            return Integer.parseInt(amount);
        } else {
            int low = Integer.parseInt(amount.substring(0, amount.indexOf("-")));
            int high = Integer.parseInt(amount.substring(amount.indexOf("-") + 1, amount.length()));
            return MathHelper.getRandomIntegerInRange(random, low, high);
        }
    }
}

package dmillerw.quadrum.common.lib.data;

import cpw.mods.fml.common.registry.GameData;
import net.minecraft.item.Item;
import net.minecraft.util.MathHelper;

import java.util.Random;

/**
 * @author dmillerw
 */
public class Drop {

    private static Random random = new Random();

    private Item dropItem;

    public String item = "";
    public int damage = 0;
    public String amount = "1";

    public Item getDrop() {
        if (dropItem == null) {
            dropItem = GameData.getItemRegistry().getRaw(item);
        }
        return dropItem;
    }

    public int getDropAmount() {
        if (!amount.contains("-")) {
            return Integer.parseInt(amount);
        } else {
            int low = Integer.parseInt(amount.substring(0, amount.indexOf("-")));
            int high = Integer.parseInt(amount.substring(amount.indexOf("-") + 1, amount.length()));
            return MathHelper.getRandomIntegerInRange(random, low, high);
        }
    }
}

Add default drop item string to prevent NPE


package org.tinylog;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Static logger for issuing log entries.
 */
public final class Logger {

	private static final ConcurrentMap<String, TaggedLogger> loggers = new ConcurrentHashMap<>();
	private static final TaggedLogger logger = new TaggedLogger(null);

	/** */
	private Logger() {
	}

	/**
	 * Retrieves a tagged logger instance. Category tags are case-sensitive. If a tagged logger does not yet exists for
	 * the passed tag, a new logger will be created. This method always returns the same logger instance for the same
	 * tag.
	 *
	 * @param tag The case-sensitive category tag of the requested logger, or {@code null} for receiving an untagged
	 *            logger
	 * @return Logger instance
	 */
	public static TaggedLogger tag(String tag) {
		if (tag == null || tag.isEmpty()) {
			return logger;
		} else {
			return loggers.computeIfAbsent(tag, TaggedLogger::new);
		}
	}

}

package org.tinylog;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * Static logger for issuing log entries.
 */
public final class Logger {

	private static final ConcurrentMap<String, TaggedLogger> loggers = new ConcurrentHashMap<>();

	/** */
	private Logger() {
	}

	/**
	 * Retrieves a tagged logger instance. Category tags are case-sensitive. If a tagged logger does not yet exists for
	 * the passed tag, a new logger will be created. This method always returns the same logger instance for the same
	 * tag.
	 *
	 * @param tag The case-sensitive category tag of the requested logger, or {@code null} for receiving an untagged
	 *            logger
	 * @return Logger instance
	 */
	public static TaggedLogger tag(String tag) {
		if (tag == null || tag.isEmpty()) {
			return loggers.computeIfAbsent("", untagged -> new TaggedLogger(null));
		} else {
			return loggers.computeIfAbsent(tag, TaggedLogger::new);
		}
	}

}

Store untagged root logger in map together with all tagged loggers


package com.geniusclone.screens;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.geniusclone.game.GameplayClassic;

public class GameScreen implements Screen {

    private Game myGame;
    private GameplayClassic gameplay;

    public GameScreen(Game g) {
        myGame = g;
        gameplay = new GameplayClassic();
        Gdx.input.setInputProcessor(gameplay);
    }

    @Override
    public void render(float delta) {
        gameplay.render();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void show() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void dispose() {
        gameplay.dispose();
    }
}

package com.geniusclone.screens;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.geniusclone.game.GameplayClassic;

public class GameScreen implements Screen {

    private Game myGame;
    private GameplayClassic gameplay;

    public GameScreen(Game g) {
        myGame = g;
        gameplay = new GameplayClassic(myGame);
        Gdx.input.setInputProcessor(gameplay);
    }

    @Override
    public void render(float delta) {
        gameplay.render();
    }

    @Override
    public void resize(int width, int height) {
    }

    @Override
    public void show() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void pause() {
    }

    @Override
    public void resume() {
    }

    @Override
    public void dispose() {
        gameplay.dispose();
    }
}

Fix game screen missing parameter

Fix game screen missing parameter


package com.kishorebabu.popularmovies;

import com.kishorebabu.popularmovies.model.Movie;
import com.kishorebabu.popularmovies.model.MoviesList;

import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;

/**
 * Created by Kishore on 2/28/2016.
 */
public interface MovieDBApi {

    @GET("movie/{movieID}")
    Call<Movie> getMovieByID(@Path("movieID") int movieID, @Query("api_key") String apiKey);

    @GET("discover/movie?sort_by=popularity.desc")
    Call<MoviesList> getMostPopularMovies(@Query("page") int page, @Query("api_key") String apiKey);

    @GET("discover/movie/?sort_by=vote_average.desc")
    Call<MoviesList> getHighestRatedMovies(@Query("page") int page, @Query("api_key") String apiKey);
}

package com.kishorebabu.popularmovies;

import com.kishorebabu.popularmovies.model.Movie;
import com.kishorebabu.popularmovies.model.MoviesList;

import retrofit.Call;
import retrofit.http.GET;
import retrofit.http.Path;
import retrofit.http.Query;

/**
 * Created by Kishore on 2/28/2016.
 */
public interface MovieDBApi {

    @GET("movie/{movieID}")
    Call<Movie> getMovieByID(@Path("movieID") int movieID, @Query("api_key") String apiKey);

    @GET("discover/movie?sort_by=popularity.desc")
    Call<MoviesList> getMostPopularMovies(@Query("page") int page, @Query("api_key") String apiKey);

    @GET("discover/movie?sort_by=vote_average.desc")
    Call<MoviesList> getHighestRatedMovies(@Query("page") int page, @Query("vote_count.gte") int minVoteCount, @Query("language") String language, @Query("api_key") String apiKey);
}

Change query for highest rated to have more query parameters


package seedu.address.commons.core;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.emeraldo.commons.core.Config;

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

public class ConfigTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void toString_defaultObject_stringReturned() {
        String defaultConfigAsString = "App title : Emeraldo\n" +
                "Current log level : INFO\n" +
                "Preference file Location : preferences.json\n" +
                "Local data file location : data/addressbook.xml\n" +
                "AddressBook name : MyAddressBook";

        assertEquals(defaultConfigAsString, new Config().toString());
    }

    @Test
    public void equalsMethod(){
        Config defaultConfig = new Config();
        assertFalse(defaultConfig.equals(null));
        assertTrue(defaultConfig.equals(defaultConfig));
    }

}

package seedu.address.commons.core;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import seedu.emeraldo.commons.core.Config;

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

public class ConfigTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void toString_defaultObject_stringReturned() {
        String defaultConfigAsString = "App title : Emeraldo\n" +
                "Current log level : INFO\n" +
                "Preference file Location : preferences.json\n" +
                "Local data file location : data/addressbook.xml\n" +
                "Emeraldo name : MyTaskManager";

        assertEquals(defaultConfigAsString, new Config().toString());
    }

    @Test
    public void equalsMethod(){
        Config defaultConfig = new Config();
        assertFalse(defaultConfig.equals(null));
        assertTrue(defaultConfig.equals(defaultConfig));
    }

}

Change occurrence of addressbook to emeraldo


package squeek.quakemovement;

import api.player.server.ServerPlayerAPI;
import api.player.server.ServerPlayerBase;

public class QuakeServerPlayer extends ServerPlayerBase
{

	private boolean wasVelocityChangedBeforeFall = false;

	public QuakeServerPlayer(ServerPlayerAPI playerapi)
	{
		super(playerapi);
	}

	@Override
	public void fall(float fallDistance, float damageMultiplier)
	{
		wasVelocityChangedBeforeFall = this.playerAPI.getVelocityChangedField() || this.player.velocityChanged;

		if (ModConfig.INCREASED_FALL_DISTANCE != 0.0D)
		{
			fallDistance -= ModConfig.INCREASED_FALL_DISTANCE;
		}
		super.fall(fallDistance, fallDistance);

		this.playerAPI.setVelocityChangedField(wasVelocityChangedBeforeFall);
		this.player.velocityChanged = wasVelocityChangedBeforeFall;
	}
}

package squeek.quakemovement;

import api.player.server.ServerPlayerAPI;
import api.player.server.ServerPlayerBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.event.entity.living.LivingFallEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;

public class QuakeServerPlayer extends ServerPlayerBase
{

	private boolean wasVelocityChangedBeforeFall = false;

	public QuakeServerPlayer(ServerPlayerAPI playerapi)
	{
		super(playerapi);

		MinecraftForge.EVENT_BUS.register(this);
	}

	@SubscribeEvent
	public void onLivingFall(LivingFallEvent event)
	{
		if (!(event.entity instanceof EntityPlayer))
			return;

		if (ModConfig.INCREASED_FALL_DISTANCE != 0.0D)
		{
			event.distance = (float) (event.distance - ModConfig.INCREASED_FALL_DISTANCE);
		}
	}

	@Override
	public void beforeFall(float fallDistance, float damageMultiplier)
	{
		wasVelocityChangedBeforeFall = this.playerAPI.getVelocityChangedField() || this.player.velocityChanged;
	}

	@Override
	public void afterFall(float fallDistance, float damageMultiplier)
	{
		this.playerAPI.setVelocityChangedField(wasVelocityChangedBeforeFall);
		this.player.velocityChanged = wasVelocityChangedBeforeFall;
	}
}

Fix fall damage being applied wrong

Fix fall damage being applied wrong