/*
Copyright 2012 Opera Software ASA
Copyright 2011 Software Freedom Conservancy
Copyright 2011 WebDriver committers

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.opera.core.systems.testing;

import com.opera.core.systems.OperaProduct;

import org.openqa.selenium.Platform;

public class IgnoreComparator {

  private OperaProduct currentProduct = OperaProduct.DESKTOP;
  private Platform currentPlatform = Platform.getCurrent();

  public void setCurrentProduct(OperaProduct product) {
    currentProduct = product;
  }

  public void setCurrentPlatform(Platform platform) {
    currentPlatform = platform;
  }

  public boolean shouldIgnore(Ignore ignoreAnnotation) {
    if (ignoreAnnotation == null) {
      return false;
    }

    for (OperaProduct product : ignoreAnnotation.products()) {
      if (product == currentProduct) {
        return true;
      }
    }

    for (Platform platform : ignoreAnnotation.platforms()) {
      if (platform.is(currentPlatform)) {
        return true;
      }
    }

    return false;
  }

}

/*
Copyright 2012 Opera Software ASA
Copyright 2011 Software Freedom Conservancy
Copyright 2011 WebDriver committers

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.opera.core.systems.testing;

import com.opera.core.systems.OperaProduct;

import org.openqa.selenium.Platform;

public class IgnoreComparator {

  private OperaProduct currentProduct = OperaProduct.DESKTOP;
  private Platform currentPlatform = Platform.getCurrent();

  public void setCurrentProduct(OperaProduct product) {
    currentProduct = product;
  }

  public void setCurrentPlatform(Platform platform) {
    currentPlatform = platform;
  }

  public boolean shouldIgnore(Ignore ignoreAnnotation) {
    if (ignoreAnnotation == null) {
      return false;
    }

    for (OperaProduct product : ignoreAnnotation.products()) {
      if (product == currentProduct) {
        return true;
      }
    }

    for (Platform platform : ignoreAnnotation.platforms()) {
      if (platform == currentPlatform) {
        return true;
      }
    }

    return false;
  }

}

Revert "For platforms, we want to match ANY however"

This reverts commit d0c2a9ca30ffb04a16f155d804d531dd31670b72.


package testclasses;

public class SimpleCastSuccess1 {

   public static void main(String[] args) {

   }

    /**
     * x has Type TOP, y has typ PUBLIC, return value is dynamic
     */
   public static int m(int x, int y) {
      int z = castTopToDyn(x);
      z += castPubToDyn(y);
      if (z >= 0) {
         return 1;
      } else {
         return 0;
      }
   }

   private static int castTopToDyn(int x) {
      return x;
   }

   private static int castPubToDyn(int x) {
      return x;
   }

}

package testclasses;

import de.unifreiburg.cs.proglang.jgs.support.Casts;

public class SimpleCastFail1 {

   public static void main(String[] args) {

   }

    /**
     * x has Type TOP, y has typ PUBLIC, return value is dynamic
     */
   public static int m(int x, int y) {
      int z = Casts.cast("[top] ~> ?", x);
      z += Casts.cast("pub ~> ?", y);
      if (z >= 0) {
         return 1;
      } else {
         return 0;
      }
   }

   private static int castTopToDyn(int x) {
      return x;
   }

   private static int castPubToDyn(int x) {
      return x;
   }

}

Add a frist DynamicAnalyzer test for casts


package net.sf.jabref.logic.l10n;

import java.util.Map;
import java.util.TreeMap;

public class Languages {

    public static final Map<String, String> LANGUAGES;

    static {
        LANGUAGES = new TreeMap<>();

        // LANGUAGES contains mappings for supported languages.
        LANGUAGES.put("Dansk", "da");
        LANGUAGES.put("Deutsch", "de");
        LANGUAGES.put("English", "en");
        LANGUAGES.put("Espaol", "es");
        LANGUAGES.put("Persian (?????)", "fa");
        LANGUAGES.put("Fran\u00E7ais", "fr");
        LANGUAGES.put("Bahasa Indonesia", "in");
        LANGUAGES.put("Italiano", "it");
        LANGUAGES.put("Japanese", "ja");
        LANGUAGES.put("Nederlands", "nl");
        LANGUAGES.put("Norsk", "no");
        LANGUAGES.put("Brazilian Portugese", "pt_BR");
        LANGUAGES.put("Russian", "ru");
        LANGUAGES.put("Turkish", "tr");
        LANGUAGES.put("Vietnamese", "vi");
        LANGUAGES.put("Simplified Chinese", "zh");
    }

}

package net.sf.jabref.logic.l10n;

import java.util.Map;
import java.util.TreeMap;

public class Languages {

    public static final Map<String, String> LANGUAGES;

    static {
        LANGUAGES = new TreeMap<>();

        // LANGUAGES contains mappings for supported languages.
        LANGUAGES.put("Dansk", "da");
        LANGUAGES.put("Deutsch", "de");
        LANGUAGES.put("English", "en");
        LANGUAGES.put("Español", "es");
        LANGUAGES.put("Persian (فارسی)", "fa");
        LANGUAGES.put("Fran\u00E7ais", "fr");
        LANGUAGES.put("Bahasa Indonesia", "in");
        LANGUAGES.put("Italiano", "it");
        LANGUAGES.put("Japanese", "ja");
        LANGUAGES.put("Nederlands", "nl");
        LANGUAGES.put("Norsk", "no");
        LANGUAGES.put("Brazilian Portugese", "pt_BR");
        LANGUAGES.put("Russian", "ru");
        LANGUAGES.put("Turkish", "tr");
        LANGUAGES.put("Vietnamese", "vi");
        LANGUAGES.put("Simplified Chinese", "zh");
    }

}

Fix persian name caused by encoding issue.


/**
 * $$\\ToureNPlaner\\$$
 */
package algorithms;

import graphrep.GraphRep;

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

/**
 * @author Niklas Schnelle, Peter Vollmer
 *
 */
public class ShortestPathFactory extends GraphAlgorithmFactory {

	public ShortestPathFactory(GraphRep graph) {
		super(graph);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see algorithms.AlgorithmFactory#createAlgorithm()
	 */
	@Override
	public Algorithm createAlgorithm() {
		return new ShortestPath(graph);
	}

	@Override
	public String getURLSuffix() {
		return "sp";
	}

	@Override
	public String getAlgName() {
		return "Shortest Path";
	}

	@Override
	public int getVersion() {
		return 1;
	}

	@Override
	public List<Map<String, Object>> getPointConstraints() {
		return null;
	}

	@Override
	public Map<String, Object> getConstraints() {
		Map<String, Object> map = new HashMap<String, Object>(2);
		map.put("minPoints", Integer.valueOf(2));
		map.put("sourceIsTarget", Boolean.FALSE);
		return map;
	}

}

/**
 * $$\\ToureNPlaner\\$$
 */
package algorithms;

import graphrep.GraphRep;

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

/**
 * @author Niklas Schnelle, Peter Vollmer
 *
 */
public class ShortestPathFactory extends GraphAlgorithmFactory {

	public ShortestPathFactory(GraphRep graph) {
		super(graph);
	}

	/*
	 * (non-Javadoc)
	 *
	 * @see algorithms.AlgorithmFactory#createAlgorithm()
	 */
	@Override
	public Algorithm createAlgorithm() {
		return new ShortestPath(graph);
	}

	@Override
	public String getURLSuffix() {
		return "sps";
	}

	@Override
	public String getAlgName() {
		return "Shortest Path Simple";
	}

	@Override
	public int getVersion() {
		return 1;
	}

	@Override
	public List<Map<String, Object>> getPointConstraints() {
		return null;
	}

	@Override
	public Map<String, Object> getConstraints() {
		Map<String, Object> map = new HashMap<String, Object>(2);
		map.put("minPoints", Integer.valueOf(2));
		map.put("sourceIsTarget", Boolean.FALSE);
		return map;
	}

}

Change name for non CH Shortest Path

Change name for non CH Shortest Path

it's now named "Shortest Path Simple" so we can test both with the same
server without recompiling


package lanchat.client;

import java.io.IOException;
import java.util.ArrayList;

import javafx.application.Platform;
import lanchat.common.ServerMessage;
import lanchat.common.ServerMessageType;
import lanchat.gui.ClientGUI;

public class MessageListener extends Thread{

  private Client client;
  private boolean running;
  private ClientGUI gui;

  public MessageListener(Client client, ClientGUI gui) {
    this.client = client;
    this.gui = gui;
  }

  public void run() {
    running = true;
    while(running ){
      try {
        ServerMessage serverMessage = (ServerMessage) client.getInputStream().readObject();

        ServerMessageType type = serverMessage.getType();
        String message = serverMessage.getMessage();
        String username = serverMessage.getUsername();
        ArrayList<String> usernames = serverMessage.getUsernames();

        switch (type) {
          case MESSAGE:
            //TODO update gui (display message)
            break;
          case CLIENTLIST:
            //TODO update gui (update clientlist)
            break;
        }
      } catch (ClassNotFoundException e) {
        //can't do anything if class is not found
      } catch (IOException e) {
       //server has closed the connection
        startGuiLoginView("Connection to server lost");
        break;
      }
    }
  }

  public void shutdown() {
    running = false;
  }

  private void startGuiLoginView(String reason) {
    Platform.runLater(new Runnable() {

      @Override
      public void run() {
        gui.startLoginView();
        gui.setLoginErrorText(reason);
      }
    });
  }
}

package lanchat.client;

import java.io.IOException;
import java.util.ArrayList;

import javafx.application.Platform;
import lanchat.common.ServerMessage;
import lanchat.common.ServerMessageType;
import lanchat.gui.ClientGUI;

public class MessageListener extends Thread{

  private Client client;
  private boolean running;
  private ClientGUI gui;

  public MessageListener(Client client, ClientGUI gui) {
    this.client = client;
    this.gui = gui;
  }

