package beast.evolution.tree;

import java.util.List;

import beast.evolution.alignment.TaxonSet;
import beast.evolution.tree.Node;

public interface TreeInterface {
    String getID();

    int getLeafNodeCount();
	int getInternalNodeCount();
	int getNodeCount();

	Node getRoot();
    Node getNode(int i);
    Node [] getNodesAsArray();

    List<Node> getExternalNodes();
    List<Node> getInternalNodes();

    TaxonSet getTaxonset();

	boolean somethingIsDirty();

    public void getMetaData(Node node, Double[] fT, String sPattern);
    public void setMetaData(Node node, Double[] fT, String sPattern);

    /*
    * Note that leaf nodes are always numbered 0,...,nodeCount-1
    * Internal nodes are numbered higher, but the root has no guaranteed
    * number.
    */
}

package beast.evolution.tree;

import java.util.List;

import beast.evolution.alignment.TaxonSet;
import beast.evolution.tree.Node;

public interface TreeInterface {
    String getID();

    int getLeafNodeCount();
	int getInternalNodeCount();
	int getNodeCount();

	Node getRoot();
    Node getNode(int i);
    Node [] getNodesAsArray();

    List<Node> getExternalNodes();
    List<Node> getInternalNodes();

    TaxonSet getTaxonset();

	boolean somethingIsDirty();

    public void getMetaData(Node node, Double[] fT, String sPattern);
    public void setMetaData(Node node, Double[] fT, String sPattern);

    /*
    * Note that leaf nodes are always numbered 0,...,nodeCount-1
    * Internal nodes are numbered higher, but the root has no guaranteed
    * number.
    */

    /**
     * @param node  top of tree/sub tree (null defaults to whole tree)
     * @param nodes array to fill (null will result in creating a new one)
     * @return tree nodes in post-order, children before parents
     */
    default public Node[] listNodesPostOrder(Node node, Node[] nodes) {
        if (node == null) {
            node = getRoot();
        }
        if (nodes == null) {
            final int n = node.getNodeCount();
            nodes = new Node[n];
        }
        getNodesPostOrder(node, nodes, 0);
        return nodes;
    }

    static int
    getNodesPostOrder(final Node node, final Node[] nodes, int pos) {
        //node.m_tree = this;
        for (final Node child : node.children) {
            pos = getNodesPostOrder(child, nodes, pos);
        }
        nodes[pos] = node;
        return pos + 1;
    }
}

Add a (default) interface method to get tree nodes in post-order


package protocolsupport.utils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.Deflater;
import java.util.zip.DeflaterInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

import org.apache.commons.io.IOUtils;

public class CompressionUtils {

	private static final int compressionLevel = getCompressionLevel();

	private static int getCompressionLevel() {
		try {
			return Integer.parseInt(System.getProperty("protocolsupport.compressionlevel", "3"));
		} catch (Throwable t) {
		}
		return 3;
	}

	private static final int compressionBuffer = getCompressionBuffer();

	private static int getCompressionBuffer() {
		try {
			return Integer.parseInt(System.getProperty("protocolsupport.compressionbuffer", "10240"));
		} catch (Throwable t) {
		}
		return 10240;
	}

	public static byte[] compress(byte[] input) throws IOException {
		Deflater deflater = new Deflater(compressionLevel);
		try {
			return IOUtils.toByteArray(new DeflaterInputStream(new ByteArrayInputStream(input), new Deflater(compressionLevel), compressionBuffer));
		} finally {
			deflater.end();
		}
	}

	public static byte[] uncompress(byte[] input) throws IOException {
		Inflater inflater = new Inflater();
		try {
			return IOUtils.toByteArray(new InflaterInputStream(new ByteArrayInputStream(input), inflater, compressionBuffer));
		} finally {
			inflater.end();
		}
	}

}

package protocolsupport.utils;

import java.util.Arrays;
import java.util.zip.Deflater;

public class CompressionUtils {

	private static final int compressionLevel = getCompressionLevel();

	private static int getCompressionLevel() {
		try {
			return Integer.parseInt(System.getProperty("protocolsupport.compressionlevel", "1"));
		} catch (Throwable t) {
		}
		return 1;
	}

	public static byte[] compress(byte[] input) {
		Deflater deflater = new Deflater(compressionLevel);
		try {
			deflater.setInput(input);
			deflater.finish();
			byte[] compressedBuf = new byte[input.length * 11 / 10 + 6];
			int size = deflater.deflate(compressedBuf);
			return Arrays.copyOf(compressedBuf, size);
		} finally {
			deflater.end();
		}
	}

}

Speed up compression, default compression level to 1


package tests;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.*;
import pages.HomePage;
import selenium.WebDriverFactory;
import utils.Log4Test;
import utils.PropertyLoader;

public class BaseTest {
    public static WebDriver driver;

    @BeforeSuite
    public void intEnv() {
        driver = WebDriverFactory.initDriver(PropertyLoader.loadProperty("browser.name"));
        driver.manage().window().maximize();
    }

    @BeforeTest
    public void beforeTest() {
        Log4Test.info("*#*#*#*#*#* Start of the test suite. *#*#*#*#*#*");
    }

    @BeforeMethod
    public void beforeMethod() {
        driver.manage().deleteAllCookies();
        Log4Test.info("-_-_-_-_- Start of the test. -_-_-_-_-");
        HomePage homePage = new HomePage(driver);
        homePage.open();
        Assert.assertTrue(homePage.isOpened(), Log4Test.error("Home page is not open."));
    }

    @AfterMethod
    public void afterMethod() {
        Log4Test.info("-_-_-_-_-  End of the test.  -_-_-_-_-");
    }

    @AfterTest
    public void afterTest() {
        Log4Test.info("*#*#*#*#*#*  End of the test suite.  *#*#*#*#*#*");
    }

    @AfterSuite
    public void shutEnv() {
        if (driver != null) {
            driver.quit();
        }
    }
}

package tests;

import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.*;
import pages.HomePage;
import selenium.WebDriverFactory;
import utils.Log4Test;
import utils.PropertyLoader;

public class BaseTest {
    public static WebDriver driver;

    @BeforeSuite
    public void intEnv() {
        driver = WebDriverFactory.initDriver(PropertyLoader.loadProperty("browser.name"));
        driver.manage().window().maximize();
    }

    @BeforeTest
    public void beforeTest() {
        Log4Test.info("*#*#*#*#*#* Start of the test suite. *#*#*#*#*#*");
    }

    @BeforeMethod
    public void beforeMethod() {
        Log4Test.info("-_-_-_-_- Start of the test. -_-_-_-_-");
        HomePage homePage = new HomePage(driver);
        homePage.open();
        Assert.assertTrue(homePage.isOpened(), Log4Test.error("Home page is not open."));
    }

    @AfterMethod
    public void afterMethod() {
        Log4Test.info("-_-_-_-_-  End of the test.  -_-_-_-_-");
    }

    @AfterTest
    public void afterTest() {
        Log4Test.info("*#*#*#*#*#*  End of the test suite.  *#*#*#*#*#*");
    }

    @AfterSuite
    public void shutEnv() {
        if (driver != null) {
            driver.quit();
        }
    }
}

Revert "Added cookies deletion step to @BeforeMethod."

This reverts commit bc44573ae5011b2155badbc77c530189e0b356ce.


package gx.realtime;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;

import gx.browserchannel.message.DataMessage;
import gx.browserchannel.message.MessageEvent;
import gx.browserchannel.message.MessageHandler;

public class RealtimeMessageHandler implements MessageHandler {

    @Override
    public void receive(MessageEvent e) {
        // Return on invalid data
        if(!(e.getMessage() instanceof DataMessage))
            return;

        // Parse data as event
        DataMessage data = (DataMessage) e.getMessage();
        JsonParser parser = data.getContent().traverse();
        parser.setCodec(new ObjectMapper());
        Event event = null;
        try {
            event = parser.readValueAs(Event.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        // Handle events
        if(event instanceof CollaboratorJoinedEvent) {
            Collaborator user = ((CollaboratorJoinedEvent)event).getCollaborator();
            System.out.println("Collaborator joined event: " + user.getDisplayName());
        }
    }
}

package gx.realtime;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;

import gx.browserchannel.message.DataMessage;
import gx.browserchannel.message.MessageEvent;
import gx.browserchannel.message.MessageHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class RealtimeMessageHandler implements MessageHandler {

    private static Logger logger = LogManager.getLogger(MessageHandler.class);

    @Override
    public void receive(MessageEvent e) {
        logger.debug("Received messageEvent {}", e);
        logger.debug("with message {}", e.getMessage());

        // Return on invalid data
        if(!(e.getMessage() instanceof DataMessage))
            return;

        // Parse data as event
        DataMessage data = (DataMessage) e.getMessage();
        Event event = parseDataMessage(data);

        // Handle events
        if(event instanceof CollaboratorJoinedEvent) {
            Collaborator user = ((CollaboratorJoinedEvent)event).getCollaborator();
            System.out.println("Collaborator joined event: " + user.getDisplayName());
        }
    }

    /**
     * Parses a given DataMessage into an Event object.
     * @param data
     * @return
     */
    protected Event parseDataMessage(DataMessage data)
    {
        JsonParser parser = data.getContent().traverse();
        parser.setCodec(new ObjectMapper());
        Event event = null;
        try {
            event = parser.readValueAs(Event.class);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return event;
    }

}

Split up the receive method into a message parser and handler for easier testing


package org.jtheque.utils;

import org.slf4j.LoggerFactory;

/*
 * Copyright JTheque (Baptiste Wicht)
 *
 * 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.
 */

public class ThreadUtils {
    private static final int PROCESSORS = Runtime.getRuntime().availableProcessors();

    public static int processors(){
        return PROCESSORS;
    }

    public static void joinAll(Iterable<Thread> threads) {
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                LoggerFactory.getLogger(ThreadUtils.class).error(e.getMessage(), e);
            }
        }
    }
}

package org.jtheque.utils;

import org.slf4j.LoggerFactory;

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

/*
 * Copyright JTheque (Baptiste Wicht)
 *
 * 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.
 */

public class ThreadUtils {
    private static final int PROCESSORS = Runtime.getRuntime().availableProcessors();