  public void run() {
    running = true;
    while(running ){
      try {
        ServerMessage serverMessage = (ServerMessage) client.getInputStream().readObject();

        ServerMessageType type = serverMessage.getType();
        String message = serverMessage.getMessage();
        String username = serverMessage.getUsername();
        ArrayList<String> usernames = serverMessage.getUsernames();

        switch (type) {
          case MESSAGE:
            //TODO update gui (display message)
            break;
          case CLIENTLIST:
            Platform.runLater(new Runnable() {

              @Override
              public void run() {
                gui.setClientList(usernames);
              }
            });
            break;
        }
      } catch (ClassNotFoundException e) {
        //can't do anything if class is not found
      } catch (IOException e) {
       //server has closed the connection
        startGuiLoginView("Connection to server lost");
        break;
      }
    }
  }

  public void shutdown() {
    running = false;
  }

  private void startGuiLoginView(String reason) {
    Platform.runLater(new Runnable() {

      @Override
      public void run() {
        gui.startLoginView();
        gui.setLoginErrorText(reason);
      }
    });
  }
}

Update gui on receiving CLIENTLIST message


package radicalzephyr;

public class WebFX {

}

package radicalzephyr;

import java.util.ArrayList;
import java.util.Map;
import java.util.Map.Entry;
import java.util.List;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.web.WebView;
import javafx.scene.web.WebEngine;
import javafx.stage.Stage;

public class WebFX extends Application {
    private String domain;
    private String port;
    private String width;
    private String height;

    @Override
    public void init() throws Exception {
        Map<String, String> args = getParameters().getNamed();

        this.domain = args.getOrDefault("domain", "localhost");
        this.port   = args.getOrDefault("port", "3000");

        this.width  = args.getOrDefault("width", "1024");
        this.height = args.getOrDefault("height", "768");
    }

    @Override
    public void start(Stage primaryStage) {
        WebView browser = new WebView();
        WebEngine engine = browser.getEngine();

        String domain = "localhost";
        String port = "9393";

        engine.load("http://" + domain + ":" + port);

        int width = 1024;
        int height = 768;
        Scene s = new Scene(browser, width, height);

        primaryStage.setScene(s);
        primaryStage.show();
    }

    private static String[] constructArgVector(Map<String, Object> options) {
        List<String> args = new ArrayList<String>();

        for (Entry<String, Object> option: options.entrySet()) {
            String argName  = option.getKey();
            String argValue = option.getValue().toString();
            args.add(String.format("--%s=%s", argName, argValue));
        }

        return args.toArray(new String[0]);
    }

    public static void start(Map<String, Object> options) {
        String[] args = constructArgVector(options);
        launch(args);
    }

    public static void main(String[] args) {
        launch(args);
    }

}

Implement first pass at JavaFX Application shim


package com.graphhopper.api;

import com.graphhopper.util.shapes.GHPoint;
import org.junit.Test;

import static junit.framework.TestCase.assertTrue;
import static org.junit.Assert.assertFalse;

public class GHMRequestTest {
    @Test
    public void testCompact() {
        GHMRequest request = new GHMRequest();
        for (int i = 0; i < 3; i++) {
            request.addFromPoint(new GHPoint());
            request.addFromPointHint("");
        }

        request.addToPoint(new GHPoint());
        request.addToPointHint("");

        request.compactPointHints();
        assertTrue(request.getToPointHints().isEmpty());
        assertTrue(request.getFromPointHints().isEmpty());
    }

    @Test
    public void testCompact2() {
        GHMRequest request = new GHMRequest();
        for (int i = 0; i < 3; i++) {
            request.addFromPoint(new GHPoint());
            request.addFromPointHint("");
        }

        request.addToPoint(new GHPoint());
        request.addToPointHint("x");

        request.compactPointHints();
        assertFalse(request.getToPointHints().isEmpty());
        assertTrue(request.getFromPointHints().isEmpty());
    }
}

package com.graphhopper.api;

import com.graphhopper.util.shapes.GHPoint;
import org.junit.jupiter.api.Test;

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

public class GHMRequestTest {
    @Test
    public void testCompact() {
        GHMRequest request = new GHMRequest();
        for (int i = 0; i < 3; i++) {
            request.addFromPoint(new GHPoint());
            request.addFromPointHint("");
        }

        request.addToPoint(new GHPoint());
        request.addToPointHint("");

        request.compactPointHints();
        assertTrue(request.getToPointHints().isEmpty());
        assertTrue(request.getFromPointHints().isEmpty());
    }

    @Test
    public void testCompact2() {
        GHMRequest request = new GHMRequest();
        for (int i = 0; i < 3; i++) {
            request.addFromPoint(new GHPoint());
            request.addFromPointHint("");
        }

        request.addToPoint(new GHPoint());
        request.addToPointHint("x");

        request.compactPointHints();
        assertFalse(request.getToPointHints().isEmpty());
        assertTrue(request.getFromPointHints().isEmpty());
    }
}

Update another test, trigger build

Update another test, trigger build


package example;

import java.util.Collections;
import java.util.Map;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Reference;
import org.springframework.data.keyvalue.annotation.KeySpace;
import org.springframework.data.redis.core.index.Indexed;

import lombok.Data;

@Data
@KeySpace("persons")
class Person {

	@Id String id;
	@Indexed String firstname;
	String lastname;

	Map<String, String> attributes = Collections.emptyMap();

	City city;

	@Reference Person mother;
}

package example;

import java.util.Collections;
import java.util.Map;

import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Reference;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.index.Indexed;

import lombok.Data;

@Data
@RedisHash("persons")
class Person {

	@Id String id;
	@Indexed String firstname;
	String lastname;

	Map<String, String> attributes = Collections.emptyMap();

	City city;

	@Reference Person mother;
}

Use the @RedisHash annotation instead of @KeySpace.

Redis Repositories use @RedisHash to identify the repository belongs to the Redis module and to create the appropriate repository type. We now use the @RedisHash annotation instead of the previous @KeySpace annotation.


package com.timostaudinger.dailydose.trigger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

@WebListener
public class Trigger implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
//        scheduler.scheduleAtFixedRate(new DailyRunner(), 0, 1, TimeUnit.MINUTES);
        // TODO
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

package com.timostaudinger.dailydose.trigger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@WebListener
public class Trigger implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        LocalDateTime localNow = LocalDateTime.now();
        ZoneId currentZone = ZoneId.of("America/New_York");
        ZonedDateTime zonedNow = ZonedDateTime.of(localNow, currentZone);
        ZonedDateTime zonedExecutionTime;
        zonedExecutionTime = zonedNow.withHour(8).withMinute(0).withSecond(0);
        if (zonedNow.compareTo(zonedExecutionTime) > 0)
            zonedExecutionTime = zonedExecutionTime.plusDays(1);

        Duration duration = Duration.between(zonedNow, zonedExecutionTime);
        long initalDelay = duration.getSeconds();

        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new DailyRunner(), initalDelay,
                24 * 60 * 60, TimeUnit.SECONDS);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

Configure Timer. Calculate inital delay in order to start the execution daily at 9am EST.


package bamboo.crawl;

import bamboo.pandas.PandasAgency;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.BindBean;
import org.skife.jdbi.v2.sqlobject.SqlBatch;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.helpers.MapResultAsBean;

import java.util.List;

public interface AgencyDAO {
    @SqlQuery("SELECT * FROM agency WHERE id = :id")
    @MapResultAsBean
    Agency findAgencyById(@Bind("id") int id);

    @SqlBatch("REPLACE INTO agency (id, name, abbreviation, url, logo) VALUES (:id, :name, :abbreviation, :url, :logo)")
    void replaceAll(@BindBean List<PandasAgency> listAgencies);
}

package bamboo.crawl;

import bamboo.pandas.PandasAgency;
import org.skife.jdbi.v2.sqlobject.Bind;
import org.skife.jdbi.v2.sqlobject.BindBean;
import org.skife.jdbi.v2.sqlobject.SqlBatch;
import org.skife.jdbi.v2.sqlobject.SqlQuery;
import org.skife.jdbi.v2.sqlobject.helpers.MapResultAsBean;

import java.util.List;

public interface AgencyDAO {
    @SqlQuery("SELECT * FROM agency WHERE id = :id")
    @MapResultAsBean
    Agency findAgencyById(@Bind("id") int id);

    @SqlBatch("INSERT INTO agency (id, name, abbreviation, url, logo) " +
            "VALUES (:id, :name, :abbreviation, :url, :logo) " +
            "ON DUPLICATE KEY UPDATE name = :name, abbreviation = :abbreviation, url = :url, logo = :logo")
    void replaceAll(@BindBean List<PandasAgency> listAgencies);
}

Use 'on duplicate key update' rather than 'replace into'

'relace into' fires triggers and constraints. :(


package org.mozartoz.truffle.nodes.call;

import org.mozartoz.truffle.nodes.OzNode;
import org.mozartoz.truffle.runtime.TailCallException;

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

public class TailCallCatcherNode extends OzNode {

	@Child CallNode callNode;

	private final BranchProfile tailCallProfile = BranchProfile.create();

	public TailCallCatcherNode(CallNode callNode) {
		this.callNode = callNode;
	}

	public Object execute(VirtualFrame frame) {
		try {
			return callNode.execute(frame);
		} catch (TailCallException firstException) {
			tailCallProfile.enter();
			TailCallException tailCall = firstException;
			while (true) {
				try {
					return callNode.executeCall(frame, tailCall.receiver, tailCall.arguments);
				} catch (TailCallException exception) {
					tailCall = exception;
				}
			}
		}
	}

}

package org.mozartoz.truffle.nodes.call;

import org.mozartoz.truffle.nodes.OzNode;
import org.mozartoz.truffle.runtime.TailCallException;

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

public class TailCallCatcherNode extends OzNode {

	@Child CallNode callNode;

	private final BranchProfile tailCallProfile = BranchProfile.create();

	public TailCallCatcherNode(CallNode callNode) {
		this.callNode = callNode;
	}

	public Object execute(VirtualFrame frame) {
		try {
			return callNode.execute(frame);
		} catch (TailCallException tailCall) {
			tailCallProfile.enter();
			while (true) {
				try {
					return callNode.executeCall(frame, tailCall.receiver, tailCall.arguments);
				} catch (TailCallException exception) {
					tailCall = exception;
				}
			}
		}
	}

}

Make sure there is no leak in tail calls

* The JVM usually just null out firstException since it's not used later,
  but better be clear.


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

public enum ApplicationState
{
    STATUS,
    LOAD,
    SCHEMA,
    DC,
    RACK,
    RELEASE_VERSION,
    REMOVAL_COORDINATOR,
    INTERNAL_IP,
    RPC_ADDRESS,
    SEVERITY,
    NET_VERSION,
    // pad to allow adding new states to existing cluster
    X1,
    X2,
    X3,
    X4,
    X5,
}

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

public enum ApplicationState
{
    STATUS,
    LOAD,
    SCHEMA,
    DC,
    RACK,
    RELEASE_VERSION,
    REMOVAL_COORDINATOR,
    X_11_PADDING, // padding specifically for 1.1
    INTERNAL_IP,
    RPC_ADDRESS,
    SEVERITY,
    NET_VERSION,
    // pad to allow adding new states to existing cluster
    X1,
    X2,
    X3,
    X4,
    X5,
}

Add gossip padding for 1.1 This puts us at 5 new states for trunk, and thus no more can be added or we exceed the previous padding.


package squeek.applecore;

import java.util.Locale;

public final class ModInfo
{
	public static final String MODID = "AppleCore";
	public static final String MODNAME = "Apple Core";
	public static final String MODAPI = "AppleCoreAPI";
	public static final String VERSION = "${version}";
	public static final String APIVERSION = "${apiversion}";
	public static final String MODID_LOWER = ModInfo.MODID.toLowerCase(Locale.ROOT);
}

package squeek.applecore;

import java.util.Locale;

public final class ModInfo
{
	public static final String MODID = "AppleCore";
	public static final String MODNAME = "AppleCore";
	public static final String MODAPI = "AppleCoreAPI";
	public static final String VERSION = "${version}";
	public static final String APIVERSION = "${apiversion}";
	public static final String MODID_LOWER = ModInfo.MODID.toLowerCase(Locale.ROOT);
}

Change MODNAME to match the .info file

Change MODNAME to match the .info file


import java.util.ArrayList;

import org.junit.*;
import static org.junit.Assert.*;

public class WordTest {

  @Test
  public void WordObjectConstructor_instantiatesCorrectly_true() {
    Word testWord = new Word ("Word");
    assertEquals(true, testWord instanceof Word);
  }

}

import java.util.ArrayList;

import org.junit.*;
import static org.junit.Assert.*;

public class WordTest {

  @Test
  public void WordObjectConstructor_instantiatesCorrectly_true() {
    Word testWord = new Word ("Word");
    assertEquals(true, testWord instanceof Word);
  }

  @Test
  public void getWord_returnsWord_true() {
    Word testWord = new Word ("Word");
    assertEquals("Word", testWord.getWord());
  }

}

Test passes for the getWord() method

Test passes for the getWord() method


package jp.setchi.HitAndBlow;

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

public class StringUtility {

	private StringUtility() {}

	public static Boolean isDistinctChars(String str) {
		if (str == null) {
			throw new IllegalArgumentException("nullłB");
		}

		final Set<Character> existedCharacters = new HashSet<>();

		for (char c : str.toCharArray()) {
			if (existedCharacters.contains(c)) {
				return false;
			}
			existedCharacters.add(c);
		}

		return true;
	}

	public static String generateDistinctRandomNumeric(int digits) {
		final List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

		if (digits < 0 || numbers.size() < digits) {
			throw new IllegalArgumentException(
					"0~" + numbers.size() + "͈̔͂Ŏw肵Ă: " + digits);
		}

		Collections.shuffle(numbers);

		StringBuilder stringBuilder = new StringBuilder();
		for (int number : numbers.subList(0, digits)) {
			stringBuilder.append(number);
		}

		return stringBuilder.toString();
	}
}

package jp.setchi.HitAndBlow;

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

public class StringUtility {

	private StringUtility() {}

	public static Boolean isDistinctChars(String str) {
		if (str == null) {
			throw new IllegalArgumentException("nullłB");
		}

		final Set<Character> existedCharacters = new HashSet<>();

		for (char c : str.toCharArray()) {
			if (existedCharacters.contains(c)) {
				return false;
			}
			existedCharacters.add(c);
		}

		return true;
	}

	public static String generateDistinctRandomNumeric(int digits) {
		final List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);

		if (digits < 0 || numbers.size() < digits) {
			throw new IllegalArgumentException(
					"0~" + numbers.size() + "͈̔͂Ŏw肵Ă: " + digits);
		}

		Collections.shuffle(numbers);

		final StringBuilder stringBuilder = new StringBuilder();
		for (int number : numbers.subList(0, digits)) {
			stringBuilder.append(number);
		}

		return stringBuilder.toString();
	}
}

Add final modifiers to immutable variables


package sg.ncl.service;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

/**
 * @author Christopher Zhong
 */
@Configuration("sg.ncl.service.AppConfig")
@Import({sg.ncl.service.user.AppConfig.class, sg.ncl.service.team.AppConfig.class, sg.ncl.service.version.AppConfig.class})
public class AppConfig {
}

package sg.ncl.service;

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import sg.ncl.service.experiment.*;

/**
 * @author Christopher Zhong
 */
@Configuration("sg.ncl.service.AppConfig")
@Import({sg.ncl.service.authentication.AppConfig.class,
        sg.ncl.service.experiment.AppConfig.class,
        sg.ncl.service.realization.AppConfig.class,
        sg.ncl.service.user.AppConfig.class,
        sg.ncl.service.team.AppConfig.class,
        sg.ncl.service.version.AppConfig.class})
public class AppConfig {
}

Add missing services to root project (DEV-100)


package com.obidea.semantika.mapping.parser.r2rml;

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

import com.obidea.semantika.util.StringUtils;

public class R2RmlTemplate
{
   private static final Pattern columnInCurlyBraces = Pattern.compile("\\{([^\\}]+)\\}");

   private int mIndex = 1;

   private String mTemplateString;
   private List<String> mColumnNames = new ArrayList<String>();

   public R2RmlTemplate(String templateString)
   {
      process(templateString);
   }

   public String getTemplateString()
   {
      return mTemplateString;
   }

   public List<String> getColumnNames()
   {
      return mColumnNames;
   }

   private void process(String templateString)
   {
      Matcher m = columnInCurlyBraces.matcher(templateString);
      while (m.find()) {
         String arg = m.group(2);
         if (!StringUtils.isEmpty(arg)) {
            mTemplateString.replace(arg, mIndex+"");
            mColumnNames.add(arg);
            mIndex++;
         }
      }
   }
}

package com.obidea.semantika.mapping.parser.r2rml;

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

import com.obidea.semantika.util.StringUtils;

public class R2RmlTemplate
{
   private static final Pattern columnInCurlyBraces = Pattern.compile("\\{([^\\}]+)\\}");

   private int mIndex = 1;

   private String mTemplateString;
   private List<String> mColumnNames = new ArrayList<String>();

   public R2RmlTemplate(String templateString)
   {
      mTemplateString = templateString;
      process(templateString);
   }

   public String getTemplateString()
   {
      return mTemplateString;
   }

   public List<String> getColumnNames()
   {
      return mColumnNames;
   }

   private void process(String templateString)
   {
      Matcher m = columnInCurlyBraces.matcher(templateString);
      while (m.find()) {
         String arg = m.group(2);
         if (!StringUtils.isEmpty(arg)) {
            mTemplateString.replace(arg, mIndex+"");
            mColumnNames.add(arg);
            mIndex++;
         }
      }
   }
}

Fix null pointer exception because of the missing value assignment.


package eic.beike.projectx.handlers;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import eic.beike.projectx.activities.GameActivity;

/**
 * @author Adam
 */
public class GameHandler extends Handler {

    GameActivity game;

    public GameHandler(Looper looper, GameActivity activity) {
        super(looper);
        game = activity;
    }

    @Override
    public void handleMessage(Message msg) {
        Log.d("Score", Thread.currentThread().getName() + ":handleMessage");

        Bundle data = msg.getData();
        int totalScore = data.getInt("score");
        int latestScore = data.getInt("latest_score");

        game.showScore(latestScore, totalScore);
    }

}

package eic.beike.projectx.handlers;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import eic.beike.projectx.activities.GameActivity;
import eic.beike.projectx.util.Constants;

/**
 * @author Adam
 * @author Alex
 */
public class GameHandler extends Handler {

    GameActivity game;

    public GameHandler(Looper looper, GameActivity activity) {
        super(looper);
        game = activity;
    }

    @Override
    public void handleMessage(Message msg) {
        Log.d("Score", Thread.currentThread().getName() + ":handleMessage");

        Bundle data = msg.getData();

        //See what operation to perform.
        String operation = data.getString("operation");
        switch (operation) {
            case Constants.UPDATESCORE:
                updateScore(data);
                break;
            case Constants.SELECTBUTTON:
                selectButton(data);
                break;
            case Constants.DESELECTBUTTON:
                deselectButton(data);
                break;
            case Constants.UPDATEBOARD:
                updateBoard(data);
                break;
            default:
                if(operation != null) {
                    Log.d(getClass().getSimpleName(), "Tried to perform unknown operation!");
                    break;
                } else {
                    Log.d(getClass().getSimpleName(), "Malformed operation message!");
                    break;
                }
        }
    }

    private void updateScore(Bundle data){
        //TODO: Add sanity checks!
        int totalScore = data.getInt("score");
        int latestScore = data.getInt("latest_score");
        int bonusScore = data.getInt("bonus_score");
        game.updateScore(latestScore, bonusScore, totalScore);
    }

    private void selectButton(Bundle data){
        //TODO: Implement this stub!
    }

    private void deselectButton(Bundle data){
        //TODO: Implement this stub!
    }

    private void updateBoard(Bundle data){
        //TODO: Implement this stub!
    }
}

Update handler to allow new operations.

Update handler to allow new operations.