    public static int processors(){
        return PROCESSORS;
    }

    public static void inNewThread(Runnable runnable){
        ExecutorService executor = Executors.newSingleThreadExecutor();

        executor.submit(runnable);

        executor.shutdown();
    }

    public static void joinAll(Iterable<Thread> threads) {
        for (Thread thread : threads) {
            try {
                thread.join();
            } catch (InterruptedException e) {
                LoggerFactory.getLogger(ThreadUtils.class).error(e.getMessage(), e);
            }
        }
    }
}

Add method to launch a Runnable in a new thread


package de.retest.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/*
 * Taken from https://stackoverflow.com/a/4694155
 */
public class DeleteOnCloseFileInputStream extends FileInputStream {

	private File file;

	public DeleteOnCloseFileInputStream( final File file ) throws FileNotFoundException {
		super( file );
		this.file = file;
	}

	@Override
	public void close() throws IOException {
		try {
			super.close();
		} finally {
			if ( file != null ) {
				file.delete();
				file = null;
			}
		}
	}

}

package de.retest.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

/*
 * Taken from https://stackoverflow.com/a/4694155
 */
public class DeleteOnCloseFileInputStream extends FileInputStream {

	private final File file;

	public DeleteOnCloseFileInputStream( final File file ) throws FileNotFoundException {
		super( file );
		this.file = file;
	}

	@Override
	public void close() throws IOException {
		try {
			super.close();
		} finally {
			FileUtils.forceDelete( file );
		}
	}
}

Fix file.delete ignored return value

Fix file.delete ignored return value


package fr.treeptik.cloudunit.controller;

import fr.treeptik.cloudunit.dto.AboutResource;
import fr.treeptik.cloudunit.dto.HomepageResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by nicolas on 12/12/2016.
 */
@Controller
@RequestMapping("/homepage")
public class HomepageController {

    @Value("#{environment.CU_JENKINS_DOMAIN}")
    private String jenkins;

    @Value("#{environment.CU_GITLAB_DOMAIN}")
    private String gitlab;

    @Value("#{environment.CU_NEXUS_DOMAIN}")
    private String nexus;

    @Value("#{environment.CU_KIBANA_DOMAIN}")
    private String kibana;

    @Value("#{environment.CU_SONAR_DOMAIN}")
    private String sonar;

    @Value("#{environment.CU_LETSCHAT_DOMAIN}")
    private String letschat;

    @RequestMapping(value = "/friends", method = RequestMethod.GET)
    public ResponseEntity<?> listFriends() {
        HomepageResource resource = new HomepageResource(jenkins, gitlab, kibana, nexus, sonar, letschat);
        return ResponseEntity.ok(resource);
    }

}

package fr.treeptik.cloudunit.controller;

import fr.treeptik.cloudunit.dto.AboutResource;
import fr.treeptik.cloudunit.dto.HomepageResource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by nicolas on 12/12/2016.
 */
@Controller
@RequestMapping("/homepage")
public class HomepageController {

    @Value("#{environment.CU_JENKINS_DOMAIN ?: 'jenkins.cloudunit.dev'}")
    private String jenkins;

    @Value("#{environment.CU_GITLAB_DOMAIN} ?: 'gitlab.cloudunit.dev'")
    private String gitlab;

    @Value("#{environment.CU_NEXUS_DOMAIN} ?: 'nexus.cloudunit.dev'")
    private String nexus;

    @Value("#{environment.CU_KIBANA_DOMAIN ?: 'kibana.cloudunit.dev'}")
    private String kibana;

    @Value("#{environment.CU_SONAR_DOMAIN} ?: 'sonar.cloudunit.dev'")
    private String sonar;

    @Value("#{environment.CU_LETSCHAT_DOMAIN} ?: 'letschat.cloudunit.dev'")
    private String letschat;

    @RequestMapping(value = "/friends", method = RequestMethod.GET)
    public ResponseEntity<?> listFriends() {
        HomepageResource resource = new HomepageResource(jenkins, gitlab, kibana, nexus, sonar, letschat);
        return ResponseEntity.ok(resource);
    }

}

Fix : add default value for homepage portal


/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

import com.kurento.kas.media.Native;

/**
 *
 * @author mparis
 *
 */
public class MediaRx extends Native {

	public static final int DEFAULT_MAX_DELAY = 200;

	public static native int startVideoRx(String sdp_str, int maxDelay, VideoRx videoPlayer);
	public static native int stopVideoRx();

	public static native int startAudioRx(String sdp_str, int maxDelay, AudioRx audioPlayer);
	public static native int stopAudioRx();

}

/*
 * Kurento Android Media: Android Media Library based on FFmpeg.
 * Copyright (C) 2011  Tikal Technologies
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 3
 * as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.kurento.kas.media.rx;

import com.kurento.kas.media.Native;

/**
 *
 * @author mparis
 *
 */
public class MediaRx extends Native {

	public static final int DEFAULT_MAX_DELAY = 200;

	public static native int startVideoRx(String sdp, int maxDelay,
			VideoRx videoReceiver);
	public static native int stopVideoRx();

	public static native int startAudioRx(String sdp, int maxDelay,
			AudioRx audioReceiver);
	public static native int stopAudioRx();

}

Change startVideoRx and startAudioRx parameters name.


package nakadi;

/**
 * Helper class to provide {@link LoggingUndefinedEventObserver}.
 */
public class LoggingUndefinedEventObserverProvider implements StreamObserverProvider {

  @Override public StreamObserver createStreamObserver() {
    return new LoggingUndefinedEventObserver();
  }

  @Override public TypeLiteral typeLiteral() {
    return new TypeLiteral<UndefinedEventMapped>() {
    };
  }
}

package nakadi;

/**
 * Helper class to provide {@link LoggingUndefinedEventObserver}.
 */
public class LoggingUndefinedEventObserverProvider implements StreamObserverProvider {

  @Override public StreamObserver createStreamObserver() {
    return new LoggingUndefinedEventObserver();
  }