package net.engin33r.luaspigot.lua.lib;

import net.engin33r.luaspigot.lua.Function;
import net.engin33r.luaspigot.lua.Library;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.LuaValue;

/**
 * Library for interacting with the chat.
 */
@SuppressWarnings("unused")
public class ChatLibrary extends Library {
    public ChatLibrary() {
        registerFunction(new BroadcastFunction());
    }

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

    private class BroadcastFunction extends Function {
        @Override
        public String getName() {
            return "broadcast";
        }

        @Override
        public Varargs call(Varargs args) {
            int n = args.narg();
            if (n == 0) return LuaValue.NIL;

            String str = "";
            for (int i = 1; i <= args.narg(); i++) {
                if (i > 1) str += "\t";
                str += args.checkjstring(i);
            }

            for (Player p : Bukkit.getOnlinePlayers()) {
                p.sendMessage(str);
            }
            return LuaValue.NIL;
        }
    }

}

package net.engin33r.luaspigot.lua.lib;

import net.engin33r.luaspigot.lua.Library;
import net.engin33r.luaspigot.lua.annotation.LibFunctionDef;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.luaj.vm2.Varargs;
import org.luaj.vm2.LuaValue;

/**
 * Library for interacting with the chat.
 */
@SuppressWarnings("unused")
public class ChatLibrary extends Library {
    @Override
    public String getName() {
        return "chat";
    }

    @LibFunctionDef(name = "broadcast")
    public Varargs broadcast(Varargs args) {
        int n = args.narg();
        if (n == 0) return LuaValue.NIL;

        String str = "";
        for (int i = 1; i <= args.narg(); i++) {
            if (i > 1) str += "\t";
            str += args.checkjstring(i);
        }

        for (Player p : Bukkit.getOnlinePlayers()) {
            p.sendMessage(str);
        }
        return LuaValue.NIL;
    }
}

Use new annotation for chat library

Use new annotation for chat library


import webserver.WebServer;

public class Client {

    public static void main(String[] args) {
        WebServer ws = new WebServer();
    }
}

import org.slf4j.MDC;
import webserver.WebServer;

public class Client {

    public static void main(String[] args) {
        MDC.put("pid", getPid());
        WebServer ws = new WebServer();
        MDC.clear();
    }

    private static String getPid() {
        String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
        return processName.split("@")[0];
    }
}

Use process id in log file names to distinguish between different instances of the same component.


package sk.httpclient.app;

import com.netflix.loadbalancer.DynamicServerListLoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

public class MyLoadBalancer extends DynamicServerListLoadBalancer {

    private int c = 0;

    @Override

    public void addServers(List<Server> newServers) {
        super.addServers(newServers);
    }

    @Override
    public Server chooseServer(Object key) {
        //c = ++c % upServerList.size();
        //return upServerList.get(c);
        return super.chooseServer(key);
    }

    @Override
    public void markServerDown(Server server) {
    }

    @Override
    public List<Server> getServerList(boolean availableOnly) {
        return null;
    }

    @Override
    public List<Server> getReachableServers() {
        return null;
    }

    @Override
    public List<Server> getAllServers() {
        return null;
    }
}

package sk.httpclient.app;

import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

public class MyLoadBalancer implements ILoadBalancer {
    private int c = 0;

    @Override

    public void addServers(List<Server> newServers) {
        //super.addServers(newServers);
    }

    private final Server[] a = new Server[]{
        new Server("localhost", 8887),
        new Server("localhost", 8888),
        new Server("localhost", 8889)
    };

    @Override
    public Server chooseServer(Object key) {
        c = ++c % 3;
        return a[c];
    }

    @Override
    public void markServerDown(Server server) {
    }

    @Override
    public List<Server> getServerList(boolean availableOnly) {
        return null;
    }

    @Override
    public List<Server> getReachableServers() {
        return null;
    }

    @Override
    public List<Server> getAllServers() {
        return null;
    }
}

Make load balancer as fast as possible. No config is used, servers are defined in code.


package com.boundary.camel.component.common;

/**
 *
 * @author davidg
 *
 */
public class ServiceInfo {

	private ServiceStatus status;
	private String message;
	private String host;
	private int port;

	public ServiceInfo() {
		status = ServiceStatus.SUCCESS;
	}

	public void setStatus(ServiceStatus status) {
		this.status = status;
	}

	public ServiceStatus getStatus() {
		return this.status;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getMessage() {
		return this.message;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getHost() {
		return this.host;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getPort() {
		return this.port;
	}

}

package com.boundary.camel.component.common;

/**
 *
 * @author davidg
 *
 */
public class ServiceInfo {

	private ServiceStatus status = ServiceStatus.SUCCESS;
	private String message = "OK";
	private String host = "localhost";
	private int port = 7;
	private int timeOut = 5000;

	public ServiceInfo() {
	}

	public void setStatus(ServiceStatus status) {
		this.status = status;
	}

	public ServiceStatus getStatus() {
		return this.status;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getMessage() {
		return this.message;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getHost() {
		return this.host;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getPort() {
		return this.port;
	}

	public void setTimeout(int timeOut) {
		this.timeOut = timeOut;
	}

	public int getTimeout() {
		return this.timeOut;
	}

}

Add infor to base service class

Add infor to base service class


package com.crowdin.cli.commands.parts;

import com.crowdin.cli.utils.MessageSource;
import com.crowdin.cli.utils.Utils;
import picocli.CommandLine;

import java.util.ResourceBundle;

@CommandLine.Command(
        name = "crowdin",
        versionProvider = Command.VersionProvider.class,
        mixinStandardHelpOptions = true,
        synopsisHeading = "%n@|underline SYNOPSIS|@:%n",
        descriptionHeading = "%n@|underline DESCRIPTION|@:%n",
        parameterListHeading = "%n@|underline PARAMETERS|@:%n",
        optionListHeading = "%n@|underline OPTIONS|@:%n",
        commandListHeading = "%n@|underline COMMANDS|@:%n",
        usageHelpAutoWidth = true
)
public abstract class Command implements Runnable {

    @CommandLine.Option(names = {"--no-progress"}, description = "Disable progress on executing command")
    protected boolean noProgress;

    @CommandLine.Option(names = {"-v", "--verbose"}, description = "Provide more information on the command processing")
    protected boolean isVerbose;

    @CommandLine.Option(names = {"--debug"}, hidden = true)
    protected boolean debug;

    protected static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;

    @Override
    public void run() {
    }

    public static class VersionProvider implements CommandLine.IVersionProvider {
        @Override
        public String[] getVersion() throws Exception {
            return new String[] {Utils.getAppVersion()};
        }
    }
}

package com.crowdin.cli.commands.parts;

import com.crowdin.cli.utils.MessageSource;
import com.crowdin.cli.utils.Utils;
import picocli.CommandLine;

import java.util.ResourceBundle;

@CommandLine.Command(
        name = "crowdin",
        versionProvider = Command.VersionProvider.class,
        synopsisHeading = "%n@|underline SYNOPSIS|@:%n",
        descriptionHeading = "%n@|underline DESCRIPTION|@:%n",
        parameterListHeading = "%n@|underline PARAMETERS|@:%n",
        optionListHeading = "%n@|underline OPTIONS|@:%n",
        commandListHeading = "%n@|underline COMMANDS|@:%n",
        usageHelpAutoWidth = true
)
public abstract class Command implements Runnable {

    @CommandLine.Option(names = {"-V", "--version"}, versionHelp = true, description = "Print version information and exit")
    boolean versionInfoRequested;

    @CommandLine.Option(names = {"-h", "--help"}, usageHelp = true, description = "Show this help message and exit")
    boolean usageHelpRequested;

    @CommandLine.Option(names = {"--no-progress"}, description = "Disable progress on executing command")
    protected boolean noProgress;

    @CommandLine.Option(names = {"-v", "--verbose"}, description = "Provide more information on the command processing")
    protected boolean isVerbose;

    @CommandLine.Option(names = {"--debug"}, hidden = true)
    protected boolean debug;

    protected static final ResourceBundle RESOURCE_BUNDLE = MessageSource.RESOURCE_BUNDLE;

    @Override
    public void run() {
    }

    public static class VersionProvider implements CommandLine.IVersionProvider {
        @Override
        public String[] getVersion() throws Exception {
            return new String[] {Utils.getAppVersion()};
        }
    }
}

Change description for help and version

Change description for help and version


package info.u_team.u_team_core.util;

import static net.minecraft.client.renderer.model.ModelBakery.STATE_CONTAINER_OVERRIDES;

import java.util.*;

import com.google.common.collect.*;

import net.minecraft.block.*;
import net.minecraft.state.StateContainer;
import net.minecraft.util.ResourceLocation;

public class ModelUtil {

	static {
		if (STATE_CONTAINER_OVERRIDES instanceof ImmutableMap) {
			final Map<ResourceLocation, StateContainer<Block, BlockState>> mutableMap = new HashMap<>();
			STATE_CONTAINER_OVERRIDES.forEach(mutableMap::put);
			STATE_CONTAINER_OVERRIDES = mutableMap;
		}
	}

	public static void addCustomStateContainer(ResourceLocation location, StateContainer<Block, BlockState> container) {
		STATE_CONTAINER_OVERRIDES.put(location, container);
	}

	public static class EmptyStateContainer extends StateContainer<Block, BlockState> {

		public EmptyStateContainer(Block block) {
			super(Block::getDefaultState, block, BlockState::new, new HashMap<>());
		}

		@Override
		public ImmutableList<BlockState> getValidStates() {
			return getOwner().getStateContainer().getValidStates();
		}

	}

}

package info.u_team.u_team_core.util;

import static net.minecraft.client.renderer.model.ModelBakery.*;

import java.util.*;

import com.google.common.collect.*;

import net.minecraft.block.*;
import net.minecraft.client.renderer.model.RenderMaterial;
import net.minecraft.state.StateContainer;
import net.minecraft.util.ResourceLocation;

public class ModelUtil {

	static {
		if (STATE_CONTAINER_OVERRIDES instanceof ImmutableMap) {
			final Map<ResourceLocation, StateContainer<Block, BlockState>> mutableMap = new HashMap<>();
			STATE_CONTAINER_OVERRIDES.forEach(mutableMap::put);
			STATE_CONTAINER_OVERRIDES = mutableMap;
		}
	}

	public static void addCustomStateContainer(ResourceLocation location, StateContainer<Block, BlockState> container) {
		STATE_CONTAINER_OVERRIDES.put(location, container);
	}

	public static void addTexture(RenderMaterial material) {
		LOCATIONS_BUILTIN_TEXTURES.add(material);
	}

	public static class EmptyStateContainer extends StateContainer<Block, BlockState> {

		public EmptyStateContainer(Block block) {
			super(Block::getDefaultState, block, BlockState::new, new HashMap<>());
		}

		@Override
		public ImmutableList<BlockState> getValidStates() {
			return getOwner().getStateContainer().getValidStates();
		}

	}

}

Add method to add custom texture

Add method to add custom texture


package net.aeten.core.spi;

/**
 *
 * @author Thomas Pérennou
 */
public @interface Configurations {
	Configuration[] value();
}

package net.aeten.core.spi;

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

/**
 *
 * @author Thomas Pérennou
 */
@Documented
@Retention(RetentionPolicy.SOURCE)
@Target({ElementType.PACKAGE, ElementType.TYPE})
public @interface Configurations {
	Configuration[] value();
}

Add Documented, Retention and Target annotations


package protocolsupport.server.listeners;

import java.util.HashSet;
import java.util.Set;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;

public class CommandListener implements Listener {
	private final Set<String> blacklist = new HashSet<>();

	public CommandListener() {
		blacklist.add("/reload");
		blacklist.add("/reload confirm");
		blacklist.add("/bukkit:reload");
		blacklist.add("/bukkit:reload confirm");
	}

	@EventHandler
	public void onCommand(PlayerCommandPreprocessEvent event) {
		if (event.getPlayer().hasPermission("bukkit.command.reload") && blacklist.contains(event.getMessage().toLowerCase())) {
			event.setCancelled(true);
			event.getPlayer().sendMessage("The reload command has been disabled by ProtocolSupport");
		}
	}
}

package protocolsupport.server.listeners;

import java.util.HashSet;
import java.util.Set;

import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerCommandPreprocessEvent;

public class CommandListener implements Listener {
	private final Set<String> blacklist = new HashSet<>();

	public CommandListener() {
		blacklist.add("/reload");
		blacklist.add("/reload confirm");
		blacklist.add("/rl");
		blacklist.add("/rl confirm");
		blacklist.add("/bukkit:reload");
		blacklist.add("/bukkit:reload confirm");
		blacklist.add("/bukkit:rl");
		blacklist.add("/bukkit:rl confirm");
	}

	@EventHandler
	public void onCommand(PlayerCommandPreprocessEvent event) {
		if (event.getPlayer().hasPermission("bukkit.command.reload") && blacklist.contains(event.getMessage().toLowerCase())) {
			event.setCancelled(true);
			event.getPlayer().sendMessage("The reload command has been disabled by ProtocolSupport");
		}
	}
}

Add /rl to command blacklist

Add /rl to command blacklist


package session;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import domain.Customer;
import domain.Order;

public class XaJpaDemoBean {

	@PersistenceContext(name="customer") EntityManager customerEntityManager;
	@PersistenceContext(name="orders") EntityManager orderEntityManager;

	public void saveCustomerOrder(Customer c, Order o, Boolean succeeds) {
		try {
			EntityTransaction customerTransaction = customerEntityManager.getTransaction();
			customerTransaction.begin();

			// Update the customer entity in the database.
			customerEntityManager.merge(c);
			c.setNumberOfOrders(c.getNumberOfOrders() + 1);
			customerTransaction.commit();

			int cid = c.getId();
			System.out.println("Updated Customer with Id " + cid);

			EntityTransaction orderTransaction = orderEntityManager.getTransaction();
			orderTransaction.begin();

			// Insert the order entity in the database.
			orderEntityManager.persist(c);
			orderTransaction.commit();

			int oid = o.getId();
			System.out.println("Created order with Id " + oid);
			Query query = customerEntityManager.createQuery("select c from Customer c order by c.name");

			List<Customer> list = query.getResultList();
			System.out.println("There are " + list.size() + " persons:");
			for (Customer p : list) {
				System.out.println(p.getName());
			}
			System.out.println();

		} finally {
			if (!succeeds) {
				throw new RuntimeException("Simulated failure!");
			}
		}
	}
}

package session;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;

import domain.Customer;
import domain.Order;

@Stateless
public class XaJpaDemoBean {

	@PersistenceContext(name="customer") EntityManager customerEntityManager;
	@PersistenceContext(name="orders") EntityManager orderEntityManager;

	public void saveCustomerOrder(Customer c, Order o, Boolean succeeds) {
		try {
			EntityTransaction customerTransaction = customerEntityManager.getTransaction();
			customerTransaction.begin();

			// Update the customer entity in the database.
			customerEntityManager.merge(c);
			c.setNumberOfOrders(c.getNumberOfOrders() + 1);
			customerTransaction.commit();

			int cid = c.getId();
			System.out.println("XaJpaDemoBean.saveCustomerOrder(): Updated Customer with Id " + cid);

			EntityTransaction orderTransaction = orderEntityManager.getTransaction();
			orderTransaction.begin();

			// Insert the order entity in the database.
			orderEntityManager.persist(c);
			orderTransaction.commit();

			int oid = o.getId();
			System.out.println("XaJpaDemoBean.saveCustomerOrder(): Created order with Id " + oid);

		} finally {
			if (!succeeds) {
				throw new RuntimeException("XaJpaDemoBean.saveCustomerOrder(): Simulated failure!");
			}
		}
	}
}

Annotate correctly (@Stateless). Correct several printouts.


package surc.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

/**
 * Servlet implementation class NewComment
 */
@WebServlet("/newComment")
public class NewComment extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public NewComment() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json; charset=UTF-8");

		PrintWriter out = response.getWriter();
		JSONObject obj = new JSONObject();
		obj.put("status", "ok");
		out.println(obj);
	}
}

package surc.test;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class NewComment
 */
@WebServlet("/newComment")
public class NewComment extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public NewComment() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("application/json; charset=UTF-8");

		// To submit the comment, you need to load the comment content by a
		// parameter name "comment" first. Additionally, you need to add all the
		// files into database as well, which still remain in session.

		PrintWriter out = response.getWriter();
		out.println("{\"status\":\"ok\"}");
	}
}

Update Example - Submit New Comment

Update Example - Submit New Comment


package uk.ac.ox.oucs.vle;

public class CourseCategoryDAO implements java.io.Serializable {

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

	private String categoryId;
	private String groupId;
	private String categoryCode;
    private String categoryName;
    private String categoryType;

    public CourseCategoryDAO() {
    }

    public String getCategoryId() {
        return this.categoryId;
    }

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
       }

    public String getGroupId() {
        return this.groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getCategoryCode() {
        return this.categoryCode;
    }

    public void setCategoryCode(String code) {
        this.categoryCode = code;
    }

    public String getCategoryName() {
        return this.categoryName;
    }

    public void setCategoryName(String name) {
        this.categoryName = name;
    }

    public String getCategoryType() {
        return this.categoryType;
    }

    public void setCategoryType(String type) {
        this.categoryType = type;
    }
}

package uk.ac.ox.oucs.vle;

public class CourseCategoryDAO implements java.io.Serializable {

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

	private String categoryId;
	private String groupId;
	private String categoryCode;
    private String categoryName;
    private String categoryType;

    public CourseCategoryDAO() {
    }

    public CourseCategoryDAO(String groupId, CourseGroup.Category_Type type, String code, String name) {
    	this.groupId = groupId;
    	this.categoryType = type.name();
    	this.categoryCode = code;
    	this.categoryName = name;
    }

    public String getCategoryId() {
        return this.categoryId;
    }

    public void setCategoryId(String categoryId) {
        this.categoryId = categoryId;
       }

    public String getGroupId() {
        return this.groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getCategoryCode() {
        return this.categoryCode;
    }

    public void setCategoryCode(String code) {
        this.categoryCode = code;
    }

    public String getCategoryName() {
        return this.categoryName;
    }

    public void setCategoryName(String name) {
        this.categoryName = name;
    }

    public String getCategoryType() {
        return this.categoryType;
    }

    public void setCategoryType(String type) {
        this.categoryType = type;
    }
}

Add new constructor to courseCategories

Add new constructor to courseCategories


package com.github.sbugat;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.junit.Test;

public class GenericUninstantiableClassTest {

	@Test(expected = InvocationTargetException.class)
	public void testUninstantiableClassConstructor() throws Exception {
		// System.out.println(this.getClass().getName().replace("Test$", "").replace("IT$", ""));

		final String targetClassName = getClass().getName().replaceFirst("Test$", "").replaceFirst("IT$", "");
		@SuppressWarnings("rawtypes")
		final Class targetClass = Class.forName(targetClassName);

		System.out.println(targetClass.getName());
		@SuppressWarnings({ "unchecked", "rawtypes" })
		final Constructor uninstantiableClassConstructor = targetClass.getDeclaredConstructor();
		uninstantiableClassConstructor.setAccessible(true);
		uninstantiableClassConstructor.newInstance();
	}
}

package com.github.sbugat;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.junit.Test;

public abstract class GenericUninstantiableClassTest {

	@Test(expected = InvocationTargetException.class)
	public void testUninstantiableClassConstructor() throws Exception {
		// System.out.println(this.getClass().getName().replace("Test$", "").replace("IT$", ""));

		final String targetClassName = getClass().getName().replaceFirst("Test$", "").replaceFirst("IT$", "");
		@SuppressWarnings("rawtypes")
		final Class targetClass = Class.forName(targetClassName);

		System.out.println(targetClass.getName());
		@SuppressWarnings({ "unchecked", "rawtypes" })
		final Constructor uninstantiableClassConstructor = targetClass.getDeclaredConstructor();
		uninstantiableClassConstructor.setAccessible(true);
		uninstantiableClassConstructor.newInstance();
	}
}

Fix build failure, change generic test to abstract


package leetcode;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * https://leetcode.com/problems/contains-duplicate-ii/
 */
public class Problem219 {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        // the key is the num value, the value is the index
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (map.containsKey(num)) {
                int idx = map.get(num);
                if (Math.abs(i - idx) <= k) {
                    return true;
                }
            }
            map.put(num, i);
        }
        return false;
    }

    public static void main(String[] args) {
        Problem219 prob = new Problem219();
        System.out.println(prob.containsNearbyDuplicate(new int[]{99, 99}, 2));
    }
}

package leetcode;

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

/**
 * https://leetcode.com/problems/contains-duplicate-ii/
 */
public class Problem219 {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        // the key is the num value, the value is the index
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int num = nums[i];
            if (map.containsKey(num)) {
                int idx = map.get(num);
                if (Math.abs(i - idx) <= k) {
                    return true;
                }
            }
            map.put(num, i);
        }
        return false;
    }

    public static void main(String[] args) {
        Problem219 prob = new Problem219();
        System.out.println(prob.containsNearbyDuplicate(new int[]{99, 99}, 2));
    }
}