  @Override public TypeLiteral typeLiteral() {
    return new TypeLiteral<UndefinedEventMapped<String>>() {
    };
  }
}

Update serialization type for undefined events


/*
 * 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.
 */
@Version("1.2.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.plugins.segment;

import aQute.bnd.annotation.Export;
import aQute.bnd.annotation.Version;

/*
 * 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.
 */
@Version("2.0.0")
@Export(optional = "provide:=true")
package org.apache.jackrabbit.oak.plugins.segment;

import aQute.bnd.annotation.Export;
import aQute.bnd.annotation.Version;

OAK-2833: Refactor TarMK
bump export package version as required

git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1682176 13f79535-47bb-0310-9956-ffa450edef68


package com.frederikam.fred.moe;

import com.frederikam.fred.moe.util.SLF4JInputStreamLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class Caddy extends Thread {

    private static final Logger log = LoggerFactory.getLogger(Caddy.class);

    public Caddy() {
        setName("Caddy");
    }

    @Override
    public void run() {
        try {
            log.info("Starting Caddy");

            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("caddy -conf Caddyfile -agree -email $CADDY_EMAIL");
            new SLF4JInputStreamLogger(log, proc.getInputStream()).start();

            try {
                int code = proc.waitFor();
                log.warn("Exited with code " + code);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            log.warn(e.getMessage());
        }
    }
}

package com.frederikam.fred.moe;

import com.frederikam.fred.moe.util.SLF4JInputStreamLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class Caddy extends Thread {

    private static final Logger log = LoggerFactory.getLogger(Caddy.class);

    public Caddy() {
        setName("Caddy");
    }

    @Override
    public void run() {
        try {
            log.info("Starting Caddy");

            ProcessBuilder pb = new ProcessBuilder()
                    .command("caddy", "-conf Caddyfile", "-agree", "-email $CADDY_EMAIL");
            Process proc = pb.start();doc
            new SLF4JInputStreamLogger(log, proc.getInputStream()).start();

            try {
                int code = proc.waitFor();
                log.warn("Exited with code " + code);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        } catch (IOException e) {
            log.warn(e.getMessage());
        }
    }
}

Test to see if caddy works now

Test to see if caddy works now


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

package org.gdg.frisbee.android;

/**
 * Created with IntelliJ IDEA.
 * User: maui
 * Date: 20.04.13
 * Time: 12:19
 */
public class Const {

    // Settings
    public static final String SETTINGS_FIRST_START = "gdg_first_start";
    public static final boolean SETTINGS_FIRST_START_DEFAULT = true;
}

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

package org.gdg.frisbee.android;

/**
 * Created with IntelliJ IDEA.
 * User: maui
 * Date: 20.04.13
 * Time: 12:19
 */
public class Const {

    // Settings
    public static final String SETTINGS_FIRST_START = "gdg_first_start";
    public static final boolean SETTINGS_FIRST_START_DEFAULT = true;
    public static final String GOOGLE_DEVELOPERS_YT_ID = "UC_x5XG1OV2P6uZZ5FSM9Ttw";
    public static final String ANDROID_DEVELOPERS_YT_ID = "UCVHFbqXqoYvEWM1Ddxl0QDg";
    public static final String YOUTUBE_DEVELOPERS_YT_ID = "UCtVd0c0tGXuTSbU5d8cSBUg";
}

Add some Google Dev related YT Channel IDs


package org.oblodiff.token;

import org.oblodiff.token.api.Token;

/**
 * The basic implementation of a {@link Token}, contains code that all {@link Token}s share.
 *
 * @param <T> the type of the content this token represents
 * @author Christian Rösch <christianroesch@gmx.net>
 */
public abstract class BasicToken<T extends Object> implements Token {

    /**
     * the representation of the value/content of this token.
     */
    private final T content;

    public BasicToken(final T ct) {
        super();
        content = ct;
    }

    @Override
    public final int hashCode() {
        return content.hashCode();
    }

    @Override
    public final boolean equals(Object obj) {
        if (!(obj instanceof BasicToken)) {
            return false;
        }

        return content.equals(((BasicToken) obj).content);
    }

    protected T getContent() {
        return content;
    }

    @Override
    public String toString() {
        return super.toString() + " >" + content + "<";
    }
}

package org.oblodiff.token;

import org.oblodiff.token.api.Token;

/**
 * The basic implementation of a {@link Token}, contains code that all {@link Token}s share.
 *
 * @param <T> the type of the content this token represents
 * @author Christian Rösch <christianroesch@gmx.net>
 */
public abstract class BasicToken<T> implements Token {

    /**
     * the representation of the value/content of this token.
     */
    private final T content;

    /**
     * @param ct the content this token represents.
     * @see #getContent() for further details
     */
    public BasicToken(final T ct) {
        super();
        content = ct;
    }

    @Override
    public final int hashCode() {
        return content.hashCode();
    }

    @Override
    public final boolean equals(Object obj) {
        return obj instanceof BasicToken && content.equals(((BasicToken) obj).content);
    }

    /**
     * @return the content of this token. The content is used for generating the hash of this token.
     */
    protected T getContent() {
        return content;
    }

    @Override
    public String toString() {
        return super.toString() + " >" + content + "<";
    }
}

Add JavaDoc and remove warnings.

Add JavaDoc and remove warnings.


package net.openhft.chronicle.bytes;

import java.io.Closeable;

public interface RingBufferReader extends RingBufferReaderStats, Closeable {

    boolean isEmpty();

    boolean isClosed();

    /**
     * Close the reader. After being closed, the reader will not block writers
     */
    @Override
    void close();

    /**
     * the readPosition and readLimit will be adjusted so that the client can read the data
     *
     * @param bytes who's byteStore must be the ring buffer,
     * @return nextReadPosition which should be passed to {@link RingBufferReader#afterRead(long)}
     */
    @SuppressWarnings("rawtypes")
    long beforeRead(Bytes bytes);

    void afterRead(long next);

    /**
     * Convenience method calls both {@link #beforeRead(Bytes)} and {@link #afterRead(long)}
     * @param bytes
     * @return whether read succeeded
     */
    @SuppressWarnings("rawtypes")
    boolean read(BytesOut bytes);

    /**
     * @return the byteStore which backs the ring buffer
     */
    @SuppressWarnings("rawtypes")
    BytesStore byteStore();

    /**
     * Take reader to just past the end of the RB
     */
    void toEnd();
}

package net.openhft.chronicle.bytes;

import java.io.Closeable;

public interface RingBufferReader extends RingBufferReaderStats, Closeable {

    boolean isEmpty();

    boolean isClosed();

    /**
     * Close the reader. After being closed, the reader will not block writers
     */
    @Override
    void close();

    /**
     * the readPosition and readLimit will be adjusted so that the client can read the data
     *
     * @param bytes who's byteStore must be the ring buffer,
     * @return nextReadPosition which should be passed to {@link RingBufferReader#afterRead(long)}
     */
    @SuppressWarnings("rawtypes")
    long beforeRead(Bytes bytes);

    void afterRead(long next);

    void afterRead(long next, long underlyingIndex);

    /**
     * Convenience method calls both {@link #beforeRead(Bytes)} and {@link #afterRead(long)}
     * @param bytes
     * @return whether read succeeded
     */
    @SuppressWarnings("rawtypes")
    boolean read(BytesOut bytes);

    /**
     * @return the byteStore which backs the ring buffer
     */
    @SuppressWarnings("rawtypes")
    BytesStore byteStore();

    /**
     * Take reader to just past the end of the RB
     */
    void toEnd();
}

Allow ring buffer to refer to underlying (drained) queue's index


package sfBugs;

import java.math.BigDecimal;

public class RFE2891944 {

	public static void main(String args[]) {

		BigDecimal bd = new BigDecimal(0.1);
		System.out.println(bd);
	}

}

package sfBugs;

import java.math.BigDecimal;

public class RFE2891944 {

	public static void bug1() {
		BigDecimal bd = new BigDecimal(0.1);
		System.out.println(bd);
	}
	public static void bug2() {
		BigDecimal bd = new BigDecimal(100.0);
		System.out.println(bd);
	}
	public static void bug3() {
		BigDecimal bd = new BigDecimal(1.0);
		System.out.println(bd);
	}

}

Test cases for BigDecimal detector (for RFE 2891944)

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


package org.wikipedia.data;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public final class GsonUtil {
    private static final Gson DEFAULT_GSON = new GsonBuilder().create();

    public static Gson getDefaultGson() {
        return DEFAULT_GSON;
    }

    private GsonUtil() { }
}

package org.wikipedia.data;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public final class GsonUtil {
    private static final String DATE_FORMAT = "MMM dd, yyyy HH:mm:ss";
    private static final Gson DEFAULT_GSON = new GsonBuilder().setDateFormat(DATE_FORMAT).create();

    public static Gson getDefaultGson() {
        return DEFAULT_GSON;
    }

    private GsonUtil() { }
}

Set date format when building default Gson to prevent crash

I have not been able to reproduce this crash, but it seems Gson has a
problem parsing date strings when unmarshalling tab data.

From the info I've looked at online, explicitly defining a date format
will prevent ParseExceptions here:

https://stackoverflow.com/questions/7816586/gson-java-text-
parseexception-unparseable-date

https://stackoverflow.com/questions/33408620/java-gson-java-text-
parseexception-unparseable-date

Bug: T118575
Change-Id: I516e7352f4997703d250980b3e94e5aa88f7ad46


package de.thetaphi.forbiddenapis;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;

/*
 * (C) Copyright Uwe Schindler (Generics Policeman) and others.
 * Parts of this work are licensed to the Apache Software Foundation (ASF)
 * under one or more contributor license agreements.
 *
 * 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.
 */

/**
 * {@inheritDoc}
 * @deprecated Use {@link de.thetaphi.forbiddenapis.ant.AntTask} instead.
 */
@Deprecated
public final class AntTask extends de.thetaphi.forbiddenapis.ant.AntTask {

  @Override
  public void execute() throws BuildException {
    log("DEPRECATED-WARNING: Please change your build.xml to use new task class de.thetaphi.forbiddenapis.ant.AntTask", Project.MSG_WARN);
    super.execute();
  }

}

package de.thetaphi.forbiddenapis;

/*
 * (C) Copyright Uwe Schindler (Generics Policeman) and others.
 * Parts of this work are licensed to the Apache Software Foundation (ASF)
 * under one or more contributor license agreements.
 *
 * 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.
 */

import java.util.Locale;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;

/**
 * {@inheritDoc}
 * @deprecated Use {@link de.thetaphi.forbiddenapis.ant.AntTask} instead.
 */
@Deprecated
public final class AntTask extends de.thetaphi.forbiddenapis.ant.AntTask {

  @Override
  public void execute() throws BuildException {
    log(String.format(Locale.ENGLISH, "DEPRECATED-WARNING: Please change your build.xml to use new task class '%s'",
        getClass().getSuperclass().getName()), Project.MSG_WARN);
    super.execute();
  }

}

Make replace task class name dynamic, move imports


/**
 * Copyright 2008 Matthew Hillsdon
 *
 * 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 net.hillsdon.reviki.web.handlers;

import java.io.InputStream;

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

import org.apache.commons.io.IOUtils;

import net.hillsdon.reviki.web.common.View;

/**
 * Render a stream with a given content type.
 *
 * @author msw
 */
public class StreamView implements View {
  private final String _mimeType;

  private final InputStream _contents;

  /**
   * @param mimeType The content type of the page (eg, "application/xml").
   * @param contents Source of the response body.
   */
  public StreamView(final String mimeType, final InputStream contents) {
    _mimeType = mimeType;
    _contents = contents;
  }

  public void render(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    response.setContentType(_mimeType);
    IOUtils.copy(_contents, response.getWriter());
  }
}

/**
 * Copyright 2008 Matthew Hillsdon
 *
 * 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 net.hillsdon.reviki.web.handlers;

import java.io.InputStream;

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

import org.apache.commons.io.IOUtils;

import net.hillsdon.reviki.web.common.View;

/**
 * Render a stream with a given content type.
 *
 * @author msw
 */
public class StreamView implements View {
  private final String _mimeType;

  private final InputStream _contents;

  /**
   * @param mimeType The content type of the page (eg, "application/xml").
   * @param contents Source of the response body.
   */
  public StreamView(final String mimeType, final InputStream contents) {
    _mimeType = mimeType;
    _contents = contents;
  }

  public void render(final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    response.setContentType(_mimeType);
    IOUtils.copy(_contents, response.getOutputStream());
  }
}

Send stream responses to the OutputStream, to handle binary formats


package org.procrastinationpatients.tts.core;

import com.sun.istack.internal.NotNull;
import javafx.scene.canvas.GraphicsContext;

/**
 * @Author Decker
 */
public interface Drawable {
    public void draw(@NotNull GraphicsContext gc);
}

package org.procrastinationpatients.tts.core;

import javafx.scene.canvas.GraphicsContext;

/**
 * @Author Decker
 */
public interface Drawable {
    public void draw(GraphicsContext gc);
}

Remove annotation which not support by maven.


package org.madhatters.mediaplayer;

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 {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/indexing_screen.fxml"));
        primaryStage.setTitle("Mad Hatter Media Player");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

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

package org.madhatters.mediaplayer;

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 {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("/fxml/indexing_screen.fxml"));

        primaryStage.setResizable(false);
        primaryStage.setTitle("Mad Hatter Media Player");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

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

Disable resizing the indexing screen

Disable resizing the indexing screen


// Copyright 2013 Judson D Neer

package com.singledsoftware.mixmaestro;

import java.io.Serializable;

/**
 * Stores data for an individual channel.
 *
 * @see Serializable
 * @author Judson D Neer
 */
public class Channel implements Serializable {

    // Unique serializable version ID
    private static final long serialVersionUID = -3705403776567370897L;

    // Unique numeric identifier for the channel
    private final int id;

    // Single character that identifies a channel type
    // TODO make this an enumeration
    private final char type;

    // User-assigned name for the channel
    private final String name;

    /**
     * Constructor.
     *
     * @param i New id
     * @param t New type
     * @param n New name
     */
    public Channel(int i, char t, String n) {
        id = i;
        type = t;
        name = n;
    }

    /**
     * @see java.io.Serializable#toString()
     */
    @Override
    public String toString() {
        // TODO put id and type in parens?
        return name;
    }

}

// Copyright 2013 Judson D Neer

package com.singledsoftware.mixmaestro;

import java.io.Serializable;

/**
 * Stores data for an individual channel.
 *
 * @see Serializable
 * @author Judson D Neer
 */
public class Channel implements Serializable {

    // Unique serializable version ID
    private static final long serialVersionUID = -3705403776567370897L;

    // Unique identifier for the channel
    private final String id;

    // Single character that identifies a channel type
    // TODO make this an enumeration
    private final char type;

    // User-assigned name for the channel
    private final String name;

    /**
     * Constructor.
     *
     * @param i New id
     * @param t New type
     * @param n New name
     */
    public Channel(String i, char t, String n) {
        id = i;
        type = t;
        name = n;
    }

    /**
     * @see java.io.Serializable#toString()
     */
    @Override
    public String toString() {
        // TODO put id and type in parens?
        return name;
    }

}

Update channel object to store ID as a string.


/*
Copyright (c) 2013, Colorado State University
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/

package galileo.event;

public interface EventListener {

    /**
     * Called when an event is ready to be processed.
     *
     * @param event GalileoEvent that was received; null if the connection has
     * been terminated.
     */
    public void onEvent(GalileoEvent event);
}

/*
Copyright (c) 2013, Colorado State University
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

This software is provided by the copyright holders and contributors "as is" and
any express or implied warranties, including, but not limited to, the implied
warranties of merchantability and fitness for a particular purpose are
disclaimed. In no event shall the copyright holder or contributors be liable for
any direct, indirect, incidental, special, exemplary, or consequential damages
(including, but not limited to, procurement of substitute goods or services;
loss of use, data, or profits; or business interruption) however caused and on
any theory of liability, whether in contract, strict liability, or tort
(including negligence or otherwise) arising in any way out of the use of this
software, even if advised of the possibility of such damage.
*/

package galileo.event;

public interface EventListener {

    /**
     * Called when an event is ready to be processed.  The implementation of
     * this method should be lightweight; large amounts of processing here will
     * delay the event processing framework because its threads will call this
     * method.
     *
     * @param event GalileoEvent that was received; null if the connection has
     * been terminated.
     */
    public void onEvent(GalileoEvent event);
}

Add more information to the onMessage method


package org.ccci.gto.android.common.db;

import android.support.test.runner.AndroidJUnit4;
import android.test.InstrumentationTestCase;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.ccci.gto.android.common.db.TestDao.TestContract.RootTable;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@RunWith(AndroidJUnit4.class)
public class ExpressionTest extends InstrumentationTestCase {

    private TestDao getDao() {
        return new TestDao(getInstrumentation().getContext());
    }

    @Test
    public void testEqualsSql() {
        final TestDao dao = getDao();

        Expression equalsExpression = RootTable.FIELD_TEST.eq("1");
        assertThat(equalsExpression.buildSql(dao).first, is("(root.test == ?)"));
    }

    @Test
    public void testNotEqualsSql() {
        final TestDao dao = getDao();

        Expression notEqualsExpression = RootTable.FIELD_TEST.not().eq("1");
        assertThat(notEqualsExpression.buildSql(dao).first, is("(NOT (root.test) == ?)"));
    }
}

package org.ccci.gto.android.common.db;

import android.support.test.runner.AndroidJUnit4;
import android.test.InstrumentationTestCase;

import org.junit.Test;
import org.junit.runner.RunWith;

import static org.ccci.gto.android.common.db.TestDao.TestContract.RootTable;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@RunWith(AndroidJUnit4.class)
public class ExpressionTest extends InstrumentationTestCase {

    private TestDao getDao() {
        return new TestDao(getInstrumentation().getContext());
    }

    @Test
    public void testEqualsSql() {
        final TestDao dao = getDao();

        Expression equalsExpression = RootTable.FIELD_TEST.eq("1");
        assertThat(equalsExpression.buildSql(dao).first, is("(root.test == ?)"));
    }

    @Test
    public void testNotEqualsSql() {
        final TestDao dao = getDao();

        Expression notEqualsExpression = RootTable.FIELD_TEST.not().eq("1");
        assertThat(notEqualsExpression.buildSql(dao).first, is("(NOT (root.test) == ?)"));
    }

    @Test
    public void testCount() {
        final TestDao dao = getDao();

        Expression countExpression = RootTable.FIELD_TEST.count();
        assertThat(countExpression.buildSql(dao).first, is("COUNT (root.test)"));
    }

    @Test
    public void testCountInHaving() {
        final TestDao dao = getDao();

        Expression countExpression = RootTable.FIELD_TEST.count().eq(1);
        assertThat(countExpression.buildSql(dao).first, is("(COUNT (root.test) == 1)"));
    }
}

Add test for count method

Add test for count method


package com.decker.Essentials;

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

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

import com.decker.Essentials.Category.Category;
import com.decker.Essentials.User.User;

public class Center extends org.sipc.se.plugin.PluginImpl
{

    Category category;
    public Center()
    {
	super();
	this.category=Category.getInstance();
    }

    @Override
    public void getResponse(HttpServletRequest request, HttpServletResponse response)
    {
	String url = request.getRequestURI();
	String target = url.substring(url.indexOf("Essentials") + "Essentials".length() + 1);
	OutputStream stream;
	try
	{
	    stream = response.getOutputStream();
	    byte[] resource;

	    if (target.matches(".*.exec"))
	    {
		//dynamic generate
		User current=new User(request.getCookies());
		resource = Command.Execute(current,request);
	    } else
	    {
		//static resource
		resource = ResourceManager.getInstance().getResource(target);
	    }

	    if (resource.length == 0)
	    {
		response.setStatus(404);
	    }

	    stream.write(resource);

	} catch (IOException e)
	{

	}

    }

    @Override
    public String getUrl()
    {
	return "Essentials";
    }

    @Override
    public boolean onEnable()
    {
	// TODO Auto-generated method stub
	return true;
    }
}

package com.decker.Essentials;

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

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

import com.decker.Essentials.Category.Category;
import com.decker.Essentials.User.User;

public class Center extends org.sipc.se.plugin.PluginImpl
{

    Category category;
    public Center()
    {
	super();
	this.category=Category.getInstance();
    }

    @Override
    public void getResponse(HttpServletRequest request, HttpServletResponse response)
    {
	String url = request.getRequestURI();
	String target = url.substring(url.indexOf("Essentials") + "Essentials".length() + 1);
	OutputStream stream;
	try
	{
	    stream = response.getOutputStream();
	    byte[] resource=null;

	    if (target.matches(".*.exec"))
	    {
		//dynamic generate
		User current=new User(request.getCookies());
		resource = Command.Execute(current,request);
	    } else
	    {
		//static resource
		resource = ResourceManager.getInstance().getResource(target);
	    }

	    if (resource.length == 0)
	    {
		response.setStatus(404);
	    }

	    stream.write(resource);

	} catch (IOException e)
	{

	}

    }

    @Override
    public String getUrl()
    {
	return "Essentials";
    }

    @Override
    public boolean onEnable()
    {
	// TODO Auto-generated method stub
	return true;
    }
}

Add defuault Homepage to all category

Add defuault Homepage to all category


package com.todoist.model;

import java.util.regex.Pattern;

public class Sanitizers {
    public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+";
    public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:@";
    public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+";

    public static final Pattern PROJECT_NAME_INVALID_PATTERN =
            Pattern.compile("[" + PROJECT_NAME_INVALID_CHARACTERS + "]+");
    public static final Pattern LABEL_NAME_INVALID_PATTERN =
            Pattern.compile("[" + LABEL_NAME_INVALID_CHARACTERS + "]+");
    public static final Pattern FILTER_NAME_INVALID_PATTERN =
            Pattern.compile("[" + FILTER_NAME_INVALID_CHARACTERS + "]+");

    public static final String REPLACEMENT = "_";
}

package com.todoist.model;

import java.util.regex.Pattern;

public class Sanitizers {
    public static final String PROJECT_NAME_INVALID_CHARACTERS = "<>\"=#+";
    public static final String LABEL_NAME_INVALID_CHARACTERS = "<>\"=#+\\s%!?~:@()";
    public static final String FILTER_NAME_INVALID_CHARACTERS = "<>\"=#+";

    public static final Pattern PROJECT_NAME_INVALID_PATTERN =
            Pattern.compile("[" + PROJECT_NAME_INVALID_CHARACTERS + "]+");
    public static final Pattern LABEL_NAME_INVALID_PATTERN =
            Pattern.compile("[" + LABEL_NAME_INVALID_CHARACTERS + "]+");
    public static final Pattern FILTER_NAME_INVALID_PATTERN =
            Pattern.compile("[" + FILTER_NAME_INVALID_CHARACTERS + "]+");

    public static final String REPLACEMENT = "_";
}

Update label sanitizer regex to add parenthesis


package codingpro.werewolves.server;

import java.io.File;
import java.io.IOException;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class IOUtils {

	/**
	 * @return whether or not the file had to be created AND that was successful
	 */
	public static boolean createFileIfNotExists(String path) {
		File file = new File(path);
		if (!file.exists()) {
			try {
				return file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

}

package codingpro.werewolves.server;

import java.io.File;
import java.io.IOException;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class IOUtils {

	/**
	 * @return whether or not the file had to be created AND that was successful
	 */
	public static boolean createFileIfNotExists(String path) {
		File file = new File(path);
		if (!file.exists()) {
			try {
				return file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

	/**
	 * @return whether or not the directory had to be created AND that was successful
	 */
	public static boolean createDirectory(String path) {
		File file = new File(path);
		return file.mkdirs();
	}

}

Add a function to create directories

Add a function to create directories


package org.lemsml.jlemsviz;

import org.lemsml.jlems.expression.ParseError;
import org.lemsml.jlems.run.ConnectionError;
import org.lemsml.jlems.run.RuntimeError;
import org.lemsml.jlems.sim.ContentError;
import org.lemsml.jlems.sim.ParseException;
import org.lemsml.jlems.type.BuildException;
import org.lemsml.jlems.xml.XMLException;
import org.lemsml.jlemsio.Main;
import org.lemsml.jlemsio.logging.DefaultLogger;
import org.lemsml.jlemsviz.datadisplay.SwingDataViewerFactory;

public final class VizMain {

	 private VizMain() {

	 }

    public static void main(String[] argv) throws ConnectionError, ContentError, RuntimeError, ParseError, ParseException, BuildException, XMLException {

    	SwingDataViewerFactory.initialize();
		DefaultLogger.initialize();

    	Main.main(argv);
    }
}

package org.lemsml.jlemsviz;

import org.lemsml.jlems.expression.ParseError;
import org.lemsml.jlems.run.ConnectionError;
import org.lemsml.jlems.run.RuntimeError;
import org.lemsml.jlems.sim.ContentError;
import org.lemsml.jlems.sim.ParseException;
import org.lemsml.jlems.type.BuildException;
import org.lemsml.jlems.xml.XMLException;
import org.lemsml.jlemsio.Main;
import org.lemsml.jlemsio.logging.DefaultLogger;
import org.lemsml.jlemsio.out.FileResultWriterFactory;
import org.lemsml.jlemsviz.datadisplay.SwingDataViewerFactory;

public final class VizMain {

	 private VizMain() {

	 }

    public static void main(String[] argv) throws ConnectionError, ContentError, RuntimeError, ParseError, ParseException, BuildException, XMLException {
    	FileResultWriterFactory.initialize();
    	SwingDataViewerFactory.initialize();
		DefaultLogger.initialize();

    	Main.main(argv);
    }
}

Initialize the file writer by default.

Initialize the file writer by default.


package org.plugin.dot;

import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;

import org.jetbrains.annotations.NotNull;
import org.plugin.dot.psi.DotId;
import org.plugin.dot.psi.impl.DotDotgraphStmtImpl;
import static org.plugin.dot.DotPSITreeUtil.getNotMentionedNodeIds;

/**
 * Dot annotator highlights and annotates dot language code based on following rule:
 * all nodes which are used in edges but not declared explicitly will be
 * annotated as "No such such node specified in graph"
 */
public class DotAnnotator implements Annotator {

    /**
     * The method annotates all nodes which are used in edges but not declared explicitly
     *
     * @param element element you would like to annotate
     * @param holder  annotation holder
     */
    @Override
    public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
        if (element instanceof DotDotgraphStmtImpl) {
            for (DotId id : getNotMentionedNodeIds(element)) {
                TextRange range = new TextRange(id.getTextRange().getStartOffset(),
                        id.getTextRange().getStartOffset());
                Annotation annotation = holder.createInfoAnnotation(range, "No such such node specified in graph");
                annotation.setHighlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL);
            }

        }

    }
}

package org.plugin.dot;

import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.lang.annotation.Annotation;
import com.intellij.lang.annotation.AnnotationHolder;
import com.intellij.lang.annotation.Annotator;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.PsiElement;

import org.jetbrains.annotations.NotNull;
import org.plugin.dot.psi.DotId;
import org.plugin.dot.psi.impl.DotDotgraphStmtImpl;
import static org.plugin.dot.DotPSITreeUtil.getNotMentionedNodeIds;

/**
 * Dot annotator highlights and annotates dot language code based on following rule:
 * all nodes which are used in edges but not declared explicitly will be
 * annotated as "No such such node specified in graph"
 */
public class DotAnnotator implements Annotator {

    /**
     * The method annotates all nodes which are used in edges but not declared explicitly
     *
     * @param element element you would like to annotate
     * @param holder  annotation holder
     */
    @Override
    public void annotate(@NotNull final PsiElement element, @NotNull AnnotationHolder holder) {
        if (element instanceof DotDotgraphStmtImpl) {
            for (DotId id : getNotMentionedNodeIds(element)) {
                TextRange range = new TextRange(id.getTextRange().getStartOffset(),
                        id.getTextRange().getEndOffset());
                Annotation annotation = holder.createInfoAnnotation(range, "No such such node specified in graph");
                annotation.setHighlightType(ProblemHighlightType.LIKE_UNUSED_SYMBOL);
            }

        }

    }
}

Fix incorrect text range selection in annotator


package com.nullprogram.guide;

import com.nullprogram.guide.Arch;
import com.nullprogram.guide.NativeGuide;
import junit.framework.TestCase;

public class NativeGuideTest extends TestCase {

    public final void testIsArchitecture() {
        String root = "/com/nullprogram/guide/";
        try {
            NativeGuide.prepare(Arch.LINUX_32,   root + "linux32/libguide.so");
            NativeGuide.prepare(Arch.LINUX_64,   root + "linux64/libguide.so");
            NativeGuide.prepare(Arch.WINDOWS_32, root + "windows32/guide.dll");
            NativeGuide.prepare(Arch.WINDOWS_64, root + "windows64/guide.dll");
            System.loadLibrary("guide");
        } catch (java.io.IOException e) {
            fail("Could not prepare library: " + e);
        }
    }
}

package com.nullprogram.guide;

import com.nullprogram.guide.Arch;
import com.nullprogram.guide.NativeGuide;
import junit.framework.TestCase;

public class NativeGuideTest extends TestCase {

    public final void testIsArchitecture() {
        try {
            NativeGuide.prepare(Arch.LINUX_32,   "linux32/libguide.so");
            NativeGuide.prepare(Arch.LINUX_64,   "linux64/libguide.so");
            NativeGuide.prepare(Arch.WINDOWS_32, "windows32/guide.dll");
            NativeGuide.prepare(Arch.WINDOWS_64, "windows64/guide.dll");
            System.loadLibrary("guide");
        } catch (java.io.IOException e) {
            fail("Could not prepare library: " + e);
        }
    }
}

Tidy up the unit test a little.

Tidy up the unit test a little.


package com.comp110.lecture23;

public class CDSPlaygroundSoln {

  public static void main(String[] args) {

    Food[] menu = Food.readFoodsFromCSV("data/rams-2015-11-10.csv");

    for(int i = 0; i < menu.length; i++) {
      Food food = menu[i];
      if(food.getSeating().equals("Dinner")) {
        if(food.isHighProteinAndOrganic()) {
          System.out.println(food.getSeating() + " - " + food);
        }
      }
    }
  }

}

package com.comp110.lecture23;

public class CDSPlaygroundSoln {

  public static void main(String[] args) {

    Food[] menu = Food.readFoodsFromCSV("data/rams-2015-11-10.csv");

    for(int i = 0; i < menu.length; i++) {
      Food food = menu[i];
      if(food.getSeating().equals("Dinner")) {
        if(food.isHighProteinAndOrganic()) {
          System.out.println(food);
        }
      }
    }
  }

}

Change print statement of solution.

Change print statement of solution.


package com.haxademic.core.draw.color;

import processing.core.PApplet;

import com.haxademic.core.app.P;

public class ColorUtil {

	public static int colorWithIntAndAlpha( PApplet p, int color, int alpha ) {
		// from: http://processing.org/discourse/beta/num_1261125421.html
		return (color & 0xffffff) | (alpha << 24);
	}

	public static int colorFromHex( String hex ) {
		return P.unhex("FF"+hex.substring(1));
	}

	public static float componentByPercent( float percent ) {
		return percent * 255f;
	}

	public final static int alphaFromColorInt( int c ) { return (c >> 24) & 0xFF; }
	public final static int redFromColorInt( int c ) { return (c >> 16) & 0xFF;	}
	public final static int greenFromColorInt( int c ) { return (c >> 8)  & 0xFF; }
	public final static int blueFromColorInt( int c ) { return c & 0xFF; }

}

package com.haxademic.core.draw.color;

import processing.core.PApplet;

import com.haxademic.core.app.P;

public class ColorUtil {

	public static int colorWithIntAndAlpha( PApplet p, int color, int alpha ) {
		// from: http://processing.org/discourse/beta/num_1261125421.html
		return (color & 0xffffff) | (alpha << 24);
	}

	public static int colorFromHex( String hex ) {
		return P.unhex("FF"+hex.substring(1));
	}

	public static float componentByPercent( float percent ) {
		return percent * 255f;
	}

	public final static int alphaFromColorInt( int c ) { return (c >> 24) & 0xFF; }
	public final static int redFromColorInt( int c ) { return (c >> 16) & 0xFF;	}
	public final static int greenFromColorInt( int c ) { return (c >> 8)  & 0xFF; }
	public final static int blueFromColorInt( int c ) { return c & 0xFF; }
	public final static int[] rgbFromColorInt( int c ) { return new int[]{redFromColorInt(c), greenFromColorInt(c), blueFromColorInt(c)}; }

}

Add color component array getter

Add color component array getter


package ch.deletescape.primitives;

public class Int {
  /**
   * Private Constructor to prevent initialization
   */
  private Int() {
  }

  /**
   * Converts a long value to integer by simply casting it
   *
   * @param lng
   *          the long value to convert
   * @return the resulting integer.
   */
  public static int from(long lng) {
    return (int) lng;
  }

  /**
   * Converts a double value to integer by simply casting it
   *
   * @param dbl
   *          the double value to convert
   * @return the resulting integer.
   */
  public static int from(double dbl) {
    return (int) dbl;
  }

  /**
   * Converts a float value to integer by simply casting it
   *
   * @param flt
   *          the float value to convert
   * @return the resulting integer.
   */
  public static int from(float flt) {
    return (int) flt;
  }

  /**
   * Converts a boolean value to integer, {@code true} resulting in {@code 1} and {@code false}
   * resulting in {@code 0}
   *
   * @param bool
   *          the boolean value to convert
   * @return the resulting integer.
   */
  public static int from(boolean bool) {
    return bool ? 1 : 0;
  }
}

package ch.deletescape.primitives;

import java.util.Random;

public class Int {
  private static Random random;

  /**
   * Private Constructor to prevent initialization
   */
  private Int() {
  }

  /**
   * Converts a long value to integer by simply casting it
   *
   * @param lng
   *          the long value to convert
   * @return the resulting integer.
   */
  public static int from(long lng) {
    return (int) lng;
  }

  /**
   * Converts a double value to integer by simply casting it
   *
   * @param dbl
   *          the double value to convert
   * @return the resulting integer.
   */
  public static int from(double dbl) {
    return (int) dbl;
  }

  /**
   * Converts a float value to integer by simply casting it
   *
   * @param flt
   *          the float value to convert
   * @return the resulting integer.
   */
  public static int from(float flt) {
    return (int) flt;
  }

  /**
   * Converts a boolean value to integer, {@code true} resulting in {@code 1} and {@code false}
   * resulting in {@code 0}
   *
   * @param bool
   *          the boolean value to convert
   * @return the resulting integer.
   */
  public static int from(boolean bool) {
    return bool ? 1 : 0;
  }

  /**
   * Convenience method for {@link Random#nextInt()}, the first time this method is called a new
   * {@link Random} instance is created
   *
   * @return a pseudorandom integer value.
   * @see Random
   */
  public static int random() {
    if (random == null) {
      random = new Random();
    }
    return random.nextInt();
  }
}

Implement a convenience method to generate random integers


package pl.vgtworld.imagedraw.filters.edgedetect;

import pl.vgtworld.imagedraw.ImageDrawEntity;
import pl.vgtworld.imagedraw.filters.ImageDrawFilter;
import pl.vgtworld.imagedraw.filters.matrix.MatrixFilter;

public class EdgeDetectFilter implements ImageDrawFilter {

	@Override
	public void doFilter(ImageDrawEntity image, int x, int y, int width, int height) {
		float[][] matrix = new float[][] {
				{ 0, 1, 0 },
				{ 1, -4, 1 },
				{ 0, 1, 0 }
		};
		MatrixFilter filter = new MatrixFilter(matrix);
		filter.doFilter(image, x, y, width, height);
	}

}

package pl.vgtworld.imagedraw.filters.edgedetect;

import pl.vgtworld.imagedraw.ImageDrawEntity;
import pl.vgtworld.imagedraw.filters.ImageDrawFilter;
import pl.vgtworld.imagedraw.filters.matrix.MatrixFilter;

public class EdgeDetectFilter implements ImageDrawFilter {

	private static final int DEFAULT_STRENGTH = 1;

	private float strength;

	public EdgeDetectFilter() {
		strength = DEFAULT_STRENGTH;
	}

	public EdgeDetectFilter(float strength) {
		this.strength = strength;
	}

	@Override
	public void doFilter(ImageDrawEntity image, int x, int y, int width, int height) {
		float[][] matrix = new float[][] {
				{ 0, strength, 0 },
				{ strength, -4 * strength, strength },
				{ 0, strength, 0 }
		};
		MatrixFilter filter = new MatrixFilter(matrix);
		filter.doFilter(image, x, y, width, height);
	}

}

Add overloaded constructor with configurabe strength.


package com.alibaba.rocketmq.example.verify;

import com.alibaba.rocketmq.common.UtilAll;
import org.apache.commons.cli.*;

public class SelectPartition {
    public static void main(String[] args) throws ParseException {
        Options options = new Options();

        Option option = new Option("p", "path", true, "Paths in CSV");
        options.addOption(option);

        CommandLineParser parser = new DefaultParser();
        CommandLine commandLine = parser.parse(options, args);
        if (!commandLine.hasOption('p')) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Select Partition", options);
            return;
        }

        String pathCSV = commandLine.getOptionValue("p");
        UtilAll.selectPath(pathCSV);

        UtilAll.getDiskPartitionSpaceUsedPercent(pathCSV);
    }
}

package com.alibaba.rocketmq.example.verify;

import com.alibaba.rocketmq.common.UtilAll;
import org.apache.commons.cli.*;

public class SelectPartition {
    public static void main(String[] args) throws ParseException {
        Options options = new Options();

        Option option = new Option("p", "path", true, "Paths in CSV");
        options.addOption(option);

        CommandLineParser parser = new DefaultParser();
        CommandLine commandLine = parser.parse(options, args);
        if (!commandLine.hasOption('p')) {
            HelpFormatter helpFormatter = new HelpFormatter();
            helpFormatter.printHelp("Select Partition", options);
            return;
        }

        String pathCSV = commandLine.getOptionValue("p");
        UtilAll.selectPath(pathCSV);

        double ratio = UtilAll.getDiskPartitionSpaceUsedPercent(pathCSV);
        System.out.println(ratio);
    }
}

Add test to show disk usage ratio per partition.


package com.rewayaat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * Main entrypoint to rewayaat app.
 */
@EnableCaching
@SpringBootApplication(scanBasePackages = {"com.rewayaat.config", "com.rewayaat.controllers"})
public class RewayaatApplication {

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

    public static void main(String[] args) {
        SpringApplication.run(RewayaatApplication.class, args);
    }
}

package com.rewayaat;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 * Main entrypoint to rewayaat app.
 */
@EnableCaching
@SpringBootApplication(scanBasePackages = {"com.rewayaat.config", "com.rewayaat.controllers",
    "com.rewayaat.service"})
public class RewayaatApplication {

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

    public static void main(String[] args) {
        SpringApplication.run(RewayaatApplication.class, args);
    }
}

Update spring base packages scan list

Update spring base packages scan list


package emp;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;

/**
 * Drops the employee table used by the other examples.
 */
public class DropTable {

    public static void main(String[] args) throws SQLException {
        PoolDataSource pool = PoolDataSourceFactory.getPoolDataSource();
        pool.setURL(args[0]);
        pool.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");

        try (Connection con = pool.getConnection()) {
            Statement stmt = con.createStatement();
            stmt.execute("drop table emp");
        }
    }

}

package emp;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.ucp.jdbc.PoolDataSource;
import oracle.ucp.jdbc.PoolDataSourceFactory;

/**
 * Drops the employee table used by the other examples.
 */
public class DropTable {

    public static void main(String[] args) throws SQLException {
        PoolDataSource pool = PoolDataSourceFactory.getPoolDataSource();
        pool.setURL(args[0]);
        pool.setConnectionFactoryClassName("oracle.jdbc.pool.OracleDataSource");

        try (Connection con = pool.getConnection()) {
            Statement stmt = con.createStatement();
            stmt.execute("drop table emp");
            System.out.println("Table dropped.");
        }
    }

}

Print that table is dropped.

Print that table is dropped.


package com.adyen;

import com.adyen.model.applicationinfo.ApplicationInfo;
import org.junit.Test;

import static com.adyen.Client.LIB_NAME;
import static com.adyen.Client.LIB_VERSION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class ApplicationInfoTest {

    @Test
    public void TestApplicationInfoEquals() {
        ApplicationInfo applicationInfo = new ApplicationInfo();
        ApplicationInfo applicationInfo2 = new ApplicationInfo();

        assertEquals(applicationInfo, applicationInfo2);
        assertNotNull(applicationInfo.getAdyenLibrary());
        assertEquals(LIB_NAME, applicationInfo.getAdyenLibrary().getName());
        assertEquals(LIB_VERSION, applicationInfo.getAdyenLibrary().getVersion());
    }
}

package com.adyen;

import com.adyen.model.applicationinfo.ApplicationInfo;
import org.junit.Test;

import static com.adyen.Client.LIB_NAME;
import static com.adyen.Client.LIB_VERSION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

public class ApplicationInfoTest {

    @Test
    public void TestApplicationInfoEquals() {
        ApplicationInfo applicationInfo = new ApplicationInfo();
        ApplicationInfo applicationInfo2 = new ApplicationInfo();

        assertEquals(applicationInfo, applicationInfo2);
    }

    @Test
    public void TestApplicationInfoPrefilledLibraryFields() {
        ApplicationInfo applicationInfo = new ApplicationInfo();

        assertNotNull(applicationInfo.getAdyenLibrary());
        assertNotNull(applicationInfo.getAdyenLibrary().getName());
        assertEquals(LIB_NAME, applicationInfo.getAdyenLibrary().getName());
        assertNotNull(applicationInfo.getAdyenLibrary().getVersion());
        assertEquals(LIB_VERSION, applicationInfo.getAdyenLibrary().getVersion());
    }
}

[PW-828] Add application info to adyen-java-api-library
- Add default library fields test


package no.dusken.momus.config;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInit implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext config = new AnnotationConfigWebApplicationContext();
        config.register(ApplicationConfig.class, SecurityConfig.class);

        servletContext.addListener(new ContextLoaderListener(config));
        ServletRegistration.Dynamic dispatcher =
            servletContext.addServlet("momusapi", new DispatcherServlet());

        dispatcher.setAsyncSupported(true);

        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/api/*");

        // Add security to the servlet
        servletContext.addFilter("springSecurityFilterChain", DelegatingFilterProxy.class)
            .addMappingForUrlPatterns(null, false, "/*");
	}

}

package no.dusken.momus.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.DispatcherServlet;

public class WebInit implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext config = new AnnotationConfigWebApplicationContext();
        config.register(ApplicationConfig.class, SecurityConfig.class);

        servletContext.addListener(new ContextLoaderListener(config));
        ServletRegistration.Dynamic dispatcher =
            servletContext.addServlet("momusapi", new DispatcherServlet());

        dispatcher.setAsyncSupported(true);

        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/api/*");

        // Add security to the servlet
        FilterRegistration.Dynamic securityFilter = servletContext
                .addFilter("springSecurityFilterChain", DelegatingFilterProxy.class);

        securityFilter.setAsyncSupported(true);
        securityFilter.addMappingForUrlPatterns(null, false, "/*");
	}

}

Enable async for security filter

Enable async for security filter


package org.dynmap;

import org.bukkit.block.Block;
import org.bukkit.block.BlockDamageLevel;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPlaceEvent;

public class DynmapBlockListener extends BlockListener {
	private MapManager mgr;

	public DynmapBlockListener(MapManager mgr) {
		this.mgr = mgr;
	}

	@Override
	public void onBlockPlaced(BlockPlaceEvent event) {
		Block blockPlaced = event.getBlockPlaced();
		mgr.touch(blockPlaced.getX(), blockPlaced.getY(), blockPlaced.getZ());
	}

	@Override
	public void onBlockDamaged(BlockDamageEvent event) {
		if (event.getDamageLevel() == BlockDamageLevel.BROKEN) {
			Block blockBroken = event.getBlock();
			mgr.touch(blockBroken.getX(), blockBroken.getY(), blockBroken.getZ());
		}
	}
}

package org.dynmap;

import org.bukkit.block.Block;
import org.bukkit.block.BlockDamageLevel;
import org.bukkit.event.block.BlockDamageEvent;
import org.bukkit.event.block.BlockListener;
import org.bukkit.event.block.BlockPlaceEvent;

public class DynmapBlockListener extends BlockListener {
	private MapManager mgr;

	public DynmapBlockListener(MapManager mgr) {
		this.mgr = mgr;
	}

	@Override
	public void onBlockPlace(BlockPlaceEvent event) {
		Block blockPlaced = event.getBlockPlaced();
		mgr.touch(blockPlaced.getX(), blockPlaced.getY(), blockPlaced.getZ());
	}

	public void onBlockDamage(BlockDamageEvent event) {
				if (event.getDamageLevel() == BlockDamageLevel.BROKEN) {
			Block blockBroken = event.getBlock();
			mgr.touch(blockBroken.getX(), blockBroken.getY(), blockBroken.getZ());
		}
	}
}

Fix to be compatible with latest Bukkit.


package models;

import java.util.*;

public class PersonHistory {

    public class Record {
        public Date most_recent_charge;
        public Rule rule;
        public int count;
    }

    public ArrayList<Record> rule_records;

    public PersonHistory(Person p) {
        HashMap<Rule, Record> records = new HashMap<Rule, Record>();
        for (Charge c : p.charges) {
            Record r = records.get(c.rule);
            if (r == null) {
                r = new Record();
                r.most_recent_charge = c.the_case.date;
                r.count = 1;
                r.rule = c.rule;
                records.put(c.rule, r);
            } else {
                r.count++;
            }
        }

        rule_records = new ArrayList<Record>(records.values());
    }

}

package models;

import java.util.*;

public class PersonHistory {

    public class Record {
        public Date most_recent_charge;
        public Rule rule;
        public int count;
    }

    public ArrayList<Record> rule_records;

    public PersonHistory(Person p) {
        HashMap<Rule, Record> records = new HashMap<Rule, Record>();
        for (Charge c : p.charges) {
            Record r = records.get(c.rule);
            if (r == null) {
                r = new Record();
                r.most_recent_charge = c.the_case.date;
                if (r.most_recent_charge == null) {
                    r.most_recent_charge = c.the_case.meeting.date;
                }
                r.count = 1;
                r.rule = c.rule;
                records.put(c.rule, r);
            } else {
                r.count++;
            }
        }

        rule_records = new ArrayList<Record>(records.values());
    }

}

Use meeting date if case has no date

Use meeting date if case has no date


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

import java.io.File;

import org.aexlib.gae.tool.TestEnvironment;

import com.google.appengine.tools.development.ApiProxyLocalImpl;
import com.google.apphosting.api.ApiProxy;

import junit.framework.TestCase;

public class GAEBaseTestCase extends TestCase {
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        ApiProxy.setEnvironmentForCurrentThread(new TestEnvironment());
        ApiProxy.setDelegate(new ApiProxyLocalImpl(new File("target")){});
    }

    @Override
    protected void tearDown() throws Exception {
        // not strictly necessary to null these out but there's no harm either
        ApiProxy.setDelegate(null);
        ApiProxy.setEnvironmentForCurrentThread(null);
        super.tearDown();
    }

    public void testDummy() {

    }
}

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

import java.io.File;

import com.google.appengine.tools.development.ApiProxyLocalImpl;
import com.google.apphosting.api.ApiProxy;

import junit.framework.TestCase;

public class GAEBaseTestCase extends TestCase {
    @Override
    protected void setUp() throws Exception {
        super.setUp();
        ApiProxy.setEnvironmentForCurrentThread(new TestEnvironment());
        ApiProxy.setDelegate(new ApiProxyLocalImpl(new File("target")){});
    }

    @Override
    protected void tearDown() throws Exception {
        // not strictly necessary to null these out but there's no harm either
        ApiProxy.setDelegate(null);
        ApiProxy.setEnvironmentForCurrentThread(null);
        super.tearDown();
    }

    public void testDummy() {

    }
}

Fix wrong change for package.

Fix wrong change for package.


package benjamin.groehbiel.ch;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationTest.class)
public class JedisTest {

    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    public void testJedisConnectionFactory() {
        assertNotNull(jedisConnectionFactory);
    }

    @Test
    public void testRedisTemplate() {
        assertNotNull(redisTemplate);
    }

}

package benjamin.groehbiel.ch;

import org.junit.After;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationTest.class)
public class JedisTest {

    @Autowired
    private JedisConnectionFactory jedisConnectionFactory;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @After
    public void tearDown() {
        redisTemplate.getConnectionFactory().getConnection().flushDb();
    }

    @Test
    public void testJedisConnectionFactory() {
        assertNotNull(jedisConnectionFactory);
    }

    @Test
    public void testRedisTemplate() {
        assertNotNull(redisTemplate);
    }

    @Test
    public void addEntry() {
        Long index = redisTemplate.opsForList().rightPush("ben", "grohbiel");
        assertThat(index, equalTo(1L));
    }

    @Test
    public void getEntry() {
        redisTemplate.opsForList().rightPush("ben", "grohbiel");
        String s = redisTemplate.opsForValue().get("ben");
        Assert.assertThat(s, equalTo("grohbiel"));
    }

}

Set and get a redis key-value pair.

Set and get a redis key-value pair.


package fi.bitrite.android.ws.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import fi.bitrite.android.ws.model.Host;

/**
 * Provide basic info that may not be accessible any other way.
 */
public class GlobalInfo {
    private static Host mMemberInfo = null;
    public static final String warmshowersCookieDomain = ".warmshowers.org";
    public static final String warmshowersBaseUrl = "https://www.warmshowers.org";
}

package fi.bitrite.android.ws.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

import fi.bitrite.android.ws.model.Host;

/**
 * Provide basic info that may not be accessible any other way.
 */
public class GlobalInfo {
    private static Host mMemberInfo = null;
    public static final String warmshowersCookieDomain = ".warmshowers.org";
    public static final String warmshowersBaseUrl = "https://www.warmshowers.org";

    // For testing with staging site
//    public static final String warmshowersCookieDomain = ".wsupg.net";
//    public static final String warmshowersBaseUrl = "http://www.wsupg.net";

}

Add commented-out details on staging site


package SW9.abstractions;

import SW9.utility.colors.Color;

public enum QueryState {
    SUCCESSFUL(Color.GREEN, Color.Intensity.I700, "✓"),
    ERROR(Color.RED, Color.Intensity.I700, "✘"),
    RUNNING(Color.GREY_BLUE, Color.Intensity.I600, "···"),
    UNKNOWN(Color.GREY, Color.Intensity.I600, "?"),
    SYNTAX_ERROR(Color.PURPLE, Color.Intensity.I700, "!");

    private final Color color;
    private final Color.Intensity colorIntensity;
    private final String indicator;

    QueryState(final Color color, final Color.Intensity colorIntensity, final String indicator) {
        this.color = color;
        this.colorIntensity = colorIntensity;
        this.indicator = indicator;
    }

    public Color getColor() {
        return color;
    }

    public Color.Intensity getColorIntensity() {
        return colorIntensity;
    }

    public String getIndicator() {
        return indicator;
    }
}

package SW9.abstractions;

import SW9.utility.colors.Color;

public enum QueryState {
    SUCCESSFUL(Color.GREEN, Color.Intensity.I700),
    ERROR(Color.RED, Color.Intensity.I700),
    RUNNING(Color.GREY_BLUE, Color.Intensity.I600),
    UNKNOWN(Color.GREY, Color.Intensity.I600),
    SYNTAX_ERROR(Color.PURPLE, Color.Intensity.I700);

    private final Color color;
    private final Color.Intensity colorIntensity;

    QueryState(final Color color, final Color.Intensity colorIntensity) {
        this.color = color;
        this.colorIntensity = colorIntensity;
    }

    public Color getColor() {
        return color;
    }

    public Color.Intensity getColorIntensity() {
        return colorIntensity;
    }
}

Remove unused property in query state

Remove unused property in query state


package com.dao.mydebts;

import okhttp3.MediaType;

/**
 * @author Oleg Chernovskiy on 05.04.16.
 */
public class Constants {

    //private static final String SERVER_ENDPOINT = "sorseg.ru:8080/debt/";
    //private static final String SERVER_ENDPOINT = "http://demoth.no-ip.org:8080/debt/";
    private static final String SERVER_ENDPOINT = "http://192.168.1.165:1337/debt/";

    public static final String SERVER_ENDPOINT_DEBTS = SERVER_ENDPOINT + "debts";
    public static final String SERVER_ENDPOINT_CREATE = SERVER_ENDPOINT + "createDebt";
    public static final String SERVER_ENDPOINT_APPROVE = SERVER_ENDPOINT + "approve";

    public static final MediaType JSON_MIME_TYPE = MediaType.parse("application/json");

    public static final int DEBT_REQUEST_LOADER = 0;

    private Constants() {
    }

}

package com.dao.mydebts;

import okhttp3.MediaType;

/**
 * @author Oleg Chernovskiy on 05.04.16.
 */
public class Constants {

    //private static final String SERVER_ENDPOINT = "sorseg.ru:8080/debt/";
    //private static final String SERVER_ENDPOINT = "http://demoth.no-ip.org:8080/debt/";
    private static final String SERVER_ENDPOINT = "http://sorseg.ru:1337/debt/";

    public static final String SERVER_ENDPOINT_DEBTS = SERVER_ENDPOINT + "debts";
    public static final String SERVER_ENDPOINT_CREATE = SERVER_ENDPOINT + "createDebt";
    public static final String SERVER_ENDPOINT_APPROVE = SERVER_ENDPOINT + "approve";

    public static final MediaType JSON_MIME_TYPE = MediaType.parse("application/json");

    public static final int DEBT_REQUEST_LOADER = 0;

    private Constants() {
    }

}

Change URL back to sorseg.ru (brought up instance)


package controller;

import boundary.PlayerApplication;
import boundary.PlayerBoardView;
import boundary.PlayerLevelView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import model.PlayerModel;

public class PlayerRestartLevelCtrl implements ActionListener{
  PlayerApplication app;
  PlayerModel model;

  public PlayerRestartLevelCtrl(PlayerApplication app, PlayerModel model) {
    this.app = app;
    this.model = model;
  }

  public void actionPerformed(ActionEvent event) {
    model.level.discardBoard();
    model.level.realizeBoard();

    PlayerBoardView boardView = ((PlayerLevelView) app.getView()).boardView;
    boardView.repaint();
  }
}

package controller;

import boundary.PlayerApplication;
import boundary.PlayerBoardView;
import boundary.PlayerLevelView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import model.PlayerModel;

public class PlayerRestartLevelCtrl implements ActionListener{
  PlayerApplication app;
  PlayerModel model;

  public PlayerRestartLevelCtrl(PlayerApplication app, PlayerModel model) {
    this.app = app;
    this.model = model;
  }

  public void actionPerformed(ActionEvent event) {
    model.level.discardBoard();
    model.level.realizeBoard();
    model.reset();

    PlayerBoardView boardView = ((PlayerLevelView) app.getView()).boardView;
    boardView.repaint();
  }
}

Add the rest of the functionality for Restarting a Level that was mentioned previously


@FunctionalInterface
interface Function {
    double apply(double x);
}

public class TwiceApp {
    private static double twice(Function f, double x) {
        return f.apply(f.apply(x));
    }
    public static void main(String[] args) {
        assert twice((x)->x+2, 10) == 14;
        assert twice(Math::floor, -11.77) == -12;
    }
}

@FunctionalInterface
interface Function {
    double apply(double x);
}

public class TwiceApp {
    private static double twice(Function f, double x) {
        return f.apply(f.apply(x));
    }
    public static void main(String[] args) {
        assert twice(x->x+2, 10) == 14;
        assert twice(Math::floor, -11.77) == -12;
    }
}

Write lambda without parens in Java

Write lambda without parens in Java


package info.u_team.u_team_core.intern.command.uteamcore;

import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;

import net.minecraft.command.*;
import net.minecraft.command.arguments.ResourceLocationArgument;
import net.minecraft.command.impl.LocateBiomeCommand;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.registries.ForgeRegistries;

public class LocateBiomeSubCommand {

	public static ArgumentBuilder<CommandSource, ?> register() {
		return Commands.literal("locatebiome") //
				.requires(source -> source.hasPermissionLevel(2)) //
				.then(Commands.argument("biome", ResourceLocationArgument.resourceLocation()) //
						.suggests((context, builder) -> ISuggestionProvider.suggest(ForgeRegistries.BIOMES.getKeys().stream().map(ResourceLocation::toString), builder)) //
						.executes(context -> locateBiome(context.getSource(), context.getArgument("biome", ResourceLocation.class))));
	}

	private static int locateBiome(CommandSource source, ResourceLocation biomeRegistryName) throws CommandSyntaxException {
		return LocateBiomeCommand.func_241049_a_(source, biomeRegistryName);
	}
}

package info.u_team.u_team_core.intern.command.uteamcore;

import com.mojang.brigadier.builder.ArgumentBuilder;
import com.mojang.brigadier.exceptions.CommandSyntaxException;

import net.minecraft.command.*;
import net.minecraft.command.arguments.*;
import net.minecraft.command.impl.LocateBiomeCommand;
import net.minecraft.util.ResourceLocation;

public class LocateBiomeSubCommand {

	public static ArgumentBuilder<CommandSource, ?> register() {
		return Commands.literal("locatebiome") //
				.requires(source -> source.hasPermissionLevel(2)) //
				.then(Commands.argument("biome", ResourceLocationArgument.resourceLocation()) //
						.suggests(SuggestionProviders.field_239574_d_) //
						.executes(context -> locateBiome(context.getSource(), context.getArgument("biome", ResourceLocation.class))));
	}

	private static int locateBiome(CommandSource source, ResourceLocation biomeRegistryName) throws CommandSyntaxException {
		return LocateBiomeCommand.func_241049_a_(source, biomeRegistryName);
	}
}

Fix locate biome sub command

Fix locate biome sub command


package bloople.net.stories;

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

/**
 * Created by i on 27/05/2016.
 */
public class StoryParser {
    private Scanner scanner;

    public StoryParser(Reader reader) {
        scanner = new Scanner(reader);
        scanner.useDelimiter("\n\n");
    }

    public void parse(Story story) throws IOException {
        while(scanner.hasNext()) {
            story.add(next());
        }
    }

    public Node next() throws IOException {
        String content = scanner.next();

        if(content.startsWith("#")) {
            return NodeFactory.heading(content);
        }
        else {
            return NodeFactory.paragraph(content);
        }
    }
}

package bloople.net.stories;

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

/**
 * Created by i on 27/05/2016.
 */
public class StoryParser {
    private Scanner scanner;

    public StoryParser(Reader reader) {
        scanner = new Scanner(reader);
        scanner.useDelimiter("(?:\r?\n){2,}+");
    }

    public void parse(Story story) throws IOException {
        while(scanner.hasNext()) {
            story.add(next());
        }
    }

    public Node next() throws IOException {
        String content = scanner.next();

        if(content.startsWith("#")) {
            return NodeFactory.heading(content);
        }
        else {
            return NodeFactory.paragraph(content);
        }
    }
}

Fix story parsing to support both windows and linux style newlines; Allow extra newlines between nodes


package water.api;

import water.DKV;
import water.Value;

import com.google.gson.JsonObject;

public class Remove extends Request {
  protected final H2OExistingKey _key = new H2OExistingKey(KEY);

  @Override
  protected Response serve() {
    Value v = _key.value();

    try {
      DKV.remove(v._key);
    } catch( Exception e ) {
      return Response.error(e.getMessage());
    }

    JsonObject response = new JsonObject();
    response.addProperty(KEY, _key.toString());
    return Response.redirect(response, StoreView.class, null);
  }
}

package water.api;

import water.UKV;
import water.Value;

import com.google.gson.JsonObject;

public class Remove extends Request {
  protected final H2OExistingKey _key = new H2OExistingKey(KEY);

  @Override
  protected Response serve() {
    Value v = _key.value();

    try {
      UKV.remove(v._key);
    } catch( Exception e ) {
      return Response.error(e.getMessage());
    }

    JsonObject response = new JsonObject();
    response.addProperty(KEY, _key.toString());
    return Response.redirect(response, StoreView.class, null);
  }
}

Fix bug with Key delete using DKV instead of UKV

Would leave behind all the internal chunks and only remove the hex array head