Remove unused import in Problem 219

Remove unused import in Problem 219


package com.easternedgerobotics.rov.fx;

import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.BorderPane;

import javax.inject.Inject;

public class MainView implements View {
    static final int SPACING = 10;

    final BorderPane box = new BorderPane();

    final ToggleButton button = new ToggleButton("Start");

    @Inject
    public MainView() {
        button.setMaxWidth(Double.MAX_VALUE);
        button.setMaxHeight(Double.MAX_VALUE);
        box.setPadding(new Insets(SPACING));
        box.setCenter(button);
    }

    @Override
    public final Parent getParent() {
        return box;
    }
}

package com.easternedgerobotics.rov.fx;

import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.BorderPane;

import javax.inject.Inject;

public class MainView implements View {
    static final int SPACING = 10;

    static final int TOGGLE_BOX_W = 256;

    static final int TOGGLE_BOX_H = 64;

    final BorderPane box = new BorderPane();

    final ToggleButton button = new ToggleButton("Start");

    @Inject
    public MainView() {
        button.setMaxWidth(Double.MAX_VALUE);
        button.setMaxHeight(Double.MAX_VALUE);
        button.setPrefSize(TOGGLE_BOX_W, TOGGLE_BOX_H);
        box.setPadding(new Insets(SPACING));
        box.setCenter(button);
    }

    @Override
    public final Parent getParent() {
        return box;
    }
}

Set initial size for main toggle box

Set initial size for main toggle box


/**
 * Copyright 2019 The CloudEvents 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 io.cloudevents.fun;

import java.util.Map;

/**
 *
 * @author fabiojose
 *
 */
@FunctionalInterface
public interface BinaryFormatExtensionMapper {

	/**
	 * Maps the 'headers' of binary format into extensions
	 * @param headers
	 */
	Map<String, String> map(Map<String, Object> headers);

}

/**
 * Copyright 2019 The CloudEvents 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 io.cloudevents.fun;

import java.util.Map;

/**
 *
 * @author fabiojose
 *
 */
@FunctionalInterface
public interface FormatExtensionMapper {

	/**
	 * Maps the 'headers' of binary format into extensions
	 * @param headers
	 */
	Map<String, String> map(Map<String, Object> headers);

}

Change to more generic definition of mapper

Signed-off-by: Fabio José <34f3a7e4e4d9fe971c99ebc4af947a5309eca653@gmail.com>


package org.techern.dbsg;

import java.util.logging.Logger;

/**
 * DyedBlockStateGenerator; A block state generator for dyed blocks
 *
 * @since 0.0.1
 */
public class DyedBlockStateGenerator {

    /**
     * The {@link Logger} used by {@link DyedBlockStateGenerator}
     *
     * @since 0.0.1
     */
    public static Logger LOGGER = Logger.getLogger("Generator");

    /**
     * Runs {@link DyedBlockStateGenerator}
     *
     * @param arguments The list of arguments
     * @since 0.0.1
     */
    public static void main(String... arguments) {
        LOGGER.info("Starting the dyed block state generator...");
    }

}

package org.techern.dbsg;

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;

import java.nio.file.Path;
import java.util.logging.Logger;

/**
 * DyedBlockStateGenerator; A block state generator for dyed blocks
 *
 * @since 0.0.1
 */
public class DyedBlockStateGenerator {

    /**
     * The {@link Logger} used by {@link DyedBlockStateGenerator}
     *
     * @since 0.0.1
     */
    public static Logger LOGGER = Logger.getLogger("Generator");

    /**
     * Runs {@link DyedBlockStateGenerator}
     *
     * @param arguments The list of arguments
     * @since 0.0.1
     */
    public static void main(String... arguments) throws IOException {
        LOGGER.info("Starting the dyed block state generator...");

        Path rootPath = FileSystems.getDefault().getPath(".");

        Path templatePath = rootPath.resolve("templates");

        Path outputPath = rootPath.resolve("generated");

        LOGGER.info("Template path is " + templatePath.toString() + ", output path is " + outputPath.toString());

        if (Files.notExists(templatePath)) {
            Files.createDirectory(templatePath);
            LOGGER.warning("Template folder does not exist; Creating");
        }
        if (Files.notExists(outputPath)) {
            Files.createDirectory(outputPath);
            LOGGER.warning("Output folder does not exist; Creating");
        }

    }

}

Check for and create directories

Check for and create directories


package me.ryleykimmel.brandywine.common;

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

public final class StringsTest {

  @Test
  public void testToFirstUpper() {
    String input = "hEllo WORLd";
    String expected = "Hello world";

    Assert.assertEquals(expected, Strings.toFirstUpper(input));
  }

  @Test
  public void testToFirstUpperInternational() {
    String input = "ππππππππ";
    String expected = "π";

    Assert.assertEquals(expected, Strings.toFirstUpper(input));
  }

  @Test(expected = IllegalArgumentException.class)
  public void failToFirstUpperZeroLength() {
    Strings.toFirstUpper("");
  }

  @Test(expected = IllegalArgumentException.class)
  public void failToFirstUpperNull() {
    Strings.toFirstUpper(null);
  }

}

package me.ryleykimmel.brandywine.common;

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

public final class StringsTest {

  @Test
  public void testToFirstUpper() {
    String input = "hEllo WORLd";
    String expected = "Hello world";

    Assert.assertEquals(expected, Strings.toFirstUpper(input));
  }

  @Test(expected = IllegalArgumentException.class)
  public void failToFirstUpperZeroLength() {
    Strings.toFirstUpper("");
  }

  @Test(expected = IllegalArgumentException.class)
  public void failToFirstUpperNull() {
    Strings.toFirstUpper(null);
  }

}

Remove international strings test to fix failing build


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

import com.upokecenter.cbor.CBORObject;

/**
 *
 * @author jimsch
 */
public enum HeaderKeys {
    Algorithm(1),
    CONTENT_TYPE(3),
    KID(2),
    IV(5),
    CriticalHeaders(2),
    CounterSignature(7),
    PARTIAL_IV(6),

    ECDH_EPK(-1),
    ECDH_SPK(-2),
    ECDH_SKID(-3),

    HKDF_Salt(-20),
    HKDF_Context_PartyU_ID(-21),
    HKDF_Context_PartyU_nonce(-22),
    HKDF_Context_PartyU_Other(-23),
    HKDF_Context_PartyV_ID(-24),
    HKDF_Context_PartyV_nonce(-25),
    HKDF_Context_PartyV_Other(-26),
    HKDF_SuppPub_Other(-999),
    HKDF_SuppPriv_Other(-998)
    ;

    private CBORObject value;

    HeaderKeys(int val) {
        this.value = CBORObject.FromObject(val);
    }

    public CBORObject AsCBOR() {
        return value;
    }
}

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

import com.upokecenter.cbor.CBORObject;

/**
 *
 * @author jimsch
 */
public enum HeaderKeys {
    Algorithm(1),
    CONTENT_TYPE(3),
    KID(4),
    IV(5),
    CriticalHeaders(2),
    CounterSignature(7),
    PARTIAL_IV(6),

    ECDH_EPK(-1),
    ECDH_SPK(-2),
    ECDH_SKID(-3),

    HKDF_Salt(-20),
    HKDF_Context_PartyU_ID(-21),
    HKDF_Context_PartyU_nonce(-22),
    HKDF_Context_PartyU_Other(-23),
    HKDF_Context_PartyV_ID(-24),
    HKDF_Context_PartyV_nonce(-25),
    HKDF_Context_PartyV_Other(-26),
    HKDF_SuppPub_Other(-999),
    HKDF_SuppPriv_Other(-998)
    ;

    private CBORObject value;

    HeaderKeys(int val) {
        this.value = CBORObject.FromObject(val);
    }

    public CBORObject AsCBOR() {
        return value;
    }
}

Correct value to match spec

Correct value to match spec


package org.yoooo.se1;

import java.util.Scanner;

public class Application {
    public void run(String[] args) {

    }

    public SimpleDirectedWeightGraph<String, Integer> getGraph() {
        return null;
    }

    private static Application sInstance = new Application();

    public static Application getInstance() {
        return sInstance;
    }

    private Application() {
    }

    /**
     * Parses string and generates graph from the string as specified in feature 1. The string
     * should only contain lowercase letters and spaces.
     *
     * @param string string from input file
     * @return graph created from string
     */
    private SimpleDirectedWeightGraph<String, Integer> stringToGraph(String string) {
        Scanner scanner = new Scanner(string);
        SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>(
                new EdgeFactory<String, Integer>() {
                    int next;

                    @Override
                    public Integer createEdge(String source, String target) {
                        return next++;
                    }
                });
        if (!scanner.hasNext()) {
            return graph;
        }
        String prev = scanner.next();
        graph.addVertex(prev);
        while (scanner.hasNext()) {
            String vertex = scanner.next();
            graph.addVertex(vertex);
            Integer edge = graph.getEdge(prev, vertex);
            if (edge != null) {
                graph.setEdgeWeight(edge, graph.getEdgeWeight(edge) + 1);
            } else {
                graph.addEdge(prev, vertex);
            }
        }
        return graph;
    }
}

package org.yoooo.se1;

import java.util.Scanner;

public class Application {
    public void run(String[] args) {

    }

    public SimpleDirectedWeightGraph<String, Integer> getGraph() {
        return null;
    }

    private static Application sInstance = new Application();

    public static Application getInstance() {
        return sInstance;
    }

    private Application() {
    }

    /**
     * Parses string and generates graph from the string as specified in feature 1. The string
     * should only contain lowercase letters and spaces.
     *
     * @param string string from input file
     * @return graph created from string
     */
    private SimpleDirectedWeightGraph<String, Integer> stringToGraph(String string) {
        Scanner scanner = new Scanner(string);
        SimpleDirectedWeightGraph<String, Integer> graph = new SimpleDirectedWeightGraph<>(
                new EdgeFactory<String, Integer>() {
                    private int mNext;

                    @Override
                    public Integer createEdge(String source, String target) {
                        return mNext++;
                    }
                });
        if (!scanner.hasNext()) {
            return graph;
        }
        String prev = scanner.next();
        graph.addVertex(prev);
        while (scanner.hasNext()) {
            String vertex = scanner.next();
            graph.addVertex(vertex);
            Integer edge = graph.getEdge(prev, vertex);
            if (edge != null) {
                graph.setEdgeWeight(edge, graph.getEdgeWeight(edge) + 1);
            } else {
                graph.addEdge(prev, vertex);
            }
        }
        return graph;
    }
}

Rename and add missing modifier

Rename and add missing modifier


/**
*	IMDBHandlerTest.java
*
*	@author Johan Brook
*	@copyright (c) 2012 Johan Brook
*	@license MIT
*/

package se.chalmers.watchmetest.net;

import org.json.JSONArray;
import org.json.JSONObject;

import se.chalmers.watchme.net.IMDBHandler;
import junit.framework.TestCase;

public class IMDBHandlerTest extends TestCase {

	IMDBHandler imdb;

	protected void setUp() throws Exception {
		super.setUp();

		this.imdb = new IMDBHandler();
	}

	public void testGetMovies() {
		JSONArray json = this.imdb.getMoviesByTitle("casino royale");
		assertNotNull(json);
		assertTrue(json.length() > 0);
	}

	public void testGetMovie() {
		JSONArray json = this.imdb.getMoviesByTitle("casino royale");

		JSONObject movie = json.optJSONObject(0);
		assertNotNull(movie);
	}

	public void testGetNonExistingMovie() {
		JSONArray json = this.imdb.getMoviesByTitle("awdkaowidoawijdwoaijdawoidjaowid");
		assertNull(json);
	}
}

/**
*	IMDBHandlerTest.java
*
*	@author Johan Brook
*	@copyright (c) 2012 Johan Brook
*	@license MIT
*/

package se.chalmers.watchmetest.net;

import org.json.JSONArray;
import org.json.JSONObject;

import se.chalmers.watchme.net.IMDBHandler;
import se.chalmers.watchme.utils.MovieHelper;
import junit.framework.TestCase;

public class IMDBHandlerTest extends TestCase {

	IMDBHandler imdb;

	protected void setUp() throws Exception {
		super.setUp();

		this.imdb = new IMDBHandler();
	}

	public void testGetMovies() {
		JSONArray json = this.imdb.getMoviesByTitle("casino royale");
		assertNotNull(json);
		assertTrue(json.length() > 0);
	}

	public void testGetMovie() {
		JSONArray json = this.imdb.getMoviesByTitle("casino royale");

		JSONObject movie = json.optJSONObject(0);
		assertNotNull(movie);
	}

	public void testGetNonExistingMovie() {
		JSONArray json = this.imdb.getMoviesByTitle("awdkaowidoawijdwoaijdawoidjaowid");
		assertNull(json);
	}

	public void testParseStringToJSON() {
		String json = "[{key: \"val\"}]";
		String json2 = "{key: \"val\"}";

		JSONObject res = IMDBHandler.parseStringToJSON(json);
		JSONObject res2 = IMDBHandler.parseStringToJSON(json2);

		assertNotNull(res);
		assertNotNull(res2);
		assertNotNull(res.optString("key"));
		assertNotNull(res2.optString("key"));
	}
}

Add test for JSON parse method

Add test for JSON parse method


package com.gruppe27.fellesprosjekt.server;

import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Server;
import com.gruppe27.fellesprosjekt.common.Network;

import java.io.IOException;

public class CalendarServer {
    Server server;
    DatabaseConnector connector;

    public CalendarServer() {
        server = new Server() {
            protected Connection newConnection() {
                return new CalendarConnection();
            }
        };

        Network.register(server);

        server.addListener(new CalendarListener(server));

        try {
            server.bind(Network.PORT);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }

        server.start();
    }

    public static void main(String[] args) {
        CalendarServer server = new CalendarServer();
    }
}

package com.gruppe27.fellesprosjekt.server;

import com.esotericsoftware.kryonet.Connection;
import com.esotericsoftware.kryonet.Server;
import com.gruppe27.fellesprosjekt.common.Network;

import java.io.IOException;

public class CalendarServer {
    private static Server server = null;
    DatabaseConnector connector;

    protected CalendarServer() {
    }

    public static Server getServer() {
        if (server == null) {
            server = new Server() {
                protected Connection newConnection() {
                    return new CalendarConnection();
                }
            };

            Network.register(server);

            server.addListener(new CalendarListener(server));

            try {
                server.bind(Network.PORT);
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(1);
            }

            server.start();
        }
        return server;
    }

    public static void main(String[] args) {
        CalendarServer.getServer();
    }
}

Make the calendar server a singleton

Make the calendar server a singleton


// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.debug.ui.editors;

import org.eclipse.ui.editors.text.TextEditor;

/**
 * A simplistic Javascript editor which supports its own key binding scope.
 */
public class JsEditor extends TextEditor {

  /** The ID of this editor as defined in plugin.xml */
  public static final String EDITOR_ID =
      "org.chromium.debug.ui.editors.JsEditor"; //$NON-NLS-1$

  /** The ID of the editor context menu */
  public static final String EDITOR_CONTEXT = EDITOR_ID + ".context"; //$NON-NLS-1$

  /** The ID of the editor ruler context menu */
  public static final String RULER_CONTEXT = EDITOR_CONTEXT + ".ruler"; //$NON-NLS-1$

  protected void initializeEditor() {
    super.initializeEditor();
    setEditorContextMenuId(EDITOR_CONTEXT);
    setRulerContextMenuId(RULER_CONTEXT);
  }

  public JsEditor() {
    super();
    setSourceViewerConfiguration(new JsSourceViewerConfiguration());
    setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope", //$NON-NLS-1$
        "org.chromium.debug.ui.editors.JsEditor.context" }); //$NON-NLS-1$
  }

}

// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.debug.ui.editors;

import org.eclipse.ui.editors.text.TextEditor;

/**
 * A simplistic Javascript editor which supports its own key binding scope.
 */
public class JsEditor extends TextEditor {

  /** The ID of this editor as defined in plugin.xml */
  public static final String EDITOR_ID =
      "org.chromium.debug.ui.editors.JsEditor"; //$NON-NLS-1$

  /** The ID of the editor context menu */
  public static final String EDITOR_CONTEXT = EDITOR_ID + ".context"; //$NON-NLS-1$

  /** The ID of the editor ruler context menu */
  public static final String RULER_CONTEXT = EDITOR_ID + ".ruler"; //$NON-NLS-1$

  @Override
  protected void initializeEditor() {
    super.initializeEditor();
    setEditorContextMenuId(EDITOR_CONTEXT);
    setRulerContextMenuId(RULER_CONTEXT);
  }

  public JsEditor() {
    super();
    setSourceViewerConfiguration(new JsSourceViewerConfiguration());
    setKeyBindingScopes(new String[] { "org.eclipse.ui.textEditorScope", //$NON-NLS-1$
        "org.chromium.debug.ui.editors.JsEditor.context" }); //$NON-NLS-1$
  }

}

Fix ruler menu for breakpoints

Fix ruler menu for breakpoints

Review URL: http://codereview.chromium.org/99357

git-svn-id: 1dc80909446f7a7ee3e21dd4d1b8517df524e9ee@6 fc8a088e-31da-11de-8fef-1f5ae417a2df


package com.google.sps.servlets;

import com.google.appengine.api.users.UserServiceFactory;
import com.google.sps.utilities.CommonUtils;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that returns the login status of the user. */
@WebServlet("/login-status")
public class LoginStatusServlet extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json;");

    // Get the current login status.
    LoginStatus status;
    if (UserServiceFactory.getUserService().isUserLoggedIn()) {
      status = LoginStatus.getLoggedInInstance();
    } else {
      status = LoginStatus.getNotLoggedInInstance();
    }

    response.getWriter().println(CommonUtils.convertToJson(status));
  }

  private static class LoginStatus {
    private static final LoginStatus STATUS_LOGGED_IN = new LoginStatus(true);
    private static final LoginStatus STATUS_NOT_LOGGED_IN = new LoginStatus(false);
    private boolean isLoggedIn;

    private LoginStatus(boolean isLoggedIn) {
      this.isLoggedIn = isLoggedIn;
    }

    public static LoginStatus getLoggedInInstance() {
      return STATUS_LOGGED_IN;
    }

    public static LoginStatus getNotLoggedInInstance() {
      return STATUS_NOT_LOGGED_IN;
    }
  }
}

package com.google.sps.servlets;

import com.google.appengine.api.users.UserServiceFactory;
import com.google.sps.utilities.CommonUtils;
import java.io.IOException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** Servlet that returns whether user is logged in and email of the user. */
@WebServlet("/login-status")
public class LoginStatusServlet extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    response.setContentType("application/json;");

    LoginStatus status;
    if (UserServiceFactory.getUserService().isUserLoggedIn()) {
      status = new LoginStatus(true, UserServiceFactory.getUserService().getCurrentUser().getEmail());
    } else {
      status = new LoginStatus(false, "");
    }

    response.getWriter().println(CommonUtils.convertToJson(status));
  }

  private class LoginStatus {
    private boolean isLoggedIn;
    private String userEmail;

    public LoginStatus(boolean isLoggedIn, String userEmail) {
      this.isLoggedIn = isLoggedIn;
      this.userEmail = userEmail;
    }
  }
}

Add email field to login status.

Add email field to login status.


package com.kduda.battleships;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("views/battleshipsScene.fxml"));
//        setUserAgentStylesheet(STYLESHEET_CASPIAN);
        primaryStage.setTitle("Battleships");
        primaryStage.setScene(new Scene(root,1024,768));
        primaryStage.show();
    }
}

package com.kduda.battleships;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("views/battleshipsScene.fxml"));
//        setUserAgentStylesheet(STYLESHEET_CASPIAN);
        primaryStage.setTitle("Battleships");
        primaryStage.setScene(new Scene(root);
        primaryStage.setResizable(false);
        primaryStage.show();
    }
}

Change resazible window to false

Change resazible window  to false


package org.stuygfx;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Main {

    private static Interpreter interpreter;
    private static Scanner sc;
    private static String currCommand;
    private static Object[] currArgs;

    public static void main(String[] args) throws IOException {

        interpreter = new Interpreter();

        if (args.length == 0) {
            sc = new Scanner(System.in);
        } else {
            sc = new Scanner(new File(args[0]));
        }

        while (sc.hasNextLine()) {
            currCommand = sc.nextLine().trim();
            if (interpreter.hasNoParams(currCommand)) {
                currArgs = CONSTANTS.NO_ARGS;
            } else {
                currArgs = interpreter.getParams(currCommand, sc.nextLine().trim());
            }
            if (currArgs == null) {
                continue;
            }
            System.out.printf(">> Calling %s with %d parameters\n", currCommand, currArgs.length);
            interpreter.call(currCommand, currArgs);
        }

        System.gc();
    }

}

package org.stuygfx;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class Main {

    private static Interpreter interpreter;
    private static Scanner sc;
    private static String currCommand;
    private static Object[] currArgs;

    public static void main(String[] args) throws IOException {
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.err.println("StuyGFX exitting...");
                System.gc();
            }
        });

        interpreter = new Interpreter();

        if (args.length == 0) {
            sc = new Scanner(System.in);
        } else {
            sc = new Scanner(new File(args[0]));
        }

        while (sc.hasNextLine()) {
            currCommand = sc.nextLine().trim();
            if (interpreter.hasNoParams(currCommand)) {
                currArgs = CONSTANTS.NO_ARGS;
            } else {
                currArgs = interpreter.getParams(currCommand, sc.nextLine().trim());
            }
            if (currArgs == null) {
                continue;
            }
            System.out.printf(">> Calling %s with %d parameters\n", currCommand, currArgs.length);
            interpreter.call(currCommand, currArgs);
        }

        System.gc();
    }

}

Add shutdown hook for garbage collector

Add shutdown hook for garbage collector


package com.partiufast.mercadodowatto;

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

public class MainActivity extends AppCompatActivity {

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

package com.partiufast.mercadodowatto;

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

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //isso é um comentário
    }
}

Add Android project to repo

Add Android project to repo


package groovy.lang;

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

/**
 * An annotation to hold the groovydoc for the annotated element at runtime, we can it "Runtime Groovydoc".
 * Runtime Groovydoc is a bit like Python's Documentation Strings and will be useful for IDE and developers who set a high value on documentations.
 *
 * The usage is very simple, just place @Groovydoc at the beginning of the content of groovydoc, then the new parser Parrot will attach the annotation Groovydoc automatically
 *
 * @since 3.0.0
 */
@Documented
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface Groovydoc {
    String value();
}

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

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

/**
 * An annotation to hold the groovydoc for the annotated element at runtime, we call it "Runtime Groovydoc".
 * Runtime Groovydoc is a bit like Python's Documentation Strings and will be useful for IDE and developers who set a high value on documentations.
 *
 * The usage is very simple, just place @Groovydoc at the beginning of the content of groovydoc, then the new parser Parrot will attach the annotation Groovydoc automatically
 *
 * @since 3.0.0
 */
@Documented
@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.CONSTRUCTOR})
@Retention(RetentionPolicy.RUNTIME)
public @interface Groovydoc {
    String value();
}

Add APL2 header and fix a typo.

Add APL2 header and fix a typo.


/*
 *
 *  Copyright 2018 Netflix, 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.netflix.genie;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Genie Agent application.
 *
 * @author mprimi
 * @since 4.0.0
 */
@SpringBootApplication
public class GenieAgentApplication {
    /**
     * Main method, actual execution is delegated to GenieAgentRunner.
     *
     * @param args command-line arguments
     */
    public static void main(final String[] args) {
        System.exit(new GenieAgentApplication().run(args));
    }

    private int run(final String[] args) {
        return SpringApplication.exit(
            SpringApplication.run(
                GenieAgentApplication.class, args
            )
        );
    }
}

/*
 *
 *  Copyright 2018 Netflix, 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.netflix.genie;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Genie Agent application.
 *
 * @author mprimi
 * @since 4.0.0
 */
@SpringBootApplication
public class GenieAgentApplication {
    /**
     * Main method, actual execution is delegated to GenieAgentRunner.
     *
     * @param args command-line arguments
     */
    public static void main(final String[] args) {
        System.exit(new GenieAgentApplication().run(args));
    }

    private int run(final String[] args) {
        final SpringApplication app = new SpringApplication(GenieAgentApplication.class);
        // Disable parsing of command-line arguments into properties.
        app.setAddCommandLineProperties(false);
        return SpringApplication.exit(app.run(args));
    }
}

Disable Spring parsing of CLI arguments as properties


package com.hmsonline.storm.cassandra.client;

import com.netflix.astyanax.Serializer;
import com.netflix.astyanax.model.Column;

public class AstyanaxColumn<K, V> implements com.hmsonline.storm.cassandra.bolt.mapper.Column<K, V> {
    private Column<K> column = null;
    private Serializer<V> serializer = null;

    public AstyanaxColumn(Column<K> column, Serializer<V> serializer) {
        this.column = column;
    }

    @Override
    public K getKey() {
        return column.getName();
    }

    @Override
    public V getValue() {
        return column.getValue(serializer);
    }
}

package com.hmsonline.storm.cassandra.client;

import com.netflix.astyanax.Serializer;
import com.netflix.astyanax.model.Column;

public class AstyanaxColumn<K, V> implements com.hmsonline.storm.cassandra.bolt.mapper.Column<K, V> {
    private Column<K> column = null;
    private Serializer<V> serializer = null;

    public AstyanaxColumn(Column<K> column, Serializer<V> serializer) {
        this.column = column;
        this.serializer = serializer;
    }

    @Override
    public K getKey() {
        return column.getName();
    }

    @Override
    public V getValue() {
        return column.getValue(serializer);
    }
}

Fix error of getting null value

Fix error of getting null value


package com.opensymphony.workflow.designer;

import java.awt.*;

import javax.swing.*;

import org.jgraph.graph.DefaultGraphCell;
import org.jgraph.graph.GraphConstants;

/**
 * @author Harsh Vijaywargiya Mar 9, 2003 1:04:57 PM
 */
public class WorkflowCell extends DefaultGraphCell
{
  public static final Rectangle defaultBounds = new Rectangle(10, 10, 100, 30);
  protected int id;
  protected String name;

  /**
   * @param cellName
   */
  public WorkflowCell(Object cellName)
  {
    super(cellName);
    GraphConstants.setBounds(attributes, defaultBounds);
    GraphConstants.setOpaque(attributes, true);
    GraphConstants.setBackground(attributes, Color.blue.darker());
    GraphConstants.setForeground(attributes, Color.white);
    GraphConstants.setBorder(attributes, BorderFactory.createRaisedBevelBorder());
    GraphConstants.setEditable(attributes, false);
    GraphConstants.setVerticalAlignment(attributes, SwingConstants.TOP);
    //GraphConstants.setFont(attributes, GraphConstants.defaultFont.deriveFont(Font.BOLD, 12));
  }

  /**
   * Returns the mId.
   * @return int
   */
  public int getId()
  {
    return id;
  }

  /**
   * Returns the mName.
   * @return String
   */
  public String getName()
  {
    return name;
  }

}

package com.opensymphony.workflow.designer;

import java.awt.*;

import javax.swing.*;

import org.jgraph.graph.DefaultGraphCell;
import org.jgraph.graph.GraphConstants;
import org.jgraph.graph.AttributeMap;

/**
 * @author Harsh Vijaywargiya Mar 9, 2003 1:04:57 PM
 */
public class WorkflowCell extends DefaultGraphCell
{
  public static final Rectangle defaultBounds = new Rectangle(10, 10, 100, 30);
  protected int id;
  protected String name;

  /**
   * @param cellName
   */
  public WorkflowCell(Object cellName)
  {
    super(cellName);
    GraphConstants.setBounds(attributes, (Rectangle)defaultBounds.clone());
    GraphConstants.setOpaque(attributes, true);
    GraphConstants.setBackground(attributes, Color.blue.darker());
    GraphConstants.setForeground(attributes, Color.white);
    GraphConstants.setBorder(attributes, BorderFactory.createRaisedBevelBorder());
    GraphConstants.setEditable(attributes, false);
    GraphConstants.setVerticalAlignment(attributes, SwingConstants.TOP);
    //GraphConstants.setFont(attributes, GraphConstants.defaultFont.deriveFont(Font.BOLD, 12));
  }

  /**
   * Returns the mId.
   * @return int
   */
  public int getId()
  {
    return id;
  }

  /**
   * Returns the mName.
   * @return String
   */
  public String getName()
  {
    return name;
  }

}

Clone bounds, don't share them!

Clone bounds, don't share them!