"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/demo/ConsoleApp/src/net/sf/launch4j/example/ConsoleApp.java",".java","2858","73","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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 net.sf.launch4j.example; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class ConsoleApp { public static void main(String[] args) { StringBuffer sb = new StringBuffer(""Hello World!\n\nJava version: ""); sb.append(System.getProperty(""java.version"")); sb.append(""\nJava home: ""); sb.append(System.getProperty(""java.home"")); sb.append(""\nCurrent dir: ""); sb.append(System.getProperty(""user.dir"")); if (args.length > 0) { sb.append(""\nArgs: ""); for (int i = 0; i < args.length; i++) { sb.append(args[i]); sb.append(' '); } } sb.append(""\n\nEnter a line of text, Ctrl-C to stop.\n\n>""); System.out.print(sb.toString()); try { BufferedReader is = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = is.readLine()) != null && !line.equalsIgnoreCase(""quit"")) { System.out.print(""You wrote: "" + line + ""\n\n>""); } is.close(); System.exit(123); } catch (IOException e) { System.err.print(e); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/demo/SimpleApp/src/net/sf/launch4j/example/SimpleApp.java",".java","3743","105","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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 net.sf.launch4j.example; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.UIManager; public class SimpleApp extends JFrame { public SimpleApp(String[] args) { super(""Java Application""); final int inset = 100; Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setBounds (inset, inset, screenSize.width - inset * 2, screenSize.height - inset * 2); JMenu menu = new JMenu(""File""); menu.add(new JMenuItem(""Open"")); menu.add(new JMenuItem(""Save"")); JMenuBar mb = new JMenuBar(); mb.setOpaque(true); mb.add(menu); setJMenuBar(mb); this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(123); }}); setVisible(true); StringBuffer sb = new StringBuffer(""Java version: ""); sb.append(System.getProperty(""java.version"")); sb.append(""\nJava home: ""); sb.append(System.getProperty(""java.home"")); sb.append(""\nCurrent dir: ""); sb.append(System.getProperty(""user.dir"")); if (args.length > 0) { sb.append(""\nArgs: ""); for (int i = 0; i < args.length; i++) { sb.append(args[i]); sb.append(' '); } } JOptionPane.showMessageDialog(this, sb.toString(), ""Info"", JOptionPane.INFORMATION_MESSAGE); } public static void setLAF() { JFrame.setDefaultLookAndFeelDecorated(true); Toolkit.getDefaultToolkit().setDynamicLayout(true); System.setProperty(""sun.awt.noerasebackground"",""true""); try { UIManager.setLookAndFeel(""com.sun.java.swing.plaf.windows.WindowsLookAndFeel""); } catch (Exception e) { System.err.println(""Failed to set LookAndFeel""); } } public static void main(String[] args) { setLAF(); new SimpleApp(args); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/Main.java",".java","3605","100","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2008 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 21, 2005 */ package net.sf.launch4j; import java.io.File; import java.io.InputStream; import java.util.Properties; import net.sf.launch4j.config.ConfigPersister; import net.sf.launch4j.formimpl.MainFrame; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class Main { private static String _name; private static String _description; public static void main(String[] args) { try { Properties props = new Properties(); InputStream in = Main.class.getClassLoader() .getResourceAsStream(""launch4j.properties""); props.load(in); in.close(); setDescription(props); if (args.length == 0) { ConfigPersister.getInstance().createBlank(); MainFrame.createInstance(); } else if (args.length == 1 && !args[0].startsWith(""-"")) { ConfigPersister.getInstance().load(new File(args[0])); Builder b = new Builder(Log.getConsoleLog()); b.build(); } else { System.out.println(_description + Messages.getString(""Main.usage"") + "": launch4j config.xml""); } } catch (Exception e) { Log.getConsoleLog().append(e.getMessage()); } } public static String getName() { return _name; } public static String getDescription() { return _description; } private static void setDescription(Properties props) { _name = ""Launch4j "" + props.getProperty(""version""); _description = _name + "" (http://launch4j.sourceforge.net/)\n"" + ""Cross-platform Java application wrapper"" + "" for creating Windows native executables.\n\n"" + ""Copyright (C) 2004, 2008 Grzegorz Kowal\n\n"" + ""Launch4j comes with ABSOLUTELY NO WARRANTY.\n"" + ""This is free software, licensed under the BSD License.\n"" + ""This product includes software developed by the Apache Software Foundation"" + "" (http://www.apache.org/).""; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/FileChooserFilter.java",".java","2639","77","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on 2004-01-15 */ package net.sf.launch4j; import java.io.File; import javax.swing.filechooser.FileFilter; /** * @author Copyright (C) 2004 Grzegorz Kowal */ public class FileChooserFilter extends FileFilter { String _description; String[] _extensions; public FileChooserFilter(String description, String extension) { _description = description; _extensions = new String[] {extension}; } public FileChooserFilter(String description, String[] extensions) { _description = description; _extensions = extensions; } public boolean accept(File f) { if (f.isDirectory()) { return true; } String ext = Util.getExtension(f); for (int i = 0; i < _extensions.length; i++) { if (ext.toLowerCase().equals(_extensions[i].toLowerCase())) { return true; } } return false; } public String getDescription() { return _description; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/Builder.java",".java","6332","208","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on 2005-04-24 */ package net.sf.launch4j; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringTokenizer; import net.sf.launch4j.binding.InvariantViolationException; import net.sf.launch4j.config.Config; import net.sf.launch4j.config.ConfigPersister; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class Builder { private final Log _log; private final File _basedir; public Builder(Log log) { _log = log; _basedir = Util.getJarBasedir(); } public Builder(Log log, File basedir) { _log = log; _basedir = basedir; } /** * @return Output file path. */ public File build() throws BuilderException { final Config c = ConfigPersister.getInstance().getConfig(); try { c.validate(); } catch (InvariantViolationException e) { throw new BuilderException(e.getMessage()); } File rc = null; File ro = null; File outfile = null; FileInputStream is = null; FileOutputStream os = null; final RcBuilder rcb = new RcBuilder(); try { rc = rcb.build(c); ro = Util.createTempFile(""o""); outfile = ConfigPersister.getInstance().getOutputFile(); Cmd resCmd = new Cmd(_basedir); resCmd.addExe(""windres"") .add(Util.WINDOWS_OS ? ""--preprocessor=type"" : ""--preprocessor=cat"") .add(""-J rc -O coff -F pe-i386"") .addAbsFile(rc) .addAbsFile(ro); _log.append(Messages.getString(""Builder.compiling.resources"")); resCmd.exec(_log); Cmd ldCmd = new Cmd(_basedir); ldCmd.addExe(""ld"") .add(""-mi386pe"") .add(""--oformat pei-i386"") .add((c.getHeaderType().equals(Config.GUI_HEADER)) ? ""--subsystem windows"" : ""--subsystem console"") .add(""-s"") // strip symbols .addFiles(c.getHeaderObjects()) .addAbsFile(ro) .addFiles(c.getLibs()) .add(""-o"") .addAbsFile(outfile); _log.append(Messages.getString(""Builder.linking"")); ldCmd.exec(_log); if (!c.isDontWrapJar()) { _log.append(Messages.getString(""Builder.wrapping"")); int len; byte[] buffer = new byte[1024]; is = new FileInputStream(Util.getAbsoluteFile( ConfigPersister.getInstance().getConfigPath(), c.getJar())); os = new FileOutputStream(outfile, true); while ((len = is.read(buffer)) > 0) { os.write(buffer, 0, len); } } _log.append(Messages.getString(""Builder.success"") + outfile.getPath()); return outfile; } catch (IOException e) { Util.delete(outfile); _log.append(e.getMessage()); throw new BuilderException(e); } catch (ExecException e) { Util.delete(outfile); String msg = e.getMessage(); if (msg != null && msg.indexOf(""windres"") != -1) { if (e.getErrLine() != -1) { _log.append(Messages.getString(""Builder.line.has.errors"", String.valueOf(e.getErrLine()))); _log.append(rcb.getLine(e.getErrLine())); } else { _log.append(Messages.getString(""Builder.generated.resource.file"")); _log.append(rcb.getContent()); } } throw new BuilderException(e); } finally { Util.close(is); Util.close(os); Util.delete(rc); Util.delete(ro); } } } class Cmd { private final List _cmd = new ArrayList(); private final File _basedir; private final File _bindir; public Cmd(File basedir) { _basedir = basedir; String path = System.getProperty(""launch4j.bindir""); if (path == null) { _bindir = new File(basedir, ""bin""); } else { File bindir = new File(path); _bindir = bindir.isAbsolute() ? bindir : new File(basedir, path); } } public Cmd add(String s) { StringTokenizer st = new StringTokenizer(s); while (st.hasMoreTokens()) { _cmd.add(st.nextToken()); } return this; } public Cmd addAbsFile(File file) { _cmd.add(file.getPath()); return this; } public Cmd addFile(String pathname) { _cmd.add(new File(_basedir, pathname).getPath()); return this; } public Cmd addExe(String pathname) { if (Util.WINDOWS_OS) { pathname += "".exe""; } _cmd.add(new File(_bindir, pathname).getPath()); return this; } public Cmd addFiles(List files) { for (Iterator iter = files.iterator(); iter.hasNext();) { addFile((String) iter.next()); } return this; } public void exec(Log log) throws ExecException { String[] cmd = (String[]) _cmd.toArray(new String[_cmd.size()]); Util.exec(cmd, log); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/OptionParser.java",".java","2772","72","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on 2005-04-24 */ package net.sf.launch4j; //import net.sf.launch4j.config.Config; //import org.apache.commons.cli.CommandLine; //import org.apache.commons.cli.CommandLineParser; //import org.apache.commons.cli.HelpFormatter; //import org.apache.commons.cli.Options; //import org.apache.commons.cli.ParseException; //import org.apache.commons.cli.PosixParser; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class OptionParser { // private final Options _options; // // public OptionParser() { // _options = new Options(); // _options.addOption(""h"", ""header"", true, ""header""); // } // // public Config parse(Config c, String[] args) throws ParseException { // CommandLineParser parser = new PosixParser(); // CommandLine cl = parser.parse(_options, args); // c.setJar(getFile(props, Config.JAR)); // c.setOutfile(getFile(props, Config.OUTFILE)); // } // // public void printHelp() { // HelpFormatter formatter = new HelpFormatter(); // formatter.printHelp(""launch4j"", _options); // } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/Messages.java",".java","2978","79","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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 net.sf.launch4j; import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = ""net.sf.launch4j.messages""; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private static final MessageFormat FORMATTER = new MessageFormat(""""); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } public static String getString(String key, String arg0) { return getString(key, new Object[] {arg0}); } public static String getString(String key, String arg0, String arg1) { return getString(key, new Object[] {arg0, arg1}); } public static String getString(String key, String arg0, String arg1, String arg2) { return getString(key, new Object[] {arg0, arg1, arg2}); } public static String getString(String key, Object[] args) { try { FORMATTER.applyPattern(RESOURCE_BUNDLE.getString(key)); return FORMATTER.format(args); } catch (MissingResourceException e) { return '!' + key + '!'; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/Util.java",".java","5877","198","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on 2005-04-24 */ package net.sf.launch4j; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class Util { public static final boolean WINDOWS_OS = System.getProperty(""os.name"") .toLowerCase().startsWith(""windows""); private Util() {} public static File createTempFile(String suffix) throws IOException { String tmpdir = System.getProperty(""launch4j.tmpdir""); if (tmpdir != null) { if (tmpdir.indexOf(' ') != -1) { throw new IOException(Messages.getString(""Util.tmpdir"")); } return File.createTempFile(""launch4j"", suffix, new File(tmpdir)); } else { return File.createTempFile(""launch4j"", suffix); } } /** * Returns the base directory of a jar file or null if the class is a standalone file. * @return System specific path * * Based on a patch submitted by Josh Elsasser */ public static File getJarBasedir() { String url = Util.class.getClassLoader() .getResource(Util.class.getName().replace('.', '/') + "".class"") .getFile() .replaceAll(""%20"", "" ""); if (url.startsWith(""file:"")) { String jar = url.substring(5, url.lastIndexOf('!')); int x = jar.lastIndexOf('/'); if (x == -1) { x = jar.lastIndexOf('\\'); } String basedir = jar.substring(0, x + 1); return new File(basedir); } else { return new File("".""); } } public static File getAbsoluteFile(File basepath, File f) { return f.isAbsolute() ? f : new File(basepath, f.getPath()); } public static String getExtension(File f) { String name = f.getName(); int x = name.lastIndexOf('.'); if (x != -1) { return name.substring(x); } else { return """"; } } public static void exec(String[] cmd, Log log) throws ExecException { BufferedReader is = null; try { if (WINDOWS_OS) { for (int i = 0; i < cmd.length; i++) { cmd[i] = cmd[i].replaceAll(""/"", ""\\\\""); } } Process p = Runtime.getRuntime().exec(cmd); is = new BufferedReader(new InputStreamReader(p.getErrorStream())); String line; int errLine = -1; Pattern pattern = Pattern.compile("":\\d+:""); while ((line = is.readLine()) != null) { log.append(line); Matcher matcher = pattern.matcher(line); if (matcher.find()) { errLine = Integer.valueOf( line.substring(matcher.start() + 1, matcher.end() - 1)) .intValue(); if (line.matches(""(?i).*unrecognized escape sequence"")) { log.append(Messages.getString(""Util.use.double.backslash"")); } break; } } is.close(); p.waitFor(); if (errLine != -1) { throw new ExecException(Messages.getString(""Util.exec.failed"") + "": "" + cmd, errLine); } if (p.exitValue() != 0) { throw new ExecException(Messages.getString(""Util.exec.failed"") + ""("" + p.exitValue() + ""): "" + cmd); } } catch (IOException e) { close(is); throw new ExecException(e); } catch (InterruptedException e) { close(is); throw new ExecException(e); } } public static void close(final InputStream o) { if (o != null) { try { o.close(); } catch (IOException e) { System.err.println(e); // XXX log } } } public static void close(final OutputStream o) { if (o != null) { try { o.close(); } catch (IOException e) { System.err.println(e); // XXX log } } } public static void close(final Reader o) { if (o != null) { try { o.close(); } catch (IOException e) { System.err.println(e); // XXX log } } } public static void close(final Writer o) { if (o != null) { try { o.close(); } catch (IOException e) { System.err.println(e); // XXX log } } } public static boolean delete(File f) { return (f != null) ? f.delete() : false; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/Log.java",".java","3125","106","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 12, 2005 */ package net.sf.launch4j; import javax.swing.JTextArea; import javax.swing.SwingUtilities; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public abstract class Log { private static final Log _consoleLog = new ConsoleLog(); private static final Log _antLog = new AntLog(); public abstract void clear(); public abstract void append(String line); public static Log getConsoleLog() { return _consoleLog; } public static Log getAntLog() { return _antLog; } public static Log getSwingLog(JTextArea textArea) { return new SwingLog(textArea); } } class ConsoleLog extends Log { public void clear() { System.out.println(""\n""); } public void append(String line) { System.out.println(""launch4j: "" + line); } } class AntLog extends Log { public void clear() { System.out.println(""\n""); } public void append(String line) { System.out.println(line); } } class SwingLog extends Log { private final JTextArea _textArea; public SwingLog(JTextArea textArea) { _textArea = textArea; } public void clear() { SwingUtilities.invokeLater(new Runnable() { public void run() { _textArea.setText(""""); }}); } public void append(final String line) { SwingUtilities.invokeLater(new Runnable() { public void run() { _textArea.append(line + ""\n""); }}); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/BuilderException.java",".java","2038","53","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 13, 2005 */ package net.sf.launch4j; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class BuilderException extends Exception { public BuilderException() {} public BuilderException(Throwable t) { super(t); } public BuilderException(String msg) { super(msg); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/RcBuilder.java",".java","11072","341","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on 2005-04-24 */ package net.sf.launch4j; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import net.sf.launch4j.config.Config; import net.sf.launch4j.config.ConfigPersister; import net.sf.launch4j.config.Jre; import net.sf.launch4j.config.Msg; import net.sf.launch4j.config.Splash; import net.sf.launch4j.config.VersionInfo; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class RcBuilder { // winnt.h public static final int LANG_NEUTRAL = 0; public static final int SUBLANG_NEUTRAL = 0; public static final int SUBLANG_DEFAULT = 1; public static final int SUBLANG_SYS_DEFAULT = 2; // MANIFEST public static final int MANIFEST = 1; // ICON public static final int APP_ICON = 1; // BITMAP public static final int SPLASH_BITMAP = 1; // RCDATA public static final int JRE_PATH = 1; public static final int JAVA_MIN_VER = 2; public static final int JAVA_MAX_VER = 3; public static final int SHOW_SPLASH = 4; public static final int SPLASH_WAITS_FOR_WINDOW = 5; public static final int SPLASH_TIMEOUT = 6; public static final int SPLASH_TIMEOUT_ERR = 7; public static final int CHDIR = 8; public static final int SET_PROC_NAME = 9; public static final int ERR_TITLE = 10; public static final int GUI_HEADER_STAYS_ALIVE = 11; public static final int JVM_OPTIONS = 12; public static final int CMD_LINE = 13; public static final int JAR = 14; public static final int MAIN_CLASS = 15; public static final int CLASSPATH = 16; public static final int WRAPPER = 17; public static final int JDK_PREFERENCE = 18; public static final int ENV_VARIABLES = 19; public static final int PRIORITY_CLASS = 20; public static final int DOWNLOAD_URL = 21; public static final int SUPPORT_URL = 22; public static final int MUTEX_NAME = 23; public static final int INSTANCE_WINDOW_TITLE = 24; public static final int INITIAL_HEAP_SIZE = 25; public static final int INITIAL_HEAP_PERCENT = 26; public static final int MAX_HEAP_SIZE = 27; public static final int MAX_HEAP_PERCENT = 28; public static final int STARTUP_ERR = 101; public static final int BUNDLED_JRE_ERR = 102; public static final int JRE_VERSION_ERR = 103; public static final int LAUNCHER_ERR = 104; public static final int INSTANCE_ALREADY_EXISTS_MSG = 105; private final StringBuffer _sb = new StringBuffer(); public String getContent() { return _sb.toString(); } public String getLine(int line) { return _sb.toString().split(""\n"")[line - 1]; } public File build(Config c) throws IOException { _sb.append(""LANGUAGE ""); _sb.append(LANG_NEUTRAL); _sb.append("", ""); _sb.append(SUBLANG_DEFAULT); _sb.append('\n'); addVersionInfo(c.getVersionInfo()); addJre(c.getJre()); addManifest(MANIFEST, c.getManifest()); addIcon(APP_ICON, c.getIcon()); addText(ERR_TITLE, c.getErrTitle()); addText(DOWNLOAD_URL, c.getDownloadUrl()); addText(SUPPORT_URL, c.getSupportUrl()); addText(CMD_LINE, c.getCmdLine()); addWindowsPath(CHDIR, c.getChdir()); addText(PRIORITY_CLASS, String.valueOf(c.getPriorityClass())); addTrue(SET_PROC_NAME, c.isCustomProcName()); addTrue(GUI_HEADER_STAYS_ALIVE, c.isStayAlive()); addSplash(c.getSplash()); addMessages(c); if (c.getSingleInstance() != null) { addText(MUTEX_NAME, c.getSingleInstance().getMutexName()); addText(INSTANCE_WINDOW_TITLE, c.getSingleInstance().getWindowTitle()); } if (c.getVariables() != null && !c.getVariables().isEmpty()) { StringBuffer vars = new StringBuffer(); append(vars, c.getVariables(), ""\t""); addText(ENV_VARIABLES, vars.toString()); } // MAIN_CLASS / JAR addTrue(WRAPPER, !c.isDontWrapJar()); if (c.getClassPath() != null) { addText(MAIN_CLASS, c.getClassPath().getMainClass()); addWindowsPath(CLASSPATH, c.getClassPath().getPathsString()); } if (c.isDontWrapJar() && c.getJar() != null) { addWindowsPath(JAR, c.getJar().getPath()); } File f = Util.createTempFile(""rc""); BufferedWriter w = new BufferedWriter(new FileWriter(f)); w.write(_sb.toString()); w.close(); return f; } private void addVersionInfo(VersionInfo v) { if (v == null) { return; } _sb.append(""1 VERSIONINFO\n""); _sb.append(""FILEVERSION ""); _sb.append(v.getFileVersion().replaceAll(""\\."", "", "")); _sb.append(""\nPRODUCTVERSION ""); _sb.append(v.getProductVersion().replaceAll(""\\."", "", "")); _sb.append(""\nFILEFLAGSMASK 0\n"" + ""FILEOS 0x40000\n"" + ""FILETYPE 1\n"" + ""{\n"" + "" BLOCK \""StringFileInfo\""\n"" + "" {\n"" + "" BLOCK \""040904E4\""\n"" + // English "" {\n""); addVerBlockValue(""CompanyName"", v.getCompanyName()); addVerBlockValue(""FileDescription"", v.getFileDescription()); addVerBlockValue(""FileVersion"", v.getTxtFileVersion()); addVerBlockValue(""InternalName"", v.getInternalName()); addVerBlockValue(""LegalCopyright"", v.getCopyright()); addVerBlockValue(""OriginalFilename"", v.getOriginalFilename()); addVerBlockValue(""ProductName"", v.getProductName()); addVerBlockValue(""ProductVersion"", v.getTxtProductVersion()); _sb.append("" }\n }\nBLOCK \""VarFileInfo\""\n{\nVALUE \""Translation\"", 0x0409, 0x04E4\n}\n}""); } private void addJre(Jre jre) { addWindowsPath(JRE_PATH, jre.getPath()); addText(JAVA_MIN_VER, jre.getMinVersion()); addText(JAVA_MAX_VER, jre.getMaxVersion()); addText(JDK_PREFERENCE, String.valueOf(jre.getJdkPreferenceIndex())); addInteger(INITIAL_HEAP_SIZE, jre.getInitialHeapSize()); addInteger(INITIAL_HEAP_PERCENT, jre.getInitialHeapPercent()); addInteger(MAX_HEAP_SIZE, jre.getMaxHeapSize()); addInteger(MAX_HEAP_PERCENT, jre.getMaxHeapPercent()); StringBuffer options = new StringBuffer(); if (jre.getOptions() != null && !jre.getOptions().isEmpty()) { addSpace(options); append(options, jre.getOptions(), "" ""); } addText(JVM_OPTIONS, options.toString()); } private void addSplash(Splash splash) { if (splash == null) { return; } addTrue(SHOW_SPLASH, true); addTrue(SPLASH_WAITS_FOR_WINDOW, splash.getWaitForWindow()); addText(SPLASH_TIMEOUT, String.valueOf(splash.getTimeout())); addTrue(SPLASH_TIMEOUT_ERR, splash.isTimeoutErr()); addBitmap(SPLASH_BITMAP, splash.getFile()); } private void addMessages(Config c) { Msg msg = c.getMessages(); if (msg == null) { msg = new Msg(); } addText(STARTUP_ERR, msg.getStartupErr()); addText(BUNDLED_JRE_ERR, msg.getBundledJreErr()); addText(JRE_VERSION_ERR, msg.getJreVersionErr()); addText(LAUNCHER_ERR, msg.getLauncherErr()); if (c.getSingleInstance() != null) { addText(INSTANCE_ALREADY_EXISTS_MSG, msg.getInstanceAlreadyExistsMsg()); } } private void append(StringBuffer sb, List list, String separator) { for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i < list.size() - 1) { sb.append(separator); } } } private void addText(int id, String text) { if (text == null || text.equals("""")) { return; } _sb.append(id); _sb.append("" RCDATA BEGIN \""""); _sb.append(escape(text)); _sb.append(""\\0\"" END\n""); } private void addTrue(int id, boolean value) { if (value) { addText(id, ""true""); } } private void addInteger(int id, Integer value) { if (value != null) { addText(id, value.toString()); } } /** * Stores path in Windows format with '\' separators. */ private void addWindowsPath(int id, String path) { if (path == null || path.equals("""")) { return; } _sb.append(id); _sb.append("" RCDATA BEGIN \""""); _sb.append(path.replaceAll(""\\\\"", ""\\\\\\\\"") .replaceAll(""/"", ""\\\\\\\\"")); _sb.append(""\\0\"" END\n""); } private void addManifest(int id, File manifest) { if (manifest == null || manifest.getPath().equals("""")) { return; } _sb.append(id); _sb.append("" 24 \""""); _sb.append(getPath(Util.getAbsoluteFile( ConfigPersister.getInstance().getConfigPath(), manifest))); _sb.append(""\""\n""); } private void addIcon(int id, File icon) { if (icon == null || icon.getPath().equals("""")) { return; } _sb.append(id); _sb.append("" ICON DISCARDABLE \""""); _sb.append(getPath(Util.getAbsoluteFile( ConfigPersister.getInstance().getConfigPath(), icon))); _sb.append(""\""\n""); } private void addBitmap(int id, File bitmap) { if (bitmap == null) { return; } _sb.append(id); _sb.append("" BITMAP \""""); _sb.append(getPath(Util.getAbsoluteFile( ConfigPersister.getInstance().getConfigPath(), bitmap))); _sb.append(""\""\n""); } private String getPath(File f) { return f.getPath().replaceAll(""\\\\"", ""\\\\\\\\""); } private void addSpace(StringBuffer sb) { int len = sb.length(); if (len-- > 0 && sb.charAt(len) != ' ') { sb.append(' '); } } private void addVerBlockValue(String key, String value) { _sb.append("" VALUE \""""); _sb.append(key); _sb.append(""\"", \""""); if (value != null) { _sb.append(escape(value)); } _sb.append(""\""\n""); } private String escape(String text) { return text.replaceAll(""\"""", ""\""\""""); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/ExecException.java",".java","2274","67","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 14, 2005 */ package net.sf.launch4j; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class ExecException extends Exception { private final int _errLine; public ExecException(Throwable t, int errLine) { super(t); _errLine = errLine; } public ExecException(Throwable t) { this(t, -1); } public ExecException(String msg, int errLine) { super(msg); _errLine = errLine; } public ExecException(String msg) { this(msg, -1); } public int getErrLine() { return _errLine; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/ClassPathFormImpl.java",".java","8051","223","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.formimpl; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; import java.util.jar.Attributes; import java.util.jar.JarFile; import javax.swing.DefaultListModel; import javax.swing.JFileChooser; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import net.sf.launch4j.FileChooserFilter; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.binding.Validator; import net.sf.launch4j.config.ClassPath; import net.sf.launch4j.form.ClassPathForm; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class ClassPathFormImpl extends ClassPathForm { private final JFileChooser _fileChooser; private final FileChooserFilter _filter = new FileChooserFilter(""Executable jar"", "".jar""); public ClassPathFormImpl(Bindings bindings, JFileChooser fc) { bindings.addOptComponent(""classPath"", ClassPath.class, _classpathCheck) .add(""classPath.mainClass"", _mainclassField) .add(""classPath.paths"", _classpathList); _fileChooser = fc; ClasspathCheckListener cpl = new ClasspathCheckListener(); _classpathCheck.addChangeListener(cpl); cpl.stateChanged(null); _classpathList.setModel(new DefaultListModel()); _classpathList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); _classpathList.addListSelectionListener(new ClasspathSelectionListener()); _newClasspathButton.addActionListener(new NewClasspathListener()); _acceptClasspathButton.addActionListener( new AcceptClasspathListener(_classpathField)); _removeClasspathButton.addActionListener(new RemoveClasspathListener()); _importClasspathButton.addActionListener(new ImportClasspathListener()); _classpathUpButton.addActionListener(new MoveUpListener()); _classpathDownButton.addActionListener(new MoveDownListener()); } private class ClasspathCheckListener implements ChangeListener { public void stateChanged(ChangeEvent e) { boolean on = _classpathCheck.isSelected(); _importClasspathButton.setEnabled(on); _classpathUpButton.setEnabled(on); _classpathDownButton.setEnabled(on); _classpathField.setEnabled(on); _newClasspathButton.setEnabled(on); _acceptClasspathButton.setEnabled(on); _removeClasspathButton.setEnabled(on); } } private class NewClasspathListener implements ActionListener { public void actionPerformed(ActionEvent e) { _classpathList.clearSelection(); _classpathField.setText(""""); _classpathField.requestFocusInWindow(); } } private class AcceptClasspathListener extends AbstractAcceptListener { public AcceptClasspathListener(JTextField f) { super(f, true); } public void actionPerformed(ActionEvent e) { String cp = getText(); if (Validator.isEmpty(cp)) { signalViolation(Messages.getString(""specifyClassPath"")); return; } DefaultListModel model = (DefaultListModel) _classpathList.getModel(); if (_classpathList.isSelectionEmpty()) { model.addElement(cp); clear(); } else { model.setElementAt(cp, _classpathList.getSelectedIndex()); } } } private class ClasspathSelectionListener implements ListSelectionListener { public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting()) { return; } if (_classpathList.isSelectionEmpty()) { _classpathField.setText(""""); } else { _classpathField.setText((String) _classpathList.getSelectedValue()); } _classpathField.requestFocusInWindow(); } } private class RemoveClasspathListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (_classpathList.isSelectionEmpty() || !MainFrame.getInstance().confirm( Messages.getString(""confirmClassPathRemoval""))) { return; } DefaultListModel model = (DefaultListModel) _classpathList.getModel(); while (!_classpathList.isSelectionEmpty()) { model.remove(_classpathList.getSelectedIndex()); } } } private class MoveUpListener implements ActionListener { public void actionPerformed(ActionEvent e) { int x = _classpathList.getSelectedIndex(); if (x < 1) { return; } DefaultListModel model = (DefaultListModel) _classpathList.getModel(); Object o = model.get(x - 1); model.set(x - 1, model.get(x)); model.set(x, o); _classpathList.setSelectedIndex(x - 1); } } private class MoveDownListener implements ActionListener { public void actionPerformed(ActionEvent e) { DefaultListModel model = (DefaultListModel) _classpathList.getModel(); int x = _classpathList.getSelectedIndex(); if (x == -1 || x >= model.getSize() - 1) { return; } Object o = model.get(x + 1); model.set(x + 1, model.get(x)); model.set(x, o); _classpathList.setSelectedIndex(x + 1); } } private class ImportClasspathListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { _fileChooser.setFileFilter(_filter); _fileChooser.setSelectedFile(new File("""")); if (_fileChooser.showOpenDialog(MainFrame.getInstance()) == JFileChooser.APPROVE_OPTION) { JarFile jar = new JarFile(_fileChooser.getSelectedFile()); if (jar.getManifest() == null) { jar.close(); MainFrame.getInstance().info(Messages.getString(""noManifest"")); return; } Attributes attr = jar.getManifest().getMainAttributes(); String mainClass = (String) attr.getValue(""Main-Class""); String classPath = (String) attr.getValue(""Class-Path""); jar.close(); _mainclassField.setText(mainClass != null ? mainClass : """"); DefaultListModel model = new DefaultListModel(); if (classPath != null) { String[] paths = classPath.split("" ""); for (int i = 0; i < paths.length; i++) { model.addElement(paths[i]); } } _classpathList.setModel(model); } } catch (IOException ex) { MainFrame.getInstance().warn(ex.getMessage()); } } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/SplashFormImpl.java",".java","2594","62","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.formimpl; import javax.swing.JFileChooser; import net.sf.launch4j.FileChooserFilter; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.config.Splash; import net.sf.launch4j.form.SplashForm; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class SplashFormImpl extends SplashForm { public SplashFormImpl(Bindings bindings, JFileChooser fc) { bindings.addOptComponent(""splash"", Splash.class, _splashCheck) .add(""splash.file"", _splashFileField) .add(""splash.waitForWindow"", _waitForWindowCheck, true) .add(""splash.timeout"", _timeoutField, ""60"") .add(""splash.timeoutErr"", _timeoutErrCheck, true); _splashFileButton.addActionListener(new BrowseActionListener(false, fc, new FileChooserFilter(""Bitmap files (.bmp)"", "".bmp""), _splashFileField)); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/SingleInstanceFormImpl.java",".java","2267","55","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /** * Created on 2007-09-22 */ package net.sf.launch4j.formimpl; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.config.SingleInstance; import net.sf.launch4j.form.SingleInstanceForm; /** * @author Copyright (C) 2007 Grzegorz Kowal */ public class SingleInstanceFormImpl extends SingleInstanceForm { public SingleInstanceFormImpl(Bindings bindings) { bindings.addOptComponent(""singleInstance"", SingleInstance.class, _singleInstanceCheck) .add(""singleInstance.mutexName"", _mutexNameField) .add(""singleInstance.windowTitle"", _windowTitleField); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/MainFrame.java",".java","11290","359","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on 2005-05-09 */ package net.sf.launch4j.formimpl; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JToolBar; import javax.swing.UIManager; import com.jgoodies.looks.Options; import com.jgoodies.looks.plastic.PlasticXPLookAndFeel; import foxtrot.Task; import foxtrot.Worker; import net.sf.launch4j.Builder; import net.sf.launch4j.BuilderException; import net.sf.launch4j.ExecException; import net.sf.launch4j.FileChooserFilter; import net.sf.launch4j.Log; import net.sf.launch4j.Main; import net.sf.launch4j.Util; import net.sf.launch4j.binding.Binding; import net.sf.launch4j.binding.BindingException; import net.sf.launch4j.binding.InvariantViolationException; import net.sf.launch4j.config.Config; import net.sf.launch4j.config.ConfigPersister; import net.sf.launch4j.config.ConfigPersisterException; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class MainFrame extends JFrame { private static MainFrame _instance; private final JToolBar _toolBar; private final JButton _runButton; private final ConfigFormImpl _configForm; private final JFileChooser _fileChooser = new FileChooser(MainFrame.class); private File _outfile; private boolean _saved = false; public static void createInstance() { try { Toolkit.getDefaultToolkit().setDynamicLayout(true); System.setProperty(""sun.awt.noerasebackground"",""true""); // JGoodies Options.setDefaultIconSize(new Dimension(16, 16)); // menu icons Options.setUseNarrowButtons(false); Options.setPopupDropShadowEnabled(true); UIManager.setLookAndFeel(new PlasticXPLookAndFeel()); _instance = new MainFrame(); } catch (Exception e) { System.err.println(e); } } public static MainFrame getInstance() { return _instance; } public MainFrame() { showConfigName(null); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); addWindowListener(new MainFrameListener()); setGlassPane(new GlassPane(this)); _fileChooser.setFileFilter(new FileChooserFilter( Messages.getString(""MainFrame.config.files""), new String[] {"".xml"", "".cfg""})); _toolBar = new JToolBar(); _toolBar.setFloatable(false); _toolBar.setRollover(true); addButton(""images/new.png"", Messages.getString(""MainFrame.new.config""), new NewActionListener()); addButton(""images/open.png"", Messages.getString(""MainFrame.open.config""), new OpenActionListener()); addButton(""images/save.png"", Messages.getString(""MainFrame.save.config""), new SaveActionListener()); _toolBar.addSeparator(); addButton(""images/build.png"", Messages.getString(""MainFrame.build.wrapper""), new BuildActionListener()); _runButton = addButton(""images/run.png"", Messages.getString(""MainFrame.test.wrapper""), new RunActionListener()); setRunEnabled(false); _toolBar.addSeparator(); addButton(""images/info.png"", Messages.getString(""MainFrame.about.launch4j""), new AboutActionListener()); _configForm = new ConfigFormImpl(); getContentPane().setLayout(new BorderLayout()); getContentPane().add(_toolBar, BorderLayout.NORTH); getContentPane().add(_configForm, BorderLayout.CENTER); pack(); Dimension scr = Toolkit.getDefaultToolkit().getScreenSize(); Dimension fr = getSize(); fr.width += 25; fr.height += 100; setBounds((scr.width - fr.width) / 2, (scr.height - fr.height) / 2, fr.width, fr.height); setVisible(true); } private JButton addButton(String iconPath, String tooltip, ActionListener l) { ImageIcon icon = new ImageIcon(MainFrame.class.getClassLoader() .getResource(iconPath)); JButton b = new JButton(icon); b.setToolTipText(tooltip); b.addActionListener(l); _toolBar.add(b); return b; } public void info(String text) { JOptionPane.showMessageDialog(this, text, Main.getName(), JOptionPane.INFORMATION_MESSAGE); } public void warn(String text) { JOptionPane.showMessageDialog(this, text, Main.getName(), JOptionPane.WARNING_MESSAGE); } public void warn(InvariantViolationException e) { Binding b = e.getBinding(); if (b != null) { b.markInvalid(); } warn(e.getMessage()); if (b != null) { e.getBinding().markValid(); } } public boolean confirm(String text) { return JOptionPane.showConfirmDialog(MainFrame.this, text, Messages.getString(""MainFrame.confirm""), JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION; } private boolean isModified() { return (!_configForm.isModified()) || confirm(Messages.getString(""MainFrame.discard.changes"")); } private boolean save() { // XXX try { _configForm.get(ConfigPersister.getInstance().getConfig()); if (_fileChooser.showSaveDialog(MainFrame.this) == JOptionPane.YES_OPTION) { File f = _fileChooser.getSelectedFile(); if (!f.getPath().endsWith("".xml"")) { f = new File(f.getPath() + "".xml""); } ConfigPersister.getInstance().save(f); _saved = true; showConfigName(f); return true; } return false; } catch (InvariantViolationException ex) { warn(ex); return false; } catch (BindingException ex) { warn(ex.getMessage()); return false; } catch (ConfigPersisterException ex) { warn(ex.getMessage()); return false; } } private void showConfigName(File config) { setTitle(Main.getName() + "" - "" + (config != null ? config.getName() : Messages.getString(""MainFrame.untitled""))); } private void setRunEnabled(boolean enabled) { if (!enabled) { _outfile = null; } _runButton.setEnabled(enabled); } private void clearConfig() { ConfigPersister.getInstance().createBlank(); _configForm.clear(ConfigPersister.getInstance().getConfig()); } private class MainFrameListener extends WindowAdapter { public void windowOpened(WindowEvent e) { clearConfig(); } public void windowClosing(WindowEvent e) { if (isModified()) { System.exit(0); } } } private class NewActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (isModified()) { clearConfig(); } _saved = false; showConfigName(null); setRunEnabled(false); } } private class OpenActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { if (isModified() && _fileChooser.showOpenDialog(MainFrame.this) == JOptionPane.YES_OPTION) { final File f = _fileChooser.getSelectedFile(); if (f.getPath().endsWith("".xml"")) { ConfigPersister.getInstance().load(f); _saved = true; } else { ConfigPersister.getInstance().loadVersion1(f); _saved = false; } _configForm.put(ConfigPersister.getInstance().getConfig()); showConfigName(f); setRunEnabled(false); } } catch (ConfigPersisterException ex) { warn(ex.getMessage()); } catch (BindingException ex) { warn(ex.getMessage()); } } } private class SaveActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { save(); } } private class BuildActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { final Log log = Log.getSwingLog(_configForm.getLogTextArea()); try { if ((!_saved || _configForm.isModified()) && !save()) { return; } log.clear(); ConfigPersister.getInstance().getConfig().checkInvariants(); Builder b = new Builder(log); _outfile = b.build(); setRunEnabled(ConfigPersister.getInstance().getConfig() .getHeaderType() == Config.GUI_HEADER // TODO fix console app test && (Util.WINDOWS_OS || !ConfigPersister.getInstance() .getConfig().isDontWrapJar())); } catch (InvariantViolationException ex) { setRunEnabled(false); ex.setBinding(_configForm.getBinding(ex.getProperty())); warn(ex); } catch (BuilderException ex) { setRunEnabled(false); log.append(ex.getMessage()); } } } private class RunActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { try { getGlassPane().setVisible(true); Worker.post(new Task() { public Object run() throws ExecException { Log log = Log.getSwingLog(_configForm.getLogTextArea()); log.clear(); String path = _outfile.getPath(); if (Util.WINDOWS_OS) { log.append(Messages.getString(""MainFrame.executing"") + path); Util.exec(new String[] { path }, log); } else { log.append(Messages.getString(""MainFrame.jar.integrity.test"") + path); Util.exec(new String[] { ""java"", ""-jar"", path }, log); } return null; } }); } catch (Exception ex) { // XXX errors logged by exec } finally { getGlassPane().setVisible(false); } }; } private class AboutActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { info(Main.getDescription()); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/FileChooser.java",".java","2476","66","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Jul 19, 2006 */ package net.sf.launch4j.formimpl; import java.io.File; import java.util.prefs.Preferences; import javax.swing.JFileChooser; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class FileChooser extends JFileChooser { private final Preferences _prefs; private final String _key; public FileChooser(Class clazz) { _prefs = Preferences.userNodeForPackage(clazz); _key = ""currentDir-"" + clazz.getName().substring(clazz.getName().lastIndexOf('.') + 1); String path = _prefs.get(_key, null); if (path != null) { setCurrentDirectory(new File(path)); } } public void approveSelection() { _prefs.put(_key, getCurrentDirectory().getPath()); super.approveSelection(); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/AbstractAcceptListener.java",".java","2630","76","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.formimpl; import java.awt.Color; import java.awt.event.ActionListener; import javax.swing.JTextField; import net.sf.launch4j.binding.Binding; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public abstract class AbstractAcceptListener implements ActionListener { final JTextField _field; public AbstractAcceptListener(JTextField f, boolean listen) { _field = f; if (listen) { _field.addActionListener(this); } } protected String getText() { return _field.getText(); } protected void clear() { _field.setText(""""); _field.requestFocusInWindow(); } protected void signalViolation(String msg) { final Color bg = _field.getBackground(); _field.setBackground(Binding.INVALID_COLOR); MainFrame.getInstance().warn(msg); _field.setBackground(bg); _field.requestFocusInWindow(); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/Messages.java",".java","2247","56","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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 net.sf.launch4j.formimpl; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = ""net.sf.launch4j.formimpl.messages""; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/ConfigFormImpl.java",".java","3748","101","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 10, 2005 */ package net.sf.launch4j.formimpl; import javax.swing.BorderFactory; import javax.swing.JFileChooser; import javax.swing.JTextArea; import net.sf.launch4j.binding.Binding; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.binding.IValidatable; import net.sf.launch4j.form.ConfigForm; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class ConfigFormImpl extends ConfigForm { private final Bindings _bindings = new Bindings(); private final JFileChooser _fileChooser = new FileChooser(ConfigFormImpl.class); public ConfigFormImpl() { _tab.setBorder(BorderFactory.createMatteBorder(0, -1, -1, -1, getBackground())); _tab.addTab(Messages.getString(""tab.basic""), new BasicFormImpl(_bindings, _fileChooser)); _tab.addTab(Messages.getString(""tab.classpath""), new ClassPathFormImpl(_bindings, _fileChooser)); _tab.addTab(Messages.getString(""tab.header""), new HeaderFormImpl(_bindings)); _tab.addTab(Messages.getString(""tab.singleInstance""), new SingleInstanceFormImpl(_bindings)); _tab.addTab(Messages.getString(""tab.jre""), new JreFormImpl(_bindings, _fileChooser)); _tab.addTab(Messages.getString(""tab.envVars""), new EnvironmentVarsFormImpl(_bindings)); _tab.addTab(Messages.getString(""tab.splash""), new SplashFormImpl(_bindings, _fileChooser)); _tab.addTab(Messages.getString(""tab.version""), new VersionInfoFormImpl(_bindings, _fileChooser)); _tab.addTab(Messages.getString(""tab.messages""), new MessagesFormImpl(_bindings)); } public void clear(IValidatable bean) { _bindings.clear(bean); } public void put(IValidatable bean) { _bindings.put(bean); } public void get(IValidatable bean) { _bindings.get(bean); } public boolean isModified() { return _bindings.isModified(); } public JTextArea getLogTextArea() { return _logTextArea; } public Binding getBinding(String property) { return _bindings.getBinding(property); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/HeaderFormImpl.java",".java","4009","103","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.formimpl; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JRadioButton; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import net.sf.launch4j.binding.Binding; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.config.Config; import net.sf.launch4j.config.ConfigPersister; import net.sf.launch4j.form.HeaderForm; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class HeaderFormImpl extends HeaderForm { private final Bindings _bindings; public HeaderFormImpl(Bindings bindings) { _bindings = bindings; _bindings.add(""headerTypeIndex"", new JRadioButton[] { _guiHeaderRadio, _consoleHeaderRadio }) .add(""headerObjects"", ""customHeaderObjects"", _headerObjectsCheck, _headerObjectsTextArea) .add(""libs"", ""customLibs"", _libsCheck, _libsTextArea); _guiHeaderRadio.addChangeListener(new HeaderTypeChangeListener()); _headerObjectsCheck.addActionListener(new HeaderObjectsActionListener()); _libsCheck.addActionListener(new LibsActionListener()); } private class HeaderTypeChangeListener implements ChangeListener { public void stateChanged(ChangeEvent e) { Config c = ConfigPersister.getInstance().getConfig(); c.setHeaderType(_guiHeaderRadio.isSelected() ? Config.GUI_HEADER : Config.CONSOLE_HEADER); if (!_headerObjectsCheck.isSelected()) { Binding b = _bindings.getBinding(""headerObjects""); b.put(c); } } } private class HeaderObjectsActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (!_headerObjectsCheck.isSelected()) { ConfigPersister.getInstance().getConfig().setHeaderObjects(null); Binding b = _bindings.getBinding(""headerObjects""); b.put(ConfigPersister.getInstance().getConfig()); } } } private class LibsActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (!_libsCheck.isSelected()) { ConfigPersister.getInstance().getConfig().setLibs(null); Binding b = _bindings.getBinding(""libs""); b.put(ConfigPersister.getInstance().getConfig()); } } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/EnvironmentVarsFormImpl.java",".java","2113","51","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Jun 10, 2006 */ package net.sf.launch4j.formimpl; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.form.EnvironmentVarsForm; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class EnvironmentVarsFormImpl extends EnvironmentVarsForm { public EnvironmentVarsFormImpl(Bindings bindings) { bindings.add(""variables"", _envVarsTextArea); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/MessagesFormImpl.java",".java","2598","59","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Oct 7, 2006 */ package net.sf.launch4j.formimpl; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.config.Msg; import net.sf.launch4j.form.MessagesForm; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class MessagesFormImpl extends MessagesForm { public MessagesFormImpl(Bindings bindings) { Msg m = new Msg(); bindings.addOptComponent(""messages"", Msg.class, _messagesCheck) .add(""messages.startupErr"", _startupErrTextArea, m.getStartupErr()) .add(""messages.bundledJreErr"", _bundledJreErrTextArea, m.getBundledJreErr()) .add(""messages.jreVersionErr"", _jreVersionErrTextArea, m.getJreVersionErr()) .add(""messages.launcherErr"", _launcherErrTextArea, m.getLauncherErr()) .add(""messages.instanceAlreadyExistsMsg"", _instanceAlreadyExistsMsgTextArea, m.getInstanceAlreadyExistsMsg()); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/JreFormImpl.java",".java","6056","167","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.formimpl; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.DefaultComboBoxModel; import javax.swing.JFileChooser; import javax.swing.JTextField; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.binding.Validator; import net.sf.launch4j.form.JreForm; import net.sf.launch4j.config.Jre; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class JreFormImpl extends JreForm { public JreFormImpl(Bindings bindings, JFileChooser fc) { _jdkPreferenceCombo.setModel(new DefaultComboBoxModel(new String[] { Messages.getString(""jdkPreference.jre.only""), Messages.getString(""jdkPreference.prefer.jre""), Messages.getString(""jdkPreference.prefer.jdk""), Messages.getString(""jdkPreference.jdk.only"")})); bindings.add(""jre.path"", _jrePathField) .add(""jre.minVersion"", _jreMinField) .add(""jre.maxVersion"", _jreMaxField) .add(""jre.jdkPreferenceIndex"", _jdkPreferenceCombo, Jre.DEFAULT_JDK_PREFERENCE_INDEX) .add(""jre.initialHeapSize"", _initialHeapSizeField) .add(""jre.initialHeapPercent"", _initialHeapPercentField) .add(""jre.maxHeapSize"", _maxHeapSizeField) .add(""jre.maxHeapPercent"", _maxHeapPercentField) .add(""jre.options"", _jvmOptionsTextArea); _varCombo.setModel(new DefaultComboBoxModel(new String[] { ""EXEDIR"", ""EXEFILE"", ""PWD"", ""OLDPWD"", ""HKEY_CLASSES_ROOT"", ""HKEY_CURRENT_USER"", ""HKEY_LOCAL_MACHINE"", ""HKEY_USERS"", ""HKEY_CURRENT_CONFIG"" })); _varCombo.addActionListener(new VarComboActionListener()); _varCombo.setSelectedIndex(0); _propertyButton.addActionListener(new PropertyActionListener()); _optionButton.addActionListener(new OptionActionListener()); _envPropertyButton.addActionListener(new EnvPropertyActionListener(_envVarField)); _envOptionButton.addActionListener(new EnvOptionActionListener(_envVarField)); } private class VarComboActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { _optionButton.setEnabled(((String) _varCombo.getSelectedItem()) .startsWith(""HKEY_"")); } } private class PropertyActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { final int pos = _jvmOptionsTextArea.getCaretPosition(); final String var = (String) _varCombo.getSelectedItem(); if (var.startsWith(""HKEY_"")) { _jvmOptionsTextArea.insert(""-Dreg.key=\""%"" + var + ""\\\\...%\""\n"", pos); } else { _jvmOptionsTextArea.insert(""-Dlaunch4j."" + var.toLowerCase() + ""=\""%"" + var + ""%\""\n"", pos); } } } private class OptionActionListener implements ActionListener { public void actionPerformed(ActionEvent e) { final int pos = _jvmOptionsTextArea.getCaretPosition(); final String var = (String) _varCombo.getSelectedItem(); if (var.startsWith(""HKEY_"")) { _jvmOptionsTextArea.insert(""%"" + var + ""\\\\...%\n"", pos); } else { _jvmOptionsTextArea.insert(""%"" + var + ""%\n"", pos); } } } private abstract class EnvActionListener extends AbstractAcceptListener { public EnvActionListener(JTextField f, boolean listen) { super(f, listen); } public void actionPerformed(ActionEvent e) { final int pos = _jvmOptionsTextArea.getCaretPosition(); final String var = getText() .replaceAll(""\"""", """") .replaceAll(""%"", """"); if (Validator.isEmpty(var)) { signalViolation(Messages.getString(""specifyVar"")); return; } add(var, pos); clear(); } protected abstract void add(String var, int pos); } private class EnvPropertyActionListener extends EnvActionListener { public EnvPropertyActionListener(JTextField f) { super(f, true); } protected void add(String var, int pos) { final String prop = var .replaceAll("" "", ""."") .replaceAll(""_"", ""."") .toLowerCase(); _jvmOptionsTextArea.insert(""-Denv."" + prop + ""=\""%"" + var + ""%\""\n"", pos); } } private class EnvOptionActionListener extends EnvActionListener { public EnvOptionActionListener(JTextField f) { super(f, false); } protected void add(String var, int pos) { _jvmOptionsTextArea.insert(""%"" + var + ""%\n"", pos); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/BasicFormImpl.java",".java","4194","102","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.formimpl; import javax.swing.JFileChooser; import javax.swing.JRadioButton; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import net.sf.launch4j.FileChooserFilter; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.config.Config; import net.sf.launch4j.form.BasicForm; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class BasicFormImpl extends BasicForm { public BasicFormImpl(Bindings bindings, JFileChooser fc) { bindings.add(""outfile"", _outfileField) .add(""dontWrapJar"", _dontWrapJarCheck) .add(""jar"", _jarField) .add(""manifest"", _manifestField) .add(""icon"", _iconField) .add(""cmdLine"", _cmdLineField) .add(""errTitle"", _errorTitleField) .add(""downloadUrl"", _downloadUrlField, Config.DOWNLOAD_URL) .add(""supportUrl"", _supportUrlField) .add(""chdir"", _chdirField) .add(""priorityIndex"", new JRadioButton[] { _normalPriorityRadio, _idlePriorityRadio, _highPriorityRadio }) .add(""customProcName"", _customProcNameCheck) .add(""stayAlive"", _stayAliveCheck); _dontWrapJarCheck.addChangeListener(new DontWrapJarChangeListener()); _outfileButton.addActionListener(new BrowseActionListener(true, fc, new FileChooserFilter(""Windows executables (.exe)"", "".exe""), _outfileField)); _jarButton.addActionListener(new BrowseActionListener(false, fc, new FileChooserFilter(""Jar files"", "".jar""), _jarField)); _manifestButton.addActionListener(new BrowseActionListener(false, fc, new FileChooserFilter(""Manifest files (.manifest)"", "".manifest""), _manifestField)); _iconButton.addActionListener(new BrowseActionListener(false, fc, new FileChooserFilter(""Icon files (.ico)"", "".ico""), _iconField)); } private class DontWrapJarChangeListener implements ChangeListener { public void stateChanged(ChangeEvent e) { boolean dontWrap = _dontWrapJarCheck.isSelected(); if (dontWrap) { _jarLabel.setIcon(loadImage(""images/asterix-o.gif"")); _jarLabel.setText(Messages.getString(""jarPath"")); _jarField.setToolTipText(Messages.getString(""jarPathTip"")); } else { _jarLabel.setIcon(loadImage(""images/asterix.gif"")); _jarLabel.setText(Messages.getString(""jar"")); _jarField.setToolTipText(Messages.getString(""jarTip"")); } _jarButton.setEnabled(!dontWrap); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/BrowseActionListener.java",".java","2980","80","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.formimpl; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JTextField; import net.sf.launch4j.FileChooserFilter; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class BrowseActionListener implements ActionListener { private final boolean _save; private final JFileChooser _fileChooser; private final FileChooserFilter _filter; private final JTextField _field; public BrowseActionListener(boolean save, JFileChooser fileChooser, FileChooserFilter filter, JTextField field) { _save = save; _fileChooser = fileChooser; _filter = filter; _field = field; } public void actionPerformed(ActionEvent e) { if (!_field.isEnabled()) { return; } _fileChooser.setFileFilter(_filter); _fileChooser.setSelectedFile(new File("""")); int result = _save ? _fileChooser.showSaveDialog(MainFrame.getInstance()) : _fileChooser.showOpenDialog(MainFrame.getInstance()); if (result == JFileChooser.APPROVE_OPTION) { _field.setText(_fileChooser.getSelectedFile().getPath()); } _fileChooser.removeChoosableFileFilter(_filter); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/VersionInfoFormImpl.java",".java","2827","64","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.formimpl; import javax.swing.JFileChooser; import net.sf.launch4j.binding.Bindings; import net.sf.launch4j.config.VersionInfo; import net.sf.launch4j.form.VersionInfoForm; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class VersionInfoFormImpl extends VersionInfoForm { public VersionInfoFormImpl(Bindings bindings, JFileChooser fc) { bindings.addOptComponent(""versionInfo"", VersionInfo.class, _versionInfoCheck) .add(""versionInfo.fileVersion"", _fileVersionField) .add(""versionInfo.productVersion"", _productVersionField) .add(""versionInfo.fileDescription"", _fileDescriptionField) .add(""versionInfo.internalName"", _internalNameField) .add(""versionInfo.originalFilename"", _originalFilenameField) .add(""versionInfo.productName"", _productNameField) .add(""versionInfo.txtFileVersion"", _txtFileVersionField) .add(""versionInfo.txtProductVersion"", _txtProductVersionField) .add(""versionInfo.companyName"", _companyNameField) .add(""versionInfo.copyright"", _copyrightField); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/formimpl/GlassPane.java",".java","1920","68","package net.sf.launch4j.formimpl; import java.awt.AWTEvent; import java.awt.Component; import java.awt.Cursor; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.AWTEventListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import javax.swing.JComponent; import javax.swing.SwingUtilities; /** * This is the glass pane class that intercepts screen interactions during * system busy states. * * Based on JavaWorld article by Yexin Chen. */ public class GlassPane extends JComponent implements AWTEventListener { private final Window _window; public GlassPane(Window w) { _window = w; addMouseListener(new MouseAdapter() {}); addKeyListener(new KeyAdapter() {}); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); } /** * Receives all key events in the AWT and processes the ones that originated * from the current window with the glass pane. * * @param event * the AWTEvent that was fired */ public void eventDispatched(AWTEvent event) { Object source = event.getSource(); if (event instanceof KeyEvent && source instanceof Component) { /* * If the event originated from the window w/glass pane, * consume the event. */ if ((SwingUtilities.windowForComponent((Component) source) == _window)) { ((KeyEvent) event).consume(); } } } /** * Sets the glass pane as visible or invisible. The mouse cursor will be set * accordingly. */ public void setVisible(boolean visible) { if (visible) { // Start receiving all events and consume them if necessary Toolkit.getDefaultToolkit().addAWTEventListener(this, AWTEvent.KEY_EVENT_MASK); } else { // Stop receiving all events Toolkit.getDefaultToolkit().removeAWTEventListener(this); } super.setVisible(visible); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/ant/AntConfig.java",".java","4155","130","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 24, 2005 */ package net.sf.launch4j.ant; import java.io.File; import java.util.ArrayList; import java.util.List; import org.apache.tools.ant.BuildException; import net.sf.launch4j.config.Config; import net.sf.launch4j.config.Msg; import net.sf.launch4j.config.SingleInstance; import net.sf.launch4j.config.Splash; import net.sf.launch4j.config.VersionInfo; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class AntConfig extends Config { private final List wrappedHeaderObjects = new ArrayList(); private final List wrappedLibs = new ArrayList(); private final List wrappedVariables = new ArrayList(); public void setJarPath(String path) { setJar(new File(path)); } public void addObj(StringWrapper obj) { wrappedHeaderObjects.add(obj); } public void addLib(StringWrapper lib) { wrappedLibs.add(lib); } public void addVar(StringWrapper var) { wrappedVariables.add(var); } // __________________________________________________________________________________ public void addSingleInstance(SingleInstance singleInstance) { checkNull(getSingleInstance(), ""singleInstance""); setSingleInstance(singleInstance); } public void addClassPath(AntClassPath classPath) { checkNull(getClassPath(), ""classPath""); setClassPath(classPath); } public void addJre(AntJre jre) { checkNull(getJre(), ""jre""); setJre(jre); } public void addSplash(Splash splash) { checkNull(getSplash(), ""splash""); setSplash(splash); } public void addVersionInfo(VersionInfo versionInfo) { checkNull(getVersionInfo(), ""versionInfo""); setVersionInfo(versionInfo); } public void addMessages(Msg messages) { checkNull(getMessages(), ""messages""); setMessages(messages); } // __________________________________________________________________________________ public void unwrap() { setHeaderObjects(StringWrapper.unwrap(wrappedHeaderObjects)); setLibs(StringWrapper.unwrap(wrappedLibs)); setVariables(StringWrapper.unwrap(wrappedVariables)); if (getClassPath() != null) { ((AntClassPath) getClassPath()).unwrap(); } if (getJre() != null) { ((AntJre) getJre()).unwrap(); } } private void checkNull(Object o, String name) { if (o != null) { throw new BuildException( Messages.getString(""AntConfig.duplicate.element"") + "": "" + name); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/ant/Launch4jTask.java",".java","5071","163","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 24, 2005 */ package net.sf.launch4j.ant; import java.io.File; import net.sf.launch4j.Builder; import net.sf.launch4j.BuilderException; import net.sf.launch4j.Log; import net.sf.launch4j.config.Config; import net.sf.launch4j.config.ConfigPersister; import net.sf.launch4j.config.ConfigPersisterException; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class Launch4jTask extends Task { private File _configFile; private AntConfig _config; // System properties private File tmpdir; // launch4j.tmpdir private File bindir; // launch4j.bindir // Override configFile settings private File jar; private File outfile; private String fileVersion; private String txtFileVersion; private String productVersion; private String txtProductVersion; public void execute() throws BuildException { try { if (tmpdir != null) { System.setProperty(""launch4j.tmpdir"", tmpdir.getPath()); } if (bindir != null) { System.setProperty(""launch4j.bindir"", bindir.getPath()); } if (_configFile != null && _config != null) { throw new BuildException( Messages.getString(""Launch4jTask.specify.config"")); } else if (_configFile != null) { ConfigPersister.getInstance().load(_configFile); Config c = ConfigPersister.getInstance().getConfig(); if (jar != null) { c.setJar(jar); } if (outfile != null) { c.setOutfile(outfile); } if (fileVersion != null) { c.getVersionInfo().setFileVersion(fileVersion); } if (txtFileVersion != null) { c.getVersionInfo().setTxtFileVersion(txtFileVersion); } if (productVersion != null) { c.getVersionInfo().setProductVersion(productVersion); } if (txtProductVersion != null) { c.getVersionInfo().setTxtProductVersion(txtProductVersion); } } else if (_config != null) { _config.unwrap(); ConfigPersister.getInstance().setAntConfig(_config, getProject().getBaseDir()); } else { throw new BuildException( Messages.getString(""Launch4jTask.specify.config"")); } final Builder b = new Builder(Log.getAntLog()); b.build(); } catch (ConfigPersisterException e) { throw new BuildException(e); } catch (BuilderException e) { throw new BuildException(e); } } public void setConfigFile(File configFile) { _configFile = configFile; } public void addConfig(AntConfig config) { _config = config; } public void setBindir(File bindir) { this.bindir = bindir; } public void setTmpdir(File tmpdir) { this.tmpdir = tmpdir; } public void setFileVersion(String fileVersion) { this.fileVersion = fileVersion; } public void setJar(File jar) { this.jar = jar; } public void setJarPath(String path) { this.jar = new File(path); } public void setOutfile(File outfile) { this.outfile = outfile; } public void setProductVersion(String productVersion) { this.productVersion = productVersion; } public void setTxtFileVersion(String txtFileVersion) { this.txtFileVersion = txtFileVersion; } public void setTxtProductVersion(String txtProductVersion) { this.txtProductVersion = txtProductVersion; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/ant/StringWrapper.java",".java","2370","68","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Jul 18, 2006 */ package net.sf.launch4j.ant; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class StringWrapper { private String text; public static List unwrap(List wrappers) { if (wrappers.isEmpty()) { return null; } List strings = new ArrayList(wrappers.size()); for (Iterator iter = wrappers.iterator(); iter.hasNext();) { strings.add(iter.next().toString()); } return strings; } public void addText(String text) { this.text = text; } public String toString() { return text; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/ant/Messages.java",".java","2237","56","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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 net.sf.launch4j.ant; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = ""net.sf.launch4j.ant.messages""; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/ant/AntClassPath.java",".java","2252","62","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Jul 19, 2006 */ package net.sf.launch4j.ant; import java.util.ArrayList; import java.util.List; import net.sf.launch4j.config.ClassPath; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class AntClassPath extends ClassPath { private final List wrappedPaths = new ArrayList(); public void setCp(String cp){ wrappedPaths.add(cp); } public void addCp(StringWrapper cp) { wrappedPaths.add(cp); } public void unwrap() { setPaths(StringWrapper.unwrap(wrappedPaths)); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/ant/AntJre.java",".java","2422","70","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Jul 18, 2006 */ package net.sf.launch4j.ant; import java.util.ArrayList; import java.util.List; import net.sf.launch4j.config.Jre; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class AntJre extends Jre { private final List wrappedOptions = new ArrayList(); public void addOpt(StringWrapper opt) { wrappedOptions.add(opt); } public void unwrap() { setOptions(StringWrapper.unwrap(wrappedOptions)); } /** * For backwards compatibility. */ public void setDontUsePrivateJres(boolean dontUse) { if (dontUse) { setJdkPreference(JDK_PREFERENCE_JRE_ONLY); } else { setJdkPreference(JDK_PREFERENCE_PREFER_JRE); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/EnvironmentVarsForm.java",".java","4211","128","package net.sf.launch4j.form; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public abstract class EnvironmentVarsForm extends JPanel { protected final JTextArea _envVarsTextArea = new JTextArea(); protected final JLabel _envVarsLabel = new JLabel(); /** * Default constructor */ public EnvironmentVarsForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE"",""CENTER:9DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _envVarsTextArea.setName(""envVarsTextArea""); JScrollPane jscrollpane1 = new JScrollPane(); jscrollpane1.setViewportView(_envVarsTextArea); jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane1,cc.xy(4,2)); _envVarsLabel.setName(""envVarsLabel""); _envVarsLabel.setText(Messages.getString(""setVariables"")); jpanel1.add(_envVarsLabel,new CellConstraints(2,2,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); addFillComponents(jpanel1,new int[]{ 1,2,3,4,5 },new int[]{ 1,2,3 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/HeaderForm.java",".java","6702","172","package net.sf.launch4j.form; import com.jeta.forms.components.separator.TitledSeparator; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; public abstract class HeaderForm extends JPanel { protected final JLabel _headerTypeLabel = new JLabel(); protected final JRadioButton _guiHeaderRadio = new JRadioButton(); protected final ButtonGroup _headerButtonGroup = new ButtonGroup(); protected final JRadioButton _consoleHeaderRadio = new JRadioButton(); protected final JTextArea _headerObjectsTextArea = new JTextArea(); protected final JTextArea _libsTextArea = new JTextArea(); protected final JCheckBox _headerObjectsCheck = new JCheckBox(); protected final JCheckBox _libsCheck = new JCheckBox(); protected final TitledSeparator _linkerOptionsSeparator = new TitledSeparator(); /** * Default constructor */ public HeaderForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:7DLU:NONE,FILL:DEFAULT:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE"",""CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,FILL:DEFAULT:GROW(0.2),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _headerTypeLabel.setName(""headerTypeLabel""); _headerTypeLabel.setText(Messages.getString(""headerType"")); jpanel1.add(_headerTypeLabel,cc.xy(2,2)); _guiHeaderRadio.setActionCommand(""GUI""); _guiHeaderRadio.setName(""guiHeaderRadio""); _guiHeaderRadio.setText(Messages.getString(""gui"")); _headerButtonGroup.add(_guiHeaderRadio); jpanel1.add(_guiHeaderRadio,cc.xy(4,2)); _consoleHeaderRadio.setActionCommand(""Console""); _consoleHeaderRadio.setName(""consoleHeaderRadio""); _consoleHeaderRadio.setText(Messages.getString(""console"")); _headerButtonGroup.add(_consoleHeaderRadio); jpanel1.add(_consoleHeaderRadio,cc.xy(6,2)); _headerObjectsTextArea.setName(""headerObjectsTextArea""); JScrollPane jscrollpane1 = new JScrollPane(); jscrollpane1.setViewportView(_headerObjectsTextArea); jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane1,cc.xywh(4,6,4,1)); _libsTextArea.setName(""libsTextArea""); JScrollPane jscrollpane2 = new JScrollPane(); jscrollpane2.setViewportView(_libsTextArea); jscrollpane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane2,cc.xywh(4,8,4,1)); _headerObjectsCheck.setActionCommand(""Object files""); _headerObjectsCheck.setName(""headerObjectsCheck""); _headerObjectsCheck.setText(Messages.getString(""objectFiles"")); jpanel1.add(_headerObjectsCheck,new CellConstraints(2,6,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); _libsCheck.setActionCommand(""w32api""); _libsCheck.setName(""libsCheck""); _libsCheck.setText(Messages.getString(""libs"")); jpanel1.add(_libsCheck,new CellConstraints(2,8,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); _linkerOptionsSeparator.setName(""linkerOptionsSeparator""); _linkerOptionsSeparator.setText(Messages.getString(""linkerOptions"")); jpanel1.add(_linkerOptionsSeparator,cc.xywh(2,4,6,1)); addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8 },new int[]{ 1,2,3,4,5,6,7,8,9 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/JreForm.java",".java","10482","267","package net.sf.launch4j.form; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; public abstract class JreForm extends JPanel { protected final JLabel _jrePathLabel = new JLabel(); protected final JLabel _jreMinLabel = new JLabel(); protected final JLabel _jreMaxLabel = new JLabel(); protected final JLabel _jvmOptionsTextLabel = new JLabel(); protected final JTextField _jrePathField = new JTextField(); protected final JTextField _jreMinField = new JTextField(); protected final JTextField _jreMaxField = new JTextField(); protected final JTextArea _jvmOptionsTextArea = new JTextArea(); protected final JLabel _initialHeapSizeLabel = new JLabel(); protected final JLabel _maxHeapSizeLabel = new JLabel(); protected final JTextField _initialHeapSizeField = new JTextField(); protected final JTextField _maxHeapSizeField = new JTextField(); protected final JComboBox _varCombo = new JComboBox(); protected final JButton _propertyButton = new JButton(); protected final JButton _optionButton = new JButton(); protected final JButton _envPropertyButton = new JButton(); protected final JButton _envOptionButton = new JButton(); protected final JTextField _envVarField = new JTextField(); protected final JTextField _maxHeapPercentField = new JTextField(); protected final JTextField _initialHeapPercentField = new JTextField(); protected final JComboBox _jdkPreferenceCombo = new JComboBox(); /** * Default constructor */ public JreForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:60DLU:NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:7DLU:NONE,FILL:60DLU:NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE"",""CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,FILL:50DLU:GROW(1.0),CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _jrePathLabel.setName(""jrePathLabel""); _jrePathLabel.setText(Messages.getString(""jrePath"")); jpanel1.add(_jrePathLabel,cc.xy(2,2)); _jreMinLabel.setName(""jreMinLabel""); _jreMinLabel.setText(Messages.getString(""jreMin"")); jpanel1.add(_jreMinLabel,cc.xy(2,4)); _jreMaxLabel.setName(""jreMaxLabel""); _jreMaxLabel.setText(Messages.getString(""jreMax"")); jpanel1.add(_jreMaxLabel,cc.xy(2,6)); _jvmOptionsTextLabel.setName(""jvmOptionsTextLabel""); _jvmOptionsTextLabel.setText(Messages.getString(""jvmOptions"")); jpanel1.add(_jvmOptionsTextLabel,new CellConstraints(2,12,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); _jrePathField.setName(""jrePathField""); _jrePathField.setToolTipText(Messages.getString(""jrePathTip"")); jpanel1.add(_jrePathField,cc.xywh(4,2,7,1)); _jreMinField.setName(""jreMinField""); jpanel1.add(_jreMinField,cc.xy(4,4)); _jreMaxField.setName(""jreMaxField""); jpanel1.add(_jreMaxField,cc.xy(4,6)); _jvmOptionsTextArea.setName(""jvmOptionsTextArea""); _jvmOptionsTextArea.setToolTipText(Messages.getString(""jvmOptionsTip"")); JScrollPane jscrollpane1 = new JScrollPane(); jscrollpane1.setViewportView(_jvmOptionsTextArea); jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane1,cc.xywh(4,12,7,1)); _initialHeapSizeLabel.setName(""initialHeapSizeLabel""); _initialHeapSizeLabel.setText(Messages.getString(""initialHeapSize"")); jpanel1.add(_initialHeapSizeLabel,cc.xy(2,8)); _maxHeapSizeLabel.setName(""maxHeapSizeLabel""); _maxHeapSizeLabel.setText(Messages.getString(""maxHeapSize"")); jpanel1.add(_maxHeapSizeLabel,cc.xy(2,10)); JLabel jlabel1 = new JLabel(); jlabel1.setText(""MB""); jpanel1.add(jlabel1,cc.xy(6,8)); JLabel jlabel2 = new JLabel(); jlabel2.setText(""MB""); jpanel1.add(jlabel2,cc.xy(6,10)); _initialHeapSizeField.setName(""initialHeapSizeField""); jpanel1.add(_initialHeapSizeField,cc.xy(4,8)); _maxHeapSizeField.setName(""maxHeapSizeField""); jpanel1.add(_maxHeapSizeField,cc.xy(4,10)); jpanel1.add(createPanel1(),cc.xywh(2,14,9,1)); _maxHeapPercentField.setName(""maxHeapPercentField""); jpanel1.add(_maxHeapPercentField,cc.xy(8,10)); _initialHeapPercentField.setName(""initialHeapPercentField""); jpanel1.add(_initialHeapPercentField,cc.xy(8,8)); _jdkPreferenceCombo.setName(""jdkPreferenceCombo""); jpanel1.add(_jdkPreferenceCombo,cc.xywh(8,4,3,1)); JLabel jlabel3 = new JLabel(); jlabel3.setText(Messages.getString(""freeMemory"")); jpanel1.add(jlabel3,cc.xy(10,8)); JLabel jlabel4 = new JLabel(); jlabel4.setText(Messages.getString(""freeMemory"")); jpanel1.add(jlabel4,cc.xy(10,10)); addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8,9,10,11 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 }); return jpanel1; } public JPanel createPanel1() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE"",""CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _varCombo.setName(""varCombo""); jpanel1.add(_varCombo,cc.xy(3,1)); _propertyButton.setActionCommand(""Add""); _propertyButton.setIcon(loadImage(""images/edit_add16.png"")); _propertyButton.setName(""propertyButton""); _propertyButton.setText(Messages.getString(""property"")); _propertyButton.setToolTipText(Messages.getString(""propertyTip"")); jpanel1.add(_propertyButton,cc.xy(5,1)); _optionButton.setActionCommand(""Add""); _optionButton.setIcon(loadImage(""images/edit_add16.png"")); _optionButton.setName(""optionButton""); _optionButton.setText(Messages.getString(""option"")); _optionButton.setToolTipText(Messages.getString(""optionTip"")); jpanel1.add(_optionButton,cc.xy(7,1)); _envPropertyButton.setActionCommand(""Add""); _envPropertyButton.setIcon(loadImage(""images/edit_add16.png"")); _envPropertyButton.setName(""envPropertyButton""); _envPropertyButton.setText(Messages.getString(""property"")); _envPropertyButton.setToolTipText(Messages.getString(""propertyTip"")); jpanel1.add(_envPropertyButton,cc.xy(5,3)); JLabel jlabel1 = new JLabel(); jlabel1.setText(Messages.getString(""varsAndRegistry"")); jpanel1.add(jlabel1,cc.xy(1,1)); JLabel jlabel2 = new JLabel(); jlabel2.setIcon(loadImage(""images/asterix.gif"")); jlabel2.setText(Messages.getString(""envVar"")); jpanel1.add(jlabel2,cc.xy(1,3)); _envOptionButton.setActionCommand(""Add""); _envOptionButton.setIcon(loadImage(""images/edit_add16.png"")); _envOptionButton.setName(""envOptionButton""); _envOptionButton.setText(Messages.getString(""option"")); _envOptionButton.setToolTipText(Messages.getString(""optionTip"")); jpanel1.add(_envOptionButton,cc.xy(7,3)); _envVarField.setName(""envVarField""); jpanel1.add(_envVarField,cc.xy(3,3)); addFillComponents(jpanel1,new int[]{ 2,4,6 },new int[]{ 2 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/Messages.java",".java","2232","56","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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 net.sf.launch4j.form; import java.util.MissingResourceException; import java.util.ResourceBundle; class Messages { private static final String BUNDLE_NAME = ""net.sf.launch4j.form.messages""; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/MessagesForm.java",".java","7472","184","package net.sf.launch4j.form; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public abstract class MessagesForm extends JPanel { protected final JTextArea _startupErrTextArea = new JTextArea(); protected final JTextArea _bundledJreErrTextArea = new JTextArea(); protected final JTextArea _jreVersionErrTextArea = new JTextArea(); protected final JTextArea _launcherErrTextArea = new JTextArea(); protected final JCheckBox _messagesCheck = new JCheckBox(); protected final JTextArea _instanceAlreadyExistsMsgTextArea = new JTextArea(); /** * Default constructor */ public MessagesForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE"",""CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _startupErrTextArea.setName(""startupErrTextArea""); JScrollPane jscrollpane1 = new JScrollPane(); jscrollpane1.setViewportView(_startupErrTextArea); jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane1,cc.xy(4,4)); _bundledJreErrTextArea.setName(""bundledJreErrTextArea""); JScrollPane jscrollpane2 = new JScrollPane(); jscrollpane2.setViewportView(_bundledJreErrTextArea); jscrollpane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane2.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane2,cc.xy(4,6)); _jreVersionErrTextArea.setName(""jreVersionErrTextArea""); _jreVersionErrTextArea.setToolTipText(Messages.getString(""jreVersionErrTip"")); JScrollPane jscrollpane3 = new JScrollPane(); jscrollpane3.setViewportView(_jreVersionErrTextArea); jscrollpane3.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane3.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane3,cc.xy(4,8)); _launcherErrTextArea.setName(""launcherErrTextArea""); JScrollPane jscrollpane4 = new JScrollPane(); jscrollpane4.setViewportView(_launcherErrTextArea); jscrollpane4.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane4.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane4,cc.xy(4,10)); JLabel jlabel1 = new JLabel(); jlabel1.setText(Messages.getString(""startupErr"")); jpanel1.add(jlabel1,new CellConstraints(2,4,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); JLabel jlabel2 = new JLabel(); jlabel2.setText(Messages.getString(""bundledJreErr"")); jpanel1.add(jlabel2,new CellConstraints(2,6,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); JLabel jlabel3 = new JLabel(); jlabel3.setText(Messages.getString(""jreVersionErr"")); jpanel1.add(jlabel3,new CellConstraints(2,8,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); JLabel jlabel4 = new JLabel(); jlabel4.setText(Messages.getString(""launcherErr"")); jpanel1.add(jlabel4,new CellConstraints(2,10,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); _messagesCheck.setActionCommand(""Add version information""); _messagesCheck.setName(""messagesCheck""); _messagesCheck.setText(Messages.getString(""addMessages"")); jpanel1.add(_messagesCheck,cc.xy(4,2)); JLabel jlabel5 = new JLabel(); jlabel5.setText(Messages.getString(""instanceAlreadyExistsMsg"")); jpanel1.add(jlabel5,new CellConstraints(2,12,1,1,CellConstraints.DEFAULT,CellConstraints.TOP)); _instanceAlreadyExistsMsgTextArea.setName(""instanceAlreadyExistsMsgTextArea""); _instanceAlreadyExistsMsgTextArea.setToolTipText(Messages.getString(""instanceAlreadyExistsMsgTip"")); JScrollPane jscrollpane5 = new JScrollPane(); jscrollpane5.setViewportView(_instanceAlreadyExistsMsgTextArea); jscrollpane5.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane5.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane5,cc.xy(4,12)); addFillComponents(jpanel1,new int[]{ 1,2,3,4,5 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/VersionInfoForm.java",".java","10164","233","package net.sf.launch4j.form; import com.jeta.forms.components.separator.TitledSeparator; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public abstract class VersionInfoForm extends JPanel { protected final JCheckBox _versionInfoCheck = new JCheckBox(); protected final JLabel _fileVersionLabel = new JLabel(); protected final JTextField _fileVersionField = new JTextField(); protected final TitledSeparator _addVersionInfoSeparator = new TitledSeparator(); protected final JLabel _productVersionLabel = new JLabel(); protected final JTextField _productVersionField = new JTextField(); protected final JLabel _fileDescriptionLabel = new JLabel(); protected final JTextField _fileDescriptionField = new JTextField(); protected final JLabel _copyrightLabel = new JLabel(); protected final JTextField _copyrightField = new JTextField(); protected final JLabel _txtFileVersionLabel = new JLabel(); protected final JTextField _txtFileVersionField = new JTextField(); protected final JLabel _txtProductVersionLabel = new JLabel(); protected final JTextField _txtProductVersionField = new JTextField(); protected final JLabel _productNameLabel = new JLabel(); protected final JTextField _productNameField = new JTextField(); protected final JLabel _originalFilenameLabel = new JLabel(); protected final JTextField _originalFilenameField = new JTextField(); protected final JLabel _internalNameLabel = new JLabel(); protected final JTextField _internalNameField = new JTextField(); protected final JLabel _companyNameLabel = new JLabel(); protected final JTextField _companyNameField = new JTextField(); /** * Default constructor */ public VersionInfoForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:60DLU:NONE,FILL:7DLU:NONE,RIGHT:DEFAULT:NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE"",""CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _versionInfoCheck.setActionCommand(""Add version information""); _versionInfoCheck.setName(""versionInfoCheck""); _versionInfoCheck.setText(Messages.getString(""addVersionInfo"")); jpanel1.add(_versionInfoCheck,cc.xywh(4,2,5,1)); _fileVersionLabel.setIcon(loadImage(""images/asterix.gif"")); _fileVersionLabel.setName(""fileVersionLabel""); _fileVersionLabel.setText(Messages.getString(""fileVersion"")); jpanel1.add(_fileVersionLabel,cc.xy(2,4)); _fileVersionField.setName(""fileVersionField""); _fileVersionField.setToolTipText(Messages.getString(""fileVersionTip"")); jpanel1.add(_fileVersionField,cc.xy(4,4)); _addVersionInfoSeparator.setName(""addVersionInfoSeparator""); _addVersionInfoSeparator.setText(""Additional information""); jpanel1.add(_addVersionInfoSeparator,cc.xywh(2,10,7,1)); _productVersionLabel.setIcon(loadImage(""images/asterix.gif"")); _productVersionLabel.setName(""productVersionLabel""); _productVersionLabel.setText(Messages.getString(""productVersion"")); jpanel1.add(_productVersionLabel,cc.xy(2,12)); _productVersionField.setName(""productVersionField""); _productVersionField.setToolTipText(Messages.getString(""productVersionTip"")); jpanel1.add(_productVersionField,cc.xy(4,12)); _fileDescriptionLabel.setIcon(loadImage(""images/asterix.gif"")); _fileDescriptionLabel.setName(""fileDescriptionLabel""); _fileDescriptionLabel.setText(Messages.getString(""fileDescription"")); jpanel1.add(_fileDescriptionLabel,cc.xy(2,6)); _fileDescriptionField.setName(""fileDescriptionField""); _fileDescriptionField.setToolTipText(Messages.getString(""fileDescriptionTip"")); jpanel1.add(_fileDescriptionField,cc.xywh(4,6,5,1)); _copyrightLabel.setIcon(loadImage(""images/asterix.gif"")); _copyrightLabel.setName(""copyrightLabel""); _copyrightLabel.setText(Messages.getString(""copyright"")); jpanel1.add(_copyrightLabel,cc.xy(2,8)); _copyrightField.setName(""copyrightField""); jpanel1.add(_copyrightField,cc.xywh(4,8,5,1)); _txtFileVersionLabel.setIcon(loadImage(""images/asterix.gif"")); _txtFileVersionLabel.setName(""txtFileVersionLabel""); _txtFileVersionLabel.setText(Messages.getString(""txtFileVersion"")); jpanel1.add(_txtFileVersionLabel,cc.xy(6,4)); _txtFileVersionField.setName(""txtFileVersionField""); _txtFileVersionField.setToolTipText(Messages.getString(""txtFileVersionTip"")); jpanel1.add(_txtFileVersionField,cc.xy(8,4)); _txtProductVersionLabel.setIcon(loadImage(""images/asterix.gif"")); _txtProductVersionLabel.setName(""txtProductVersionLabel""); _txtProductVersionLabel.setText(Messages.getString(""txtProductVersion"")); jpanel1.add(_txtProductVersionLabel,cc.xy(6,12)); _txtProductVersionField.setName(""txtProductVersionField""); _txtProductVersionField.setToolTipText(Messages.getString(""txtProductVersionTip"")); jpanel1.add(_txtProductVersionField,cc.xy(8,12)); _productNameLabel.setIcon(loadImage(""images/asterix.gif"")); _productNameLabel.setName(""productNameLabel""); _productNameLabel.setText(Messages.getString(""productName"")); jpanel1.add(_productNameLabel,cc.xy(2,14)); _productNameField.setName(""productNameField""); jpanel1.add(_productNameField,cc.xywh(4,14,5,1)); _originalFilenameLabel.setIcon(loadImage(""images/asterix.gif"")); _originalFilenameLabel.setName(""originalFilenameLabel""); _originalFilenameLabel.setText(Messages.getString(""originalFilename"")); jpanel1.add(_originalFilenameLabel,cc.xy(2,20)); _originalFilenameField.setName(""originalFilenameField""); _originalFilenameField.setToolTipText(Messages.getString(""originalFilenameTip"")); jpanel1.add(_originalFilenameField,cc.xywh(4,20,5,1)); _internalNameLabel.setIcon(loadImage(""images/asterix.gif"")); _internalNameLabel.setName(""internalNameLabel""); _internalNameLabel.setText(Messages.getString(""internalName"")); jpanel1.add(_internalNameLabel,cc.xy(2,18)); _internalNameField.setName(""internalNameField""); _internalNameField.setToolTipText(Messages.getString(""internalNameTip"")); jpanel1.add(_internalNameField,cc.xywh(4,18,5,1)); _companyNameLabel.setName(""companyNameLabel""); _companyNameLabel.setText(Messages.getString(""companyName"")); jpanel1.add(_companyNameLabel,cc.xy(2,16)); _companyNameField.setName(""companyNameField""); jpanel1.add(_companyNameField,cc.xywh(4,16,5,1)); addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8,9 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/ClassPathForm.java",".java","7852","194","package net.sf.launch4j.form; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; public abstract class ClassPathForm extends JPanel { protected final JTextField _classpathField = new JTextField(); protected final JLabel _classpathFieldLabel = new JLabel(); protected final JLabel _classpathListLabel = new JLabel(); protected final JList _classpathList = new JList(); protected final JLabel _mainclassLabel = new JLabel(); protected final JTextField _mainclassField = new JTextField(); protected final JButton _acceptClasspathButton = new JButton(); protected final JButton _removeClasspathButton = new JButton(); protected final JButton _importClasspathButton = new JButton(); protected final JButton _classpathUpButton = new JButton(); protected final JButton _classpathDownButton = new JButton(); protected final JCheckBox _classpathCheck = new JCheckBox(); protected final JButton _newClasspathButton = new JButton(); /** * Default constructor */ public ClassPathForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:3DLU:NONE,FILL:26PX:NONE,FILL:7DLU:NONE"",""CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:DEFAULT:GROW(1.0),CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _classpathField.setName(""classpathField""); jpanel1.add(_classpathField,cc.xywh(4,11,7,1)); _classpathFieldLabel.setIcon(loadImage(""images/asterix.gif"")); _classpathFieldLabel.setName(""classpathFieldLabel""); _classpathFieldLabel.setText(Messages.getString(""editClassPath"")); jpanel1.add(_classpathFieldLabel,cc.xy(2,11)); _classpathListLabel.setName(""classpathListLabel""); _classpathListLabel.setText(Messages.getString(""classPath"")); jpanel1.add(_classpathListLabel,cc.xy(2,6)); _classpathList.setName(""classpathList""); JScrollPane jscrollpane1 = new JScrollPane(); jscrollpane1.setViewportView(_classpathList); jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane1,cc.xywh(4,6,7,4)); _mainclassLabel.setIcon(loadImage(""images/asterix.gif"")); _mainclassLabel.setName(""mainclassLabel""); _mainclassLabel.setText(Messages.getString(""mainClass"")); jpanel1.add(_mainclassLabel,cc.xy(2,4)); _mainclassField.setName(""mainclassField""); jpanel1.add(_mainclassField,cc.xywh(4,4,7,1)); _acceptClasspathButton.setActionCommand(""Add""); _acceptClasspathButton.setIcon(loadImage(""images/ok16.png"")); _acceptClasspathButton.setName(""acceptClasspathButton""); _acceptClasspathButton.setText(Messages.getString(""accept"")); jpanel1.add(_acceptClasspathButton,cc.xy(8,13)); _removeClasspathButton.setActionCommand(""Remove""); _removeClasspathButton.setIcon(loadImage(""images/cancel16.png"")); _removeClasspathButton.setName(""removeClasspathButton""); _removeClasspathButton.setText(Messages.getString(""remove"")); jpanel1.add(_removeClasspathButton,cc.xy(10,13)); _importClasspathButton.setIcon(loadImage(""images/open16.png"")); _importClasspathButton.setName(""importClasspathButton""); _importClasspathButton.setToolTipText(Messages.getString(""importClassPath"")); jpanel1.add(_importClasspathButton,cc.xy(12,4)); _classpathUpButton.setIcon(loadImage(""images/up16.png"")); _classpathUpButton.setName(""classpathUpButton""); jpanel1.add(_classpathUpButton,cc.xy(12,6)); _classpathDownButton.setIcon(loadImage(""images/down16.png"")); _classpathDownButton.setName(""classpathDownButton""); jpanel1.add(_classpathDownButton,cc.xy(12,8)); _classpathCheck.setActionCommand(""Custom classpath""); _classpathCheck.setName(""classpathCheck""); _classpathCheck.setText(Messages.getString(""customClassPath"")); jpanel1.add(_classpathCheck,cc.xy(4,2)); _newClasspathButton.setActionCommand(""New""); _newClasspathButton.setIcon(loadImage(""images/new16.png"")); _newClasspathButton.setName(""newClasspathButton""); _newClasspathButton.setText(Messages.getString(""new"")); jpanel1.add(_newClasspathButton,cc.xy(6,13)); addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/SplashForm.java",".java","6280","167","package net.sf.launch4j.form; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public abstract class SplashForm extends JPanel { protected final JLabel _splashFileLabel = new JLabel(); protected final JLabel _waitForWindowLabel = new JLabel(); protected final JLabel _timeoutLabel = new JLabel(); protected final JCheckBox _timeoutErrCheck = new JCheckBox(); protected final JTextField _splashFileField = new JTextField(); protected final JTextField _timeoutField = new JTextField(); protected final JButton _splashFileButton = new JButton(); protected final JCheckBox _splashCheck = new JCheckBox(); protected final JCheckBox _waitForWindowCheck = new JCheckBox(); /** * Default constructor */ public SplashForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:60DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:3DLU:NONE,FILL:26PX:NONE,FILL:7DLU:NONE"",""CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _splashFileLabel.setIcon(loadImage(""images/asterix.gif"")); _splashFileLabel.setName(""splashFileLabel""); _splashFileLabel.setText(Messages.getString(""splashFile"")); jpanel1.add(_splashFileLabel,cc.xy(2,4)); _waitForWindowLabel.setName(""waitForWindowLabel""); _waitForWindowLabel.setText(Messages.getString(""waitForWindow"")); jpanel1.add(_waitForWindowLabel,cc.xy(2,6)); _timeoutLabel.setIcon(loadImage(""images/asterix.gif"")); _timeoutLabel.setName(""timeoutLabel""); _timeoutLabel.setText(Messages.getString(""timeout"")); jpanel1.add(_timeoutLabel,cc.xy(2,8)); _timeoutErrCheck.setActionCommand(""Signal error on timeout""); _timeoutErrCheck.setName(""timeoutErrCheck""); _timeoutErrCheck.setText(Messages.getString(""timeoutErr"")); _timeoutErrCheck.setToolTipText(Messages.getString(""timeoutErrTip"")); jpanel1.add(_timeoutErrCheck,cc.xywh(4,10,2,1)); _splashFileField.setName(""splashFileField""); _splashFileField.setToolTipText(Messages.getString(""splashFileTip"")); jpanel1.add(_splashFileField,cc.xywh(4,4,2,1)); _timeoutField.setName(""timeoutField""); _timeoutField.setToolTipText(Messages.getString(""timeoutTip"")); jpanel1.add(_timeoutField,cc.xy(4,8)); _splashFileButton.setIcon(loadImage(""images/open16.png"")); _splashFileButton.setName(""splashFileButton""); jpanel1.add(_splashFileButton,cc.xy(7,4)); _splashCheck.setActionCommand(""Enable splash screen""); _splashCheck.setName(""splashCheck""); _splashCheck.setText(Messages.getString(""enableSplash"")); jpanel1.add(_splashCheck,cc.xywh(4,2,2,1)); _waitForWindowCheck.setActionCommand(""Close splash screen when an application window appears""); _waitForWindowCheck.setName(""waitForWindowCheck""); _waitForWindowCheck.setText(Messages.getString(""waitForWindowText"")); jpanel1.add(_waitForWindowCheck,cc.xywh(4,6,2,1)); addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/ConfigForm.java",".java","4350","133","package net.sf.launch4j.form; import com.jeta.forms.components.separator.TitledSeparator; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTextArea; public abstract class ConfigForm extends JPanel { protected final JTextArea _logTextArea = new JTextArea(); protected final TitledSeparator _logSeparator = new TitledSeparator(); protected final JTabbedPane _tab = new JTabbedPane(); /** * Default constructor */ public ConfigForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE"",""CENTER:3DLU:NONE,FILL:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,FILL:DEFAULT:GROW(1.0),CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _logTextArea.setName(""logTextArea""); JScrollPane jscrollpane1 = new JScrollPane(); jscrollpane1.setViewportView(_logTextArea); jscrollpane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); jscrollpane1.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); jpanel1.add(jscrollpane1,cc.xy(2,6)); _logSeparator.setName(""logSeparator""); _logSeparator.setText(Messages.getString(""log"")); jpanel1.add(_logSeparator,cc.xy(2,4)); _tab.setName(""tab""); jpanel1.add(_tab,cc.xywh(1,2,3,1)); addFillComponents(jpanel1,new int[]{ 1,2,3 },new int[]{ 1,3,4,5,6,7 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/SingleInstanceForm.java",".java","4808","142","package net.sf.launch4j.form; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public abstract class SingleInstanceForm extends JPanel { protected final JLabel _splashFileLabel = new JLabel(); protected final JTextField _mutexNameField = new JTextField(); protected final JCheckBox _singleInstanceCheck = new JCheckBox(); protected final JTextField _windowTitleField = new JTextField(); protected final JLabel _splashFileLabel1 = new JLabel(); /** * Default constructor */ public SingleInstanceForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:60DLU:NONE,FILL:DEFAULT:GROW(1.0),FILL:7DLU:NONE"",""CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _splashFileLabel.setIcon(loadImage(""images/asterix.gif"")); _splashFileLabel.setName(""splashFileLabel""); _splashFileLabel.setText(Messages.getString(""mutexName"")); jpanel1.add(_splashFileLabel,cc.xy(2,4)); _mutexNameField.setName(""mutexNameField""); _mutexNameField.setToolTipText(Messages.getString(""mutexNameTip"")); jpanel1.add(_mutexNameField,cc.xywh(4,4,2,1)); _singleInstanceCheck.setActionCommand(""Enable splash screen""); _singleInstanceCheck.setName(""singleInstanceCheck""); _singleInstanceCheck.setText(Messages.getString(""enableSingleInstance"")); jpanel1.add(_singleInstanceCheck,cc.xywh(4,2,2,1)); _windowTitleField.setName(""windowTitleField""); _windowTitleField.setToolTipText(Messages.getString(""windowTitleTip"")); jpanel1.add(_windowTitleField,cc.xywh(4,6,2,1)); _splashFileLabel1.setName(""splashFileLabel""); _splashFileLabel1.setText(Messages.getString(""windowTitle"")); jpanel1.add(_splashFileLabel1,cc.xy(2,6)); addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6 },new int[]{ 1,2,3,4,5,6,7 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/form/BasicForm.java",".java","11830","284","package net.sf.launch4j.form; import com.jeta.forms.components.separator.TitledSeparator; import com.jgoodies.forms.layout.CellConstraints; import com.jgoodies.forms.layout.FormLayout; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Box; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; public abstract class BasicForm extends JPanel { protected final JButton _outfileButton = new JButton(); protected final JLabel _outfileLabel = new JLabel(); protected final JLabel _iconLabel = new JLabel(); protected final JLabel _jarLabel = new JLabel(); protected final JButton _jarButton = new JButton(); protected final JButton _iconButton = new JButton(); protected final JLabel _cmdLineLabel = new JLabel(); protected final JLabel _optionsLabel = new JLabel(); protected final JLabel _chdirLabel = new JLabel(); protected final JLabel _processPriorityLabel = new JLabel(); protected final JRadioButton _normalPriorityRadio = new JRadioButton(); protected final ButtonGroup _buttongroup1 = new ButtonGroup(); protected final JRadioButton _idlePriorityRadio = new JRadioButton(); protected final JRadioButton _highPriorityRadio = new JRadioButton(); protected final JCheckBox _customProcNameCheck = new JCheckBox(); protected final JCheckBox _stayAliveCheck = new JCheckBox(); protected final JTextField _cmdLineField = new JTextField(); protected final JTextField _chdirField = new JTextField(); protected final JTextField _iconField = new JTextField(); protected final JCheckBox _dontWrapJarCheck = new JCheckBox(); protected final JTextField _jarField = new JTextField(); protected final JTextField _outfileField = new JTextField(); protected final JLabel _errorTitleLabel = new JLabel(); protected final JTextField _errorTitleField = new JTextField(); protected final JLabel _downloadUrlLabel = new JLabel(); protected final JTextField _downloadUrlField = new JTextField(); protected final JLabel _supportUrlLabel = new JLabel(); protected final JTextField _supportUrlField = new JTextField(); protected final JTextField _manifestField = new JTextField(); protected final JButton _manifestButton = new JButton(); /** * Default constructor */ public BasicForm() { initializePanel(); } /** * Adds fill components to empty cells in the first row and first column of the grid. * This ensures that the grid spacing will be the same as shown in the designer. * @param cols an array of column indices in the first row where fill components should be added. * @param rows an array of row indices in the first column where fill components should be added. */ void addFillComponents( Container panel, int[] cols, int[] rows ) { Dimension filler = new Dimension(10,10); boolean filled_cell_11 = false; CellConstraints cc = new CellConstraints(); if ( cols.length > 0 && rows.length > 0 ) { if ( cols[0] == 1 && rows[0] == 1 ) { /** add a rigid area */ panel.add( Box.createRigidArea( filler ), cc.xy(1,1) ); filled_cell_11 = true; } } for( int index = 0; index < cols.length; index++ ) { if ( cols[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(cols[index],1) ); } for( int index = 0; index < rows.length; index++ ) { if ( rows[index] == 1 && filled_cell_11 ) { continue; } panel.add( Box.createRigidArea( filler ), cc.xy(1,rows[index]) ); } } /** * Helper method to load an image file from the CLASSPATH * @param imageName the package and name of the file to load relative to the CLASSPATH * @return an ImageIcon instance with the specified image file * @throws IllegalArgumentException if the image resource cannot be loaded. */ public ImageIcon loadImage( String imageName ) { try { ClassLoader classloader = getClass().getClassLoader(); java.net.URL url = classloader.getResource( imageName ); if ( url != null ) { ImageIcon icon = new ImageIcon( url ); return icon; } } catch( Exception e ) { e.printStackTrace(); } throw new IllegalArgumentException( ""Unable to load image: "" + imageName ); } public JPanel createPanel() { JPanel jpanel1 = new JPanel(); FormLayout formlayout1 = new FormLayout(""FILL:7DLU:NONE,RIGHT:MAX(65DLU;DEFAULT):NONE,FILL:3DLU:NONE,FILL:DEFAULT:NONE,FILL:7DLU:NONE,FILL:DEFAULT:NONE,FILL:7DLU:NONE,FILL:DEFAULT:NONE,FILL:DEFAULT:NONE,FILL:DEFAULT:GROW(1.0),FILL:3DLU:NONE,FILL:26PX:NONE,FILL:7DLU:NONE"",""CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:3DLU:NONE,CENTER:DEFAULT:NONE,CENTER:9DLU:NONE""); CellConstraints cc = new CellConstraints(); jpanel1.setLayout(formlayout1); _outfileButton.setIcon(loadImage(""images/open16.png"")); _outfileButton.setName(""outfileButton""); jpanel1.add(_outfileButton,cc.xy(12,2)); _outfileLabel.setIcon(loadImage(""images/asterix.gif"")); _outfileLabel.setName(""outfileLabel""); _outfileLabel.setText(Messages.getString(""outfile"")); jpanel1.add(_outfileLabel,cc.xy(2,2)); _iconLabel.setName(""iconLabel""); _iconLabel.setText(Messages.getString(""icon"")); jpanel1.add(_iconLabel,cc.xy(2,10)); _jarLabel.setIcon(loadImage(""images/asterix.gif"")); _jarLabel.setName(""jarLabel""); _jarLabel.setText(Messages.getString(""jar"")); jpanel1.add(_jarLabel,cc.xy(2,4)); _jarButton.setIcon(loadImage(""images/open16.png"")); _jarButton.setName(""jarButton""); jpanel1.add(_jarButton,cc.xy(12,4)); _iconButton.setIcon(loadImage(""images/open16.png"")); _iconButton.setName(""iconButton""); jpanel1.add(_iconButton,cc.xy(12,10)); _cmdLineLabel.setName(""cmdLineLabel""); _cmdLineLabel.setText(Messages.getString(""cmdLine"")); _cmdLineLabel.setToolTipText(""""); jpanel1.add(_cmdLineLabel,cc.xy(2,14)); _optionsLabel.setName(""optionsLabel""); _optionsLabel.setText(Messages.getString(""options"")); jpanel1.add(_optionsLabel,cc.xy(2,18)); _chdirLabel.setName(""chdirLabel""); _chdirLabel.setText(Messages.getString(""chdir"")); jpanel1.add(_chdirLabel,cc.xy(2,12)); _processPriorityLabel.setName(""processPriorityLabel""); _processPriorityLabel.setText(Messages.getString(""priority"")); jpanel1.add(_processPriorityLabel,cc.xy(2,16)); _normalPriorityRadio.setActionCommand(Messages.getString(""normalPriority"")); _normalPriorityRadio.setName(""normalPriorityRadio""); _normalPriorityRadio.setText(Messages.getString(""normalPriority"")); _buttongroup1.add(_normalPriorityRadio); jpanel1.add(_normalPriorityRadio,cc.xy(4,16)); _idlePriorityRadio.setActionCommand(Messages.getString(""idlePriority"")); _idlePriorityRadio.setName(""idlePriorityRadio""); _idlePriorityRadio.setText(Messages.getString(""idlePriority"")); _buttongroup1.add(_idlePriorityRadio); jpanel1.add(_idlePriorityRadio,cc.xy(6,16)); _highPriorityRadio.setActionCommand(Messages.getString(""highPriority"")); _highPriorityRadio.setName(""highPriorityRadio""); _highPriorityRadio.setText(Messages.getString(""highPriority"")); _buttongroup1.add(_highPriorityRadio); jpanel1.add(_highPriorityRadio,cc.xy(8,16)); _customProcNameCheck.setActionCommand(""Custom process name""); _customProcNameCheck.setName(""customProcNameCheck""); _customProcNameCheck.setText(Messages.getString(""customProcName"")); jpanel1.add(_customProcNameCheck,cc.xywh(4,18,7,1)); _stayAliveCheck.setActionCommand(""Stay alive after launching a GUI application""); _stayAliveCheck.setName(""stayAliveCheck""); _stayAliveCheck.setText(Messages.getString(""stayAlive"")); jpanel1.add(_stayAliveCheck,cc.xywh(4,20,7,1)); _cmdLineField.setName(""cmdLineField""); _cmdLineField.setToolTipText(Messages.getString(""cmdLineTip"")); jpanel1.add(_cmdLineField,cc.xywh(4,14,7,1)); _chdirField.setName(""chdirField""); _chdirField.setToolTipText(Messages.getString(""chdirTip"")); jpanel1.add(_chdirField,cc.xywh(4,12,7,1)); _iconField.setName(""iconField""); _iconField.setToolTipText(Messages.getString(""iconTip"")); jpanel1.add(_iconField,cc.xywh(4,10,7,1)); _dontWrapJarCheck.setActionCommand(""Don't wrap the jar, launch it only""); _dontWrapJarCheck.setName(""dontWrapJarCheck""); _dontWrapJarCheck.setText(Messages.getString(""dontWrapJar"")); jpanel1.add(_dontWrapJarCheck,cc.xywh(4,6,7,1)); _jarField.setName(""jarField""); _jarField.setToolTipText(Messages.getString(""jarTip"")); jpanel1.add(_jarField,cc.xywh(4,4,7,1)); _outfileField.setName(""outfileField""); _outfileField.setToolTipText(Messages.getString(""outfileTip"")); jpanel1.add(_outfileField,cc.xywh(4,2,7,1)); TitledSeparator titledseparator1 = new TitledSeparator(); titledseparator1.setText(Messages.getString(""downloadAndSupport"")); jpanel1.add(titledseparator1,cc.xywh(2,22,11,1)); _errorTitleLabel.setName(""errorTitleLabel""); _errorTitleLabel.setText(Messages.getString(""errorTitle"")); jpanel1.add(_errorTitleLabel,cc.xy(2,24)); _errorTitleField.setName(""errorTitleField""); _errorTitleField.setToolTipText(Messages.getString(""errorTitleTip"")); jpanel1.add(_errorTitleField,cc.xywh(4,24,7,1)); _downloadUrlLabel.setIcon(loadImage(""images/asterix.gif"")); _downloadUrlLabel.setName(""downloadUrlLabel""); _downloadUrlLabel.setText(Messages.getString(""downloadUrl"")); jpanel1.add(_downloadUrlLabel,cc.xy(2,26)); _downloadUrlField.setName(""downloadUrlField""); jpanel1.add(_downloadUrlField,cc.xywh(4,26,7,1)); _supportUrlLabel.setName(""supportUrlLabel""); _supportUrlLabel.setText(Messages.getString(""supportUrl"")); jpanel1.add(_supportUrlLabel,cc.xy(2,28)); _supportUrlField.setName(""supportUrlField""); jpanel1.add(_supportUrlField,cc.xywh(4,28,7,1)); JLabel jlabel1 = new JLabel(); jlabel1.setText(Messages.getString(""manifest"")); jpanel1.add(jlabel1,cc.xy(2,8)); _manifestField.setName(""manifestField""); _manifestField.setToolTipText(Messages.getString(""manifestTip"")); jpanel1.add(_manifestField,cc.xywh(4,8,7,1)); _manifestButton.setIcon(loadImage(""images/open16.png"")); _manifestButton.setName(""manifestButton""); jpanel1.add(_manifestButton,cc.xy(12,8)); addFillComponents(jpanel1,new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13 },new int[]{ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29 }); return jpanel1; } /** * Initializer */ protected void initializePanel() { setLayout(new BorderLayout()); add(createPanel(), BorderLayout.CENTER); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/Msg.java",".java","4279","112","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Oct 8, 2006 */ package net.sf.launch4j.config; import net.sf.launch4j.binding.IValidatable; import net.sf.launch4j.binding.Validator; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class Msg implements IValidatable { private String startupErr; private String bundledJreErr; private String jreVersionErr; private String launcherErr; private String instanceAlreadyExistsMsg; public void checkInvariants() { Validator.checkOptString(startupErr, 1024, ""startupErr"", Messages.getString(""Msg.startupErr"")); Validator.checkOptString(bundledJreErr, 1024, ""bundledJreErr"", Messages.getString(""Msg.bundledJreErr"")); Validator.checkOptString(jreVersionErr, 1024, ""jreVersionErr"", Messages.getString(""Msg.jreVersionErr"")); Validator.checkOptString(launcherErr, 1024, ""launcherErr"", Messages.getString(""Msg.launcherErr"")); Validator.checkOptString(instanceAlreadyExistsMsg, 1024, ""instanceAlreadyExistsMsg"", Messages.getString(""Msg.instanceAlreadyExistsMsg"")); } public String getStartupErr() { return !Validator.isEmpty(startupErr) ? startupErr : ""An error occurred while starting the application.""; } public void setStartupErr(String startupErr) { this.startupErr = startupErr; } public String getBundledJreErr() { return !Validator.isEmpty(bundledJreErr) ? bundledJreErr : ""This application was configured to use a bundled Java Runtime"" + "" Environment but the runtime is missing or corrupted.""; } public void setBundledJreErr(String bundledJreErr) { this.bundledJreErr = bundledJreErr; } public String getJreVersionErr() { return !Validator.isEmpty(jreVersionErr) ? jreVersionErr : ""This application requires a Java Runtime Environment""; } public void setJreVersionErr(String jreVersionErr) { this.jreVersionErr = jreVersionErr; } public String getLauncherErr() { return !Validator.isEmpty(launcherErr) ? launcherErr : ""The registry refers to a nonexistent Java Runtime Environment"" + "" installation or the runtime is corrupted.""; } public void setLauncherErr(String launcherErr) { this.launcherErr = launcherErr; } public String getInstanceAlreadyExistsMsg() { return !Validator.isEmpty(instanceAlreadyExistsMsg) ? instanceAlreadyExistsMsg : ""An application instance is already running.""; } public void setInstanceAlreadyExistsMsg(String instanceAlreadyExistsMsg) { this.instanceAlreadyExistsMsg = instanceAlreadyExistsMsg; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/Config.java",".java","11193","397","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 21, 2005 */ package net.sf.launch4j.config; import java.io.File; import java.util.Arrays; import java.util.List; import net.sf.launch4j.binding.IValidatable; import net.sf.launch4j.binding.Validator; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class Config implements IValidatable { // 1.x config properties_____________________________________________________________ public static final String HEADER = ""header""; public static final String JAR = ""jar""; public static final String OUTFILE = ""outfile""; public static final String ERR_TITLE = ""errTitle""; public static final String JAR_ARGS = ""jarArgs""; public static final String CHDIR = ""chdir""; public static final String CUSTOM_PROC_NAME = ""customProcName""; public static final String STAY_ALIVE = ""stayAlive""; public static final String ICON = ""icon""; // __________________________________________________________________________________ public static final String DOWNLOAD_URL = ""http://java.com/download""; public static final String GUI_HEADER = ""gui""; public static final String CONSOLE_HEADER = ""console""; private static final String[] HEADER_TYPES = new String[] { GUI_HEADER, CONSOLE_HEADER }; private static final String[] PRIORITY_CLASS_NAMES = new String[] { ""normal"", ""idle"", ""high"" }; private static final int[] PRIORITY_CLASSES = new int[] { 0x00000020, 0x00000040, 0x00000080 }; private boolean dontWrapJar; private String headerType = GUI_HEADER; private List headerObjects; private List libs; private File jar; private File outfile; // Runtime header configuration private String errTitle; private String cmdLine; private String chdir; private String priority; private String downloadUrl; private String supportUrl; private boolean customProcName; private boolean stayAlive; private File manifest; private File icon; private List variables; private SingleInstance singleInstance; private ClassPath classPath; private Jre jre; private Splash splash; private VersionInfo versionInfo; private Msg messages; public void checkInvariants() { Validator.checkTrue(outfile != null && outfile.getPath().endsWith("".exe""), ""outfile"", Messages.getString(""Config.specify.output.exe"")); if (dontWrapJar) { if (jar != null && !jar.getPath().equals("""")) { Validator.checkRelativeWinPath(jar.getPath(), ""jar"", Messages.getString(""Config.application.jar.path"")); } else { Validator.checkTrue(classPath != null, ""classPath"", Messages.getString(""ClassPath.or.jar"")); } } else { Validator.checkFile(jar, ""jar"", Messages.getString(""Config.application.jar"")); } if (!Validator.isEmpty(chdir)) { Validator.checkRelativeWinPath(chdir, ""chdir"", Messages.getString(""Config.chdir.relative"")); Validator.checkFalse(chdir.toLowerCase().equals(""true"") || chdir.toLowerCase().equals(""false""), ""chdir"", Messages.getString(""Config.chdir.path"")); } Validator.checkOptFile(manifest, ""manifest"", Messages.getString(""Config.manifest"")); Validator.checkOptFile(icon, ""icon"", Messages.getString(""Config.icon"")); Validator.checkOptString(cmdLine, Validator.MAX_BIG_STR, ""jarArgs"", Messages.getString(""Config.jar.arguments"")); Validator.checkOptString(errTitle, Validator.MAX_STR, ""errTitle"", Messages.getString(""Config.error.title"")); Validator.checkOptString(downloadUrl, 256, ""downloadUrl"", Messages.getString(""Config.download.url"")); Validator.checkOptString(supportUrl, 256, ""supportUrl"", Messages.getString(""Config.support.url"")); Validator.checkIn(getHeaderType(), HEADER_TYPES, ""headerType"", Messages.getString(""Config.header.type"")); Validator.checkFalse(getHeaderType().equals(CONSOLE_HEADER) && splash != null, ""headerType"", Messages.getString(""Config.splash.not.impl.by.console.hdr"")); Validator.checkOptStrings(variables, Validator.MAX_ARGS, Validator.MAX_ARGS, ""[^=%\t]+=[^=\t]+"", ""variables"", Messages.getString(""Config.variables""), Messages.getString(""Config.variables.err"")); Validator.checkIn(getPriority(), PRIORITY_CLASS_NAMES, ""priority"", Messages.getString(""Config.priority"")); jre.checkInvariants(); } public void validate() { checkInvariants(); if (classPath != null) { classPath.checkInvariants(); } if (splash != null) { splash.checkInvariants(); } if (versionInfo != null) { versionInfo.checkInvariants(); } } /** Change current directory to EXE location. */ public String getChdir() { return chdir; } public void setChdir(String chdir) { this.chdir = chdir; } /** Constant command line arguments passed to the application. */ public String getCmdLine() { return cmdLine; } public void setCmdLine(String cmdLine) { this.cmdLine = cmdLine; } /** Optional, error message box title. */ public String getErrTitle() { return errTitle; } public void setErrTitle(String errTitle) { this.errTitle = errTitle; } /** launch4j header file. */ public String getHeaderType() { return headerType.toLowerCase(); } public void setHeaderType(String headerType) { this.headerType = headerType; } /** launch4j header file index - used by GUI. */ public int getHeaderTypeIndex() { int x = Arrays.asList(HEADER_TYPES).indexOf(getHeaderType()); return x != -1 ? x : 0; } public void setHeaderTypeIndex(int headerTypeIndex) { headerType = HEADER_TYPES[headerTypeIndex]; } public boolean isCustomHeaderObjects() { return headerObjects != null && !headerObjects.isEmpty(); } public List getHeaderObjects() { return isCustomHeaderObjects() ? headerObjects : getHeaderType().equals(GUI_HEADER) ? LdDefaults.GUI_HEADER_OBJECTS : LdDefaults.CONSOLE_HEADER_OBJECTS; } public void setHeaderObjects(List headerObjects) { this.headerObjects = headerObjects; } public boolean isCustomLibs() { return libs != null && !libs.isEmpty(); } public List getLibs() { return isCustomLibs() ? libs : LdDefaults.LIBS; } public void setLibs(List libs) { this.libs = libs; } /** Wrapper's manifest for User Account Control. */ public File getManifest() { return manifest; } public void setManifest(File manifest) { this.manifest = manifest; } /** ICO file. */ public File getIcon() { return icon; } public void setIcon(File icon) { this.icon = icon; } /** Jar to wrap. */ public File getJar() { return jar; } public void setJar(File jar) { this.jar = jar; } public List getVariables() { return variables; } public void setVariables(List variables) { this.variables = variables; } public ClassPath getClassPath() { return classPath; } public void setClassPath(ClassPath classpath) { this.classPath = classpath; } /** JRE configuration */ public Jre getJre() { return jre; } public void setJre(Jre jre) { this.jre = jre; } /** Output EXE file. */ public File getOutfile() { return outfile; } public void setOutfile(File outfile) { this.outfile = outfile; } /** Custom process name as the output EXE file name. */ public boolean isCustomProcName() { return customProcName; } public void setCustomProcName(boolean customProcName) { this.customProcName = customProcName; } /** Splash screen configuration. */ public Splash getSplash() { return splash; } public void setSplash(Splash splash) { this.splash = splash; } /** Stay alive after launching the application. */ public boolean isStayAlive() { return stayAlive; } public void setStayAlive(boolean stayAlive) { this.stayAlive = stayAlive; } public VersionInfo getVersionInfo() { return versionInfo; } public void setVersionInfo(VersionInfo versionInfo) { this.versionInfo = versionInfo; } public boolean isDontWrapJar() { return dontWrapJar; } public void setDontWrapJar(boolean dontWrapJar) { this.dontWrapJar = dontWrapJar; } public int getPriorityIndex() { int x = Arrays.asList(PRIORITY_CLASS_NAMES).indexOf(getPriority()); return x != -1 ? x : 0; } public void setPriorityIndex(int x) { priority = PRIORITY_CLASS_NAMES[x]; } public String getPriority() { return Validator.isEmpty(priority) ? PRIORITY_CLASS_NAMES[0] : priority; } public void setPriority(String priority) { this.priority = priority; } public int getPriorityClass() { return PRIORITY_CLASSES[getPriorityIndex()]; } public String getDownloadUrl() { return downloadUrl == null ? DOWNLOAD_URL : downloadUrl; } public void setDownloadUrl(String downloadUrl) { this.downloadUrl = downloadUrl; } public String getSupportUrl() { return supportUrl; } public void setSupportUrl(String supportUrl) { this.supportUrl = supportUrl; } public Msg getMessages() { return messages; } public void setMessages(Msg messages) { this.messages = messages; } public SingleInstance getSingleInstance() { return singleInstance; } public void setSingleInstance(SingleInstance singleInstance) { this.singleInstance = singleInstance; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/Messages.java",".java","2993","79","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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 net.sf.launch4j.config; import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = ""net.sf.launch4j.config.messages""; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private static final MessageFormat FORMATTER = new MessageFormat(""""); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } public static String getString(String key, String arg0) { return getString(key, new Object[] {arg0}); } public static String getString(String key, String arg0, String arg1) { return getString(key, new Object[] {arg0, arg1}); } public static String getString(String key, String arg0, String arg1, String arg2) { return getString(key, new Object[] {arg0, arg1, arg2}); } public static String getString(String key, Object[] args) { try { FORMATTER.applyPattern(RESOURCE_BUNDLE.getString(key)); return FORMATTER.format(args); } catch (MissingResourceException e) { return '!' + key + '!'; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/ConfigPersisterException.java",".java","2054","52","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 22, 2005 */ package net.sf.launch4j.config; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class ConfigPersisterException extends Exception { public ConfigPersisterException(String msg, Throwable t) { super(msg, t); } public ConfigPersisterException(Throwable t) { super(t); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/LdDefaults.java",".java","2411","63","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Sep 3, 2005 */ package net.sf.launch4j.config; import java.util.Arrays; import java.util.List; public class LdDefaults { public static final List GUI_HEADER_OBJECTS = Arrays.asList(new String[] { ""w32api/crt2.o"", ""head/guihead.o"", ""head/head.o"" }); public static final List CONSOLE_HEADER_OBJECTS = Arrays.asList(new String[] { ""w32api/crt2.o"", ""head/consolehead.o"", ""head/head.o""}); public static final List LIBS = Arrays.asList(new String[] { ""w32api/libmingw32.a"", ""w32api/libgcc.a"", ""w32api/libmsvcrt.a"", ""w32api/libkernel32.a"", ""w32api/libuser32.a"", ""w32api/libadvapi32.a"", ""w32api/libshell32.a"" }); } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/SingleInstance.java",".java","2638","75","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /** * Created on 2007-09-16 */ package net.sf.launch4j.config; import net.sf.launch4j.binding.IValidatable; import net.sf.launch4j.binding.Validator; /** * @author Copyright (C) 2007 Grzegorz Kowal */ public class SingleInstance implements IValidatable { private String mutexName; private String windowTitle; public void checkInvariants() { Validator.checkString(mutexName, Validator.MAX_STR, ""singleInstance.mutexName"", Messages.getString(""SingleInstance.mutexName"")); Validator.checkOptString(windowTitle, Validator.MAX_STR, ""singleInstance.windowTitle"", Messages.getString(""SingleInstance.windowTitle"")); } public String getWindowTitle() { return windowTitle; } public void setWindowTitle(String appWindowName) { this.windowTitle = appWindowName; } public String getMutexName() { return mutexName; } public void setMutexName(String mutexName) { this.mutexName = mutexName; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/VersionInfo.java",".java","5740","169","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 21, 2005 */ package net.sf.launch4j.config; import net.sf.launch4j.binding.IValidatable; import net.sf.launch4j.binding.Validator; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class VersionInfo implements IValidatable { public static final String VERSION_PATTERN = ""(\\d+\\.){3}\\d+""; private String fileVersion; private String txtFileVersion; private String fileDescription; private String copyright; private String productVersion; private String txtProductVersion; private String productName; private String companyName; private String internalName; private String originalFilename; public void checkInvariants() { Validator.checkString(fileVersion, 20, VERSION_PATTERN, ""versionInfo.fileVersion"", Messages.getString(""VersionInfo.file.version"")); Validator.checkString(txtFileVersion, 50, ""versionInfo.txtFileVersion"", Messages.getString(""VersionInfo.txt.file.version"")); Validator.checkString(fileDescription, 150, ""versionInfo.fileDescription"", Messages.getString(""VersionInfo.file.description"")); Validator.checkString(copyright, 150, ""versionInfo.copyright"", Messages.getString(""VersionInfo.copyright"")); Validator.checkString(productVersion, 20, VERSION_PATTERN, ""versionInfo.productVersion"", Messages.getString(""VersionInfo.product.version"")); Validator.checkString(txtProductVersion, 50, ""versionInfo.txtProductVersion"", Messages.getString(""VersionInfo.txt.product.version"")); Validator.checkString(productName, 150, ""versionInfo.productName"", Messages.getString(""VersionInfo.product.name"")); Validator.checkOptString(companyName, 150, ""versionInfo.companyName"", Messages.getString(""VersionInfo.company.name"")); Validator.checkString(internalName, 50, ""versionInfo.internalName"", Messages.getString(""VersionInfo.internal.name"")); Validator.checkTrue(!internalName.endsWith("".exe""), ""versionInfo.internalName"", Messages.getString(""VersionInfo.internal.name.not.exe"")); Validator.checkString(originalFilename, 50, ""versionInfo.originalFilename"", Messages.getString(""VersionInfo.original.filename"")); Validator.checkTrue(originalFilename.endsWith("".exe""), ""versionInfo.originalFilename"", Messages.getString(""VersionInfo.original.filename.exe"")); } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getCopyright() { return copyright; } public void setCopyright(String copyright) { this.copyright = copyright; } public String getFileDescription() { return fileDescription; } public void setFileDescription(String fileDescription) { this.fileDescription = fileDescription; } public String getFileVersion() { return fileVersion; } public void setFileVersion(String fileVersion) { this.fileVersion = fileVersion; } public String getInternalName() { return internalName; } public void setInternalName(String internalName) { this.internalName = internalName; } public String getOriginalFilename() { return originalFilename; } public void setOriginalFilename(String originalFilename) { this.originalFilename = originalFilename; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductVersion() { return productVersion; } public void setProductVersion(String productVersion) { this.productVersion = productVersion; } public String getTxtFileVersion() { return txtFileVersion; } public void setTxtFileVersion(String txtFileVersion) { this.txtFileVersion = txtFileVersion; } public String getTxtProductVersion() { return txtProductVersion; } public void setTxtProductVersion(String txtProductVersion) { this.txtProductVersion = txtProductVersion; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/ConfigPersister.java",".java","8579","250","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 22, 2005 */ package net.sf.launch4j.config; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Properties; import net.sf.launch4j.Util; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class ConfigPersister { private static final ConfigPersister _instance = new ConfigPersister(); private final XStream _xstream; private Config _config; private File _configPath; private ConfigPersister() { _xstream = new XStream(new DomDriver()); _xstream.alias(""launch4jConfig"", Config.class); _xstream.alias(""classPath"", ClassPath.class); _xstream.alias(""jre"", Jre.class); _xstream.alias(""splash"", Splash.class); _xstream.alias(""versionInfo"", VersionInfo.class); _xstream.addImplicitCollection(Config.class, ""headerObjects"", ""obj"", String.class); _xstream.addImplicitCollection(Config.class, ""libs"", ""lib"", String.class); _xstream.addImplicitCollection(Config.class, ""variables"", ""var"", String.class); _xstream.addImplicitCollection(ClassPath.class, ""paths"", ""cp"", String.class); _xstream.addImplicitCollection(Jre.class, ""options"", ""opt"", String.class); } public static ConfigPersister getInstance() { return _instance; } public Config getConfig() { return _config; } public File getConfigPath() { return _configPath; } public File getOutputPath() throws IOException { if (_config.getOutfile().isAbsolute()) { return _config.getOutfile().getParentFile(); } File parent = _config.getOutfile().getParentFile(); return (parent != null) ? new File(_configPath, parent.getPath()) : _configPath; } public File getOutputFile() throws IOException { return _config.getOutfile().isAbsolute() ? _config.getOutfile() : new File(getOutputPath(), _config.getOutfile().getName()); } public void createBlank() { _config = new Config(); _config.setJre(new Jre()); _configPath = null; } public void setAntConfig(Config c, File basedir) { _config = c; _configPath = basedir; } public void load(File f) throws ConfigPersisterException { try { FileReader r = new FileReader(f); char[] buf = new char[(int) f.length()]; r.read(buf); r.close(); // Convert 2.x config to 3.x String s = String.valueOf(buf) .replaceAll(""0<"", ""gui<"") .replaceAll(""1<"", ""console<"") .replaceAll(""jarArgs>"", ""cmdLine>"") .replaceAll("""", """") .replaceAll(""args>"", ""opt>"") .replaceAll("""", """") .replaceAll(""false"", """" + Jre.JDK_PREFERENCE_PREFER_JRE + """") .replaceAll(""true"", """" + Jre.JDK_PREFERENCE_JRE_ONLY + """") .replaceAll(""0"", """") .replaceAll(""0"", """"); _config = (Config) _xstream.fromXML(s); setConfigPath(f); } catch (Exception e) { throw new ConfigPersisterException(e); } } /** * Imports launch4j 1.x.x config file. */ public void loadVersion1(File f) throws ConfigPersisterException { try { Props props = new Props(f); _config = new Config(); String header = props.getProperty(Config.HEADER); _config.setHeaderType(header == null || header.toLowerCase().equals(""guihead.bin"") ? Config.GUI_HEADER : Config.CONSOLE_HEADER); _config.setJar(props.getFile(Config.JAR)); _config.setOutfile(props.getFile(Config.OUTFILE)); _config.setJre(new Jre()); _config.getJre().setPath(props.getProperty(Jre.PATH)); _config.getJre().setMinVersion(props.getProperty(Jre.MIN_VERSION)); _config.getJre().setMaxVersion(props.getProperty(Jre.MAX_VERSION)); String args = props.getProperty(Jre.ARGS); if (args != null) { List jreOptions = new ArrayList(); jreOptions.add(args); _config.getJre().setOptions(jreOptions); } _config.setCmdLine(props.getProperty(Config.JAR_ARGS)); _config.setChdir(""true"".equals(props.getProperty(Config.CHDIR)) ? ""."" : null); _config.setCustomProcName(""true"".equals( props.getProperty(""setProcName""))); // 1.x _config.setStayAlive(""true"".equals(props.getProperty(Config.STAY_ALIVE))); _config.setErrTitle(props.getProperty(Config.ERR_TITLE)); _config.setIcon(props.getFile(Config.ICON)); File splashFile = props.getFile(Splash.SPLASH_FILE); if (splashFile != null) { _config.setSplash(new Splash()); _config.getSplash().setFile(splashFile); String waitfor = props.getProperty(""waitfor""); // 1.x _config.getSplash().setWaitForWindow(waitfor != null && !waitfor.equals("""")); String splashTimeout = props.getProperty(Splash.TIMEOUT); if (splashTimeout != null) { _config.getSplash().setTimeout(Integer.parseInt(splashTimeout)); } _config.getSplash().setTimeoutErr(""true"".equals( props.getProperty(Splash.TIMEOUT_ERR))); } else { _config.setSplash(null); } setConfigPath(f); } catch (IOException e) { throw new ConfigPersisterException(e); } } public void save(File f) throws ConfigPersisterException { try { BufferedWriter w = new BufferedWriter(new FileWriter(f)); _xstream.toXML(_config, w); w.close(); setConfigPath(f); } catch (Exception e) { throw new ConfigPersisterException(e); } } private void setConfigPath(File configFile) { _configPath = configFile.getAbsoluteFile().getParentFile(); } private class Props { final Properties _properties = new Properties(); public Props(File f) throws IOException { FileInputStream is = null; try { is = new FileInputStream(f); _properties.load(is); } finally { Util.close(is); } } /** * Get property and remove trailing # comments. */ public String getProperty(String key) { String p = _properties.getProperty(key); if (p == null) { return null; } int x = p.indexOf('#'); if (x == -1) { return p; } do { x--; } while (x > 0 && (p.charAt(x) == ' ' || p.charAt(x) == '\t')); return (x == 0) ? """" : p.substring(0, x + 1); } public File getFile(String key) { String value = getProperty(key); return value != null ? new File(value) : null; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/Jre.java",".java","8340","236","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 21, 2005 */ package net.sf.launch4j.config; import java.util.Arrays; import java.util.List; import net.sf.launch4j.binding.IValidatable; import net.sf.launch4j.binding.Validator; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class Jre implements IValidatable { // 1.x config properties_____________________________________________________________ public static final String PATH = ""jrepath""; public static final String MIN_VERSION = ""javamin""; public static final String MAX_VERSION = ""javamax""; public static final String ARGS = ""jvmArgs""; // __________________________________________________________________________________ public static final String VERSION_PATTERN = ""(\\d\\.){2}\\d(_\\d+)?""; public static final String JDK_PREFERENCE_JRE_ONLY = ""jreOnly""; public static final String JDK_PREFERENCE_PREFER_JRE = ""preferJre""; public static final String JDK_PREFERENCE_PREFER_JDK = ""preferJdk""; public static final String JDK_PREFERENCE_JDK_ONLY = ""jdkOnly""; private static final String[] JDK_PREFERENCE_NAMES = new String[] { JDK_PREFERENCE_JRE_ONLY, JDK_PREFERENCE_PREFER_JRE, JDK_PREFERENCE_PREFER_JDK, JDK_PREFERENCE_JDK_ONLY }; public static final int DEFAULT_JDK_PREFERENCE_INDEX = Arrays.asList(JDK_PREFERENCE_NAMES).indexOf(JDK_PREFERENCE_PREFER_JRE); private String path; private String minVersion; private String maxVersion; private String jdkPreference; private Integer initialHeapSize; private Integer initialHeapPercent; private Integer maxHeapSize; private Integer maxHeapPercent; private List options; public void checkInvariants() { Validator.checkOptString(minVersion, 10, VERSION_PATTERN, ""jre.minVersion"", Messages.getString(""Jre.min.version"")); Validator.checkOptString(maxVersion, 10, VERSION_PATTERN, ""jre.maxVersion"", Messages.getString(""Jre.max.version"")); if (Validator.isEmpty(path)) { Validator.checkFalse(Validator.isEmpty(minVersion), ""jre.minVersion"", Messages.getString(""Jre.specify.jre.min.version.or.path"")); } else { Validator.checkString(path, Validator.MAX_PATH, ""jre.path"", Messages.getString(""Jre.bundled.path"")); } if (!Validator.isEmpty(maxVersion)) { Validator.checkFalse(Validator.isEmpty(minVersion), ""jre.minVersion"", Messages.getString(""Jre.specify.min.version"")); Validator.checkTrue(minVersion.compareTo(maxVersion) < 0, ""jre.maxVersion"", Messages.getString(""Jre.max.greater.than.min"")); } Validator.checkTrue(initialHeapSize == null || maxHeapSize != null, ""jre.maxHeapSize"", Messages.getString(""Jre.initial.and.max.heap"")); Validator.checkTrue(initialHeapSize == null || initialHeapSize.intValue() > 0, ""jre.initialHeapSize"", Messages.getString(""Jre.initial.heap"")); Validator.checkTrue(maxHeapSize == null || (maxHeapSize.intValue() >= ((initialHeapSize != null) ? initialHeapSize.intValue() : 1)), ""jre.maxHeapSize"", Messages.getString(""Jre.max.heap"")); Validator.checkTrue(initialHeapPercent == null || maxHeapPercent != null, ""jre.maxHeapPercent"", Messages.getString(""Jre.initial.and.max.heap"")); if (initialHeapPercent != null) { Validator.checkRange(initialHeapPercent.intValue(), 1, 100, ""jre.initialHeapPercent"", Messages.getString(""Jre.initial.heap.percent"")); } if (maxHeapPercent != null) { Validator.checkRange(maxHeapPercent.intValue(), initialHeapPercent != null ? initialHeapPercent.intValue() : 1, 100, ""jre.maxHeapPercent"", Messages.getString(""Jre.max.heap.percent"")); } Validator.checkIn(getJdkPreference(), JDK_PREFERENCE_NAMES, ""jre.jdkPreference"", Messages.getString(""Jre.jdkPreference.invalid"")); Validator.checkOptStrings(options, Validator.MAX_ARGS, Validator.MAX_ARGS, ""[^\""]*|([^\""]*\""[^\""]*\""[^\""]*)*"", ""jre.options"", Messages.getString(""Jre.jvm.options""), Messages.getString(""Jre.jvm.options.unclosed.quotation"")); // Quoted variable references: ""[^%]*|([^%]*\""([^%]*%[^%]+%[^%]*)+\""[^%]*)*"" Validator.checkOptStrings(options, Validator.MAX_ARGS, Validator.MAX_ARGS, ""[^%]*|([^%]*([^%]*%[^%]+%[^%]*)+[^%]*)*"", ""jre.options"", Messages.getString(""Jre.jvm.options""), Messages.getString(""Jre.jvm.options.variable"")); } /** JVM options */ public List getOptions() { return options; } public void setOptions(List options) { this.options = options; } /** Max Java version (x.x.x) */ public String getMaxVersion() { return maxVersion; } public void setMaxVersion(String maxVersion) { this.maxVersion = maxVersion; } /** Min Java version (x.x.x) */ public String getMinVersion() { return minVersion; } public void setMinVersion(String minVersion) { this.minVersion = minVersion; } /** Preference for standalone JRE or JDK-private JRE */ public String getJdkPreference() { return Validator.isEmpty(jdkPreference) ? JDK_PREFERENCE_PREFER_JRE : jdkPreference; } public void setJdkPreference(String jdkPreference) { this.jdkPreference = jdkPreference; } /** Preference for standalone JRE or JDK-private JRE */ public int getJdkPreferenceIndex() { int x = Arrays.asList(JDK_PREFERENCE_NAMES).indexOf(getJdkPreference()); return x != -1 ? x : DEFAULT_JDK_PREFERENCE_INDEX; } public void setJdkPreferenceIndex(int x) { jdkPreference = JDK_PREFERENCE_NAMES[x]; } /** JRE path */ public String getPath() { return path; } public void setPath(String path) { this.path = path; } /** Initial heap size in MB */ public Integer getInitialHeapSize() { return initialHeapSize; } public void setInitialHeapSize(Integer initialHeapSize) { this.initialHeapSize = getInteger(initialHeapSize); } /** Max heap size in MB */ public Integer getMaxHeapSize() { return maxHeapSize; } public void setMaxHeapSize(Integer maxHeapSize) { this.maxHeapSize = getInteger(maxHeapSize); } public Integer getInitialHeapPercent() { return initialHeapPercent; } public void setInitialHeapPercent(Integer initialHeapPercent) { this.initialHeapPercent = getInteger(initialHeapPercent); } public Integer getMaxHeapPercent() { return maxHeapPercent; } public void setMaxHeapPercent(Integer maxHeapPercent) { this.maxHeapPercent = getInteger(maxHeapPercent); } /** Convert 0 to null */ private Integer getInteger(Integer i) { return i != null && i.intValue() == 0 ? null : i; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/ClassPath.java",".java","2866","88","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.config; import java.util.List; import net.sf.launch4j.binding.IValidatable; import net.sf.launch4j.binding.Validator; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class ClassPath implements IValidatable { private String mainClass; private List paths; public void checkInvariants() { Validator.checkString(mainClass, Validator.MAX_PATH, ""mainClass"", Messages.getString(""ClassPath.mainClass"")); Validator.checkOptStrings(paths, Validator.MAX_PATH, Validator.MAX_BIG_STR, ""paths"", Messages.getString(""ClassPath.path"")); } public String getMainClass() { return mainClass; } public void setMainClass(String mainClass) { this.mainClass = mainClass; } public List getPaths() { return paths; } public void setPaths(List paths) { this.paths = paths; } public String getPathsString() { StringBuffer sb = new StringBuffer(); for (int i = 0; i < paths.size(); i++) { sb.append(paths.get(i)); if (i < paths.size() - 1) { sb.append(';'); } } return sb.toString(); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/config/Splash.java",".java","3541","104","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 21, 2005 */ package net.sf.launch4j.config; import java.io.File; import net.sf.launch4j.binding.IValidatable; import net.sf.launch4j.binding.Validator; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class Splash implements IValidatable { // 1.x config properties_____________________________________________________________ public static final String SPLASH_FILE = ""splash""; public static final String WAIT_FOR_TITLE = ""waitForTitle""; public static final String TIMEOUT = ""splashTimeout""; public static final String TIMEOUT_ERR = ""splashTimeoutErr""; // __________________________________________________________________________________ private File file; private boolean waitForWindow = true; private int timeout = 60; private boolean timeoutErr = true; public void checkInvariants() { Validator.checkFile(file, ""splash.file"", Messages.getString(""Splash.splash.file"")); Validator.checkRange(timeout, 1, 60 * 15, ""splash.timeout"", Messages.getString(""Splash.splash.timeout"")); } /** Splash screen in BMP format. */ public File getFile() { return file; } public void setFile(File file) { this.file = file; } /** Splash timeout in seconds. */ public int getTimeout() { return timeout; } public void setTimeout(int timeout) { this.timeout = timeout; } /** Signal error on splash timeout. */ public boolean isTimeoutErr() { return timeoutErr; } public void setTimeoutErr(boolean timeoutErr) { this.timeoutErr = timeoutErr; } /** Hide splash screen when the child process displayes the first window. */ public boolean getWaitForWindow() { return waitForWindow; } public void setWaitForWindow(boolean waitForWindow) { this.waitForWindow = waitForWindow; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/Bindings.java",".java","9840","318","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 30, 2005 */ package net.sf.launch4j.binding; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JList; import javax.swing.JRadioButton; import javax.swing.JTextArea; import javax.swing.JToggleButton; import javax.swing.text.JTextComponent; import org.apache.commons.beanutils.PropertyUtils; /** * Creates and handles bindings. * * @author Copyright (C) 2005 Grzegorz Kowal */ public class Bindings implements PropertyChangeListener { private final Map _bindings = new HashMap(); private final Map _optComponents = new HashMap(); private boolean _modified = false; /** * Used to track component modifications. */ public void propertyChange(PropertyChangeEvent evt) { String prop = evt.getPropertyName(); if (""AccessibleValue"".equals(prop) || ""AccessibleText"".equals(prop) || ""AccessibleVisibleData"".equals(prop)) { _modified = true; } } /** * Any of the components modified? */ public boolean isModified() { return _modified; } public Binding getBinding(String property) { return (Binding) _bindings.get(property); } private void registerPropertyChangeListener(JComponent c) { c.getAccessibleContext().addPropertyChangeListener(this); } private void registerPropertyChangeListener(JComponent[] cs) { for (int i = 0; i < cs.length; i++) { cs[i].getAccessibleContext().addPropertyChangeListener(this); } } private boolean isPropertyNull(IValidatable bean, Binding b) { try { for (Iterator iter = _optComponents.keySet().iterator(); iter.hasNext();) { String property = (String) iter.next(); if (b.getProperty().startsWith(property)) { return PropertyUtils.getProperty(bean, property) == null; } } return false; } catch (Exception e) { throw new BindingException(e); } } /** * Enables or disables all components bound to properties that begin with given prefix. */ public void setComponentsEnabled(String prefix, boolean enabled) { for (Iterator iter = _bindings.values().iterator(); iter.hasNext();) { Binding b = (Binding) iter.next(); if (b.getProperty().startsWith(prefix)) { b.setEnabled(enabled); } } } /** * Clear all components, set them to their default values. * Clears the _modified flag. */ public void clear(IValidatable bean) { for (Iterator iter = _optComponents.values().iterator(); iter.hasNext();) { ((Binding) iter.next()).clear(bean); } for (Iterator iter = _bindings.values().iterator(); iter.hasNext();) { ((Binding) iter.next()).clear(bean); } _modified = false; } /** * Copies data from the Java Bean to the UI components. * Clears the _modified flag. */ public void put(IValidatable bean) { for (Iterator iter = _optComponents.values().iterator(); iter.hasNext();) { ((Binding) iter.next()).put(bean); } for (Iterator iter = _bindings.values().iterator(); iter.hasNext();) { Binding b = (Binding) iter.next(); if (isPropertyNull(bean, b)) { b.clear(null); } else { b.put(bean); } } _modified = false; } /** * Copies data from UI components to the Java Bean and checks it's class invariants. * Clears the _modified flag. * @throws InvariantViolationException * @throws BindingException */ public void get(IValidatable bean) { try { for (Iterator iter = _optComponents.values().iterator(); iter.hasNext();) { ((Binding) iter.next()).get(bean); } for (Iterator iter = _bindings.values().iterator(); iter.hasNext();) { Binding b = (Binding) iter.next(); if (!isPropertyNull(bean, b)) { b.get(bean); } } bean.checkInvariants(); for (Iterator iter = _optComponents.keySet().iterator(); iter.hasNext();) { String property = (String) iter.next(); IValidatable component = (IValidatable) PropertyUtils.getProperty(bean, property); if (component != null) { component.checkInvariants(); } } _modified = false; // XXX } catch (InvariantViolationException e) { e.setBinding(getBinding(e.getProperty())); throw e; } catch (Exception e) { throw new BindingException(e); } } private Bindings add(Binding b) { if (_bindings.containsKey(b.getProperty())) { throw new BindingException(Messages.getString(""Bindings.duplicate.binding"")); } _bindings.put(b.getProperty(), b); return this; } /** * Add an optional (nullable) Java Bean component of type clazz. */ public Bindings addOptComponent(String property, Class clazz, JToggleButton c, boolean enabledByDefault) { Binding b = new OptComponentBinding(this, property, clazz, c, enabledByDefault); if (_optComponents.containsKey(property)) { throw new BindingException(Messages.getString(""Bindings.duplicate.binding"")); } _optComponents.put(property, b); return this; } /** * Add an optional (nullable) Java Bean component of type clazz. */ public Bindings addOptComponent(String property, Class clazz, JToggleButton c) { return addOptComponent(property, clazz, c, false); } /** * Handles JEditorPane, JTextArea, JTextField */ public Bindings add(String property, JTextComponent c, String defaultValue) { registerPropertyChangeListener(c); return add(new JTextComponentBinding(property, c, defaultValue)); } /** * Handles JEditorPane, JTextArea, JTextField */ public Bindings add(String property, JTextComponent c) { registerPropertyChangeListener(c); return add(new JTextComponentBinding(property, c, """")); } /** * Handles JToggleButton, JCheckBox */ public Bindings add(String property, JToggleButton c, boolean defaultValue) { registerPropertyChangeListener(c); return add(new JToggleButtonBinding(property, c, defaultValue)); } /** * Handles JToggleButton, JCheckBox */ public Bindings add(String property, JToggleButton c) { registerPropertyChangeListener(c); return add(new JToggleButtonBinding(property, c, false)); } /** * Handles JRadioButton */ public Bindings add(String property, JRadioButton[] cs, int defaultValue) { registerPropertyChangeListener(cs); return add(new JRadioButtonBinding(property, cs, defaultValue)); } /** * Handles JRadioButton */ public Bindings add(String property, JRadioButton[] cs) { registerPropertyChangeListener(cs); return add(new JRadioButtonBinding(property, cs, 0)); } /** * Handles JTextArea */ public Bindings add(String property, JTextArea textArea, String defaultValue) { registerPropertyChangeListener(textArea); return add(new JTextComponentBinding(property, textArea, defaultValue)); } /** * Handles JTextArea lists */ public Bindings add(String property, JTextArea textArea) { registerPropertyChangeListener(textArea); return add(new JTextAreaBinding(property, textArea)); } /** * Handles Optional JTextArea lists */ public Bindings add(String property, String stateProperty, JToggleButton button, JTextArea textArea) { registerPropertyChangeListener(button); registerPropertyChangeListener(textArea); return add(new OptJTextAreaBinding(property, stateProperty, button, textArea)); } /** * Handles JList */ public Bindings add(String property, JList list) { registerPropertyChangeListener(list); return add(new JListBinding(property, list)); } /** * Handles JComboBox */ public Bindings add(String property, JComboBox combo, int defaultValue) { registerPropertyChangeListener(combo); return add(new JComboBoxBinding(property, combo, defaultValue)); } /** * Handles JComboBox */ public Bindings add(String property, JComboBox combo) { registerPropertyChangeListener(combo); return add(new JComboBoxBinding(property, combo, 0)); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/IValidatable.java",".java","1906","45","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on 2004-01-30 */ package net.sf.launch4j.binding; /** * @author Copyright (C) 2004 Grzegorz Kowal */ public interface IValidatable { public void checkInvariants(); } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/Validator.java",".java","8461","260","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on 2004-01-30 */ package net.sf.launch4j.binding; import java.io.File; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.List; import net.sf.launch4j.Util; import net.sf.launch4j.config.ConfigPersister; /** * @author Copyright (C) 2004 Grzegorz Kowal */ public class Validator { public static final String ALPHANUMERIC_PATTERN = ""[\\w]*?""; public static final String ALPHA_PATTERN = ""[\\w&&\\D]*?""; public static final String NUMERIC_PATTERN = ""[\\d]*?""; public static final String PATH_PATTERN = ""[\\w|[ .,:\\-/\\\\]]*?""; public static final int MAX_STR = 128; public static final int MAX_PATH = 260; public static final int MAX_BIG_STR = 8192; // or 16384; public static final int MAX_ARGS = 32767 - 2048; private Validator() {} public static boolean isEmpty(String s) { return s == null || s.equals(""""); } public static void checkNotNull(Object o, String property, String name) { if (o == null) { signalViolation(property, Messages.getString(""Validator.empty.field"", name)); } } public static void checkString(String s, int maxLength, String property, String name) { if (s == null || s.length() == 0) { signalViolation(property, Messages.getString(""Validator.empty.field"", name)); } if (s.length() > maxLength) { signalLengthViolation(property, name, maxLength); } } public static void checkOptStrings(List strings, int maxLength, int totalMaxLength, String property, String name) { if (strings == null) { return; } int totalLength = 0; for (Iterator iter = strings.iterator(); iter.hasNext();) { String s = (String) iter.next(); checkString(s, maxLength, property, name); totalLength += s.length(); if (totalLength > totalMaxLength) { signalLengthViolation(property, name, totalMaxLength); } } } public static void checkString(String s, int maxLength, String pattern, String property, String name) { checkString(s, maxLength, property, name); if (!s.matches(pattern)) { signalViolation(property, Messages.getString(""Validator.invalid.data"", name)); } } public static void checkOptStrings(List strings, int maxLength, int totalMaxLength, String pattern, String property, String name, String msg) { if (strings == null) { return; } int totalLength = 0; for (Iterator iter = strings.iterator(); iter.hasNext();) { String s = (String) iter.next(); checkString(s, maxLength, property, name); if (!s.matches(pattern)) { signalViolation(property, msg != null ? msg : Messages.getString(""Validator.invalid.data"", name)); } totalLength += s.length(); if (totalLength > totalMaxLength) { signalLengthViolation(property, name, totalMaxLength); } } } public static void checkOptString(String s, int maxLength, String property, String name) { if (s == null || s.length() == 0) { return; } if (s.length() > maxLength) { signalLengthViolation(property, name, maxLength); } } public static void checkOptString(String s, int maxLength, String pattern, String property, String name) { if (s == null || s.length() == 0) { return; } if (s.length() > maxLength) { signalLengthViolation(property, name, maxLength); } if (!s.matches(pattern)) { signalViolation(property, Messages.getString(""Validator.invalid.data"", name)); } } public static void checkRange(int value, int min, int max, String property, String name) { if (value < min || value > max) { signalViolation(property, Messages.getString(""Validator.must.be.in.range"", name, String.valueOf(min), String.valueOf(max))); } } public static void checkRange(char value, char min, char max, String property, String name) { if (value < min || value > max) { signalViolation(property, Messages.getString(""Validator.must.be.in.range"", name, String.valueOf(min), String.valueOf(max))); } } public static void checkMin(int value, int min, String property, String name) { if (value < min) { signalViolation(property, Messages.getString(""Validator.must.be.at.least"", name, String.valueOf(min))); } } public static void checkIn(String s, String[] strings, String property, String name) { if (isEmpty(s)) { signalViolation(property, Messages.getString(""Validator.empty.field"", name)); } List list = Arrays.asList(strings); if (!list.contains(s)) { signalViolation(property, Messages.getString(""Validator.invalid.option"", name, list.toString())); } } public static void checkTrue(boolean condition, String property, String msg) { if (!condition) { signalViolation(property, msg); } } public static void checkFalse(boolean condition, String property, String msg) { if (condition) { signalViolation(property, msg); } } public static void checkElementsNotNullUnique(Collection c, String property, String msg) { if (c.contains(null) || new HashSet(c).size() != c.size()) { signalViolation(property, Messages.getString(""Validator.already.exists"", msg)); } } public static void checkElementsUnique(Collection c, String property, String msg) { if (new HashSet(c).size() != c.size()) { signalViolation(property, Messages.getString(""Validator.already.exists"", msg)); } } public static void checkFile(File f, String property, String fileDescription) { File cfgPath = ConfigPersister.getInstance().getConfigPath(); if (f == null || f.getPath().equals("""") || (!f.exists() && !Util.getAbsoluteFile(cfgPath, f).exists())) { signalViolation(property, Messages.getString(""Validator.doesnt.exist"", fileDescription)); } } public static void checkOptFile(File f, String property, String fileDescription) { if (f != null && f.getPath().length() > 0) { checkFile(f, property, fileDescription); } } public static void checkRelativeWinPath(String path, String property, String msg) { if (path == null || path.equals("""") || path.startsWith(""/"") || path.startsWith(""\\"") || path.indexOf(':') != -1) { signalViolation(property, msg); } } public static void signalLengthViolation(String property, String name, int maxLength) { signalViolation(property, Messages.getString(""Validator.exceeds.max.length"", name, String.valueOf(maxLength))); } public static void signalViolation(String property, String msg) { throw new InvariantViolationException(property, msg); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/JRadioButtonBinding.java",".java","4624","147","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 10, 2005 */ package net.sf.launch4j.binding; import java.awt.Color; import javax.swing.JRadioButton; import org.apache.commons.beanutils.PropertyUtils; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class JRadioButtonBinding implements Binding { private final String _property; private final JRadioButton[] _buttons; private final int _defaultValue; private final Color _validColor; public JRadioButtonBinding(String property, JRadioButton[] buttons, int defaultValue) { if (property == null || buttons == null) { throw new NullPointerException(); } for (int i = 0; i < buttons.length; i++) { if (buttons[i] == null) { throw new NullPointerException(); } } if (property.equals("""") || buttons.length == 0 || defaultValue < 0 || defaultValue >= buttons.length) { throw new IllegalArgumentException(); } _property = property; _buttons = buttons; _defaultValue = defaultValue; _validColor = buttons[0].getBackground(); } public String getProperty() { return _property; } public void clear(IValidatable bean) { select(_defaultValue); } public void put(IValidatable bean) { try { Integer i = (Integer) PropertyUtils.getProperty(bean, _property); if (i == null) { throw new BindingException( Messages.getString(""JRadioButtonBinding.property.null"")); } select(i.intValue()); } catch (Exception e) { throw new BindingException(e); } } public void get(IValidatable bean) { try { for (int i = 0; i < _buttons.length; i++) { if (_buttons[i].isSelected()) { PropertyUtils.setProperty(bean, _property, new Integer(i)); return; } } throw new BindingException( Messages.getString(""JRadioButtonBinding.nothing.selected"")); } catch (Exception e) { throw new BindingException(e); } } private void select(int index) { if (index < 0 || index >= _buttons.length) { throw new BindingException( Messages.getString(""JRadioButtonBinding.index.out.of.bounds"")); } _buttons[index].setSelected(true); } public void markValid() { for (int i = 0; i < _buttons.length; i++) { if (_buttons[i].isSelected()) { _buttons[i].setBackground(_validColor); _buttons[i].requestFocusInWindow(); return; } } throw new BindingException( Messages.getString(""JRadioButtonBinding.nothing.selected"")); } public void markInvalid() { for (int i = 0; i < _buttons.length; i++) { if (_buttons[i].isSelected()) { _buttons[i].setBackground(Binding.INVALID_COLOR); return; } } throw new BindingException( Messages.getString(""JRadioButtonBinding.nothing.selected"")); } public void setEnabled(boolean enabled) { for (int i = 0; i < _buttons.length; i++) { _buttons[i].setEnabled(enabled); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/JListBinding.java",".java","3729","119","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 1, 2006 */ package net.sf.launch4j.binding; import java.awt.Color; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JList; import org.apache.commons.beanutils.PropertyUtils; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class JListBinding implements Binding { private final String _property; private final JList _list; private final Color _validColor; public JListBinding(String property, JList list) { if (property == null || list == null) { throw new NullPointerException(); } if (property.equals("""")) { throw new IllegalArgumentException(); } _property = property; _list = list; _validColor = _list.getBackground(); } public String getProperty() { return _property; } public void clear(IValidatable bean) { _list.setModel(new DefaultListModel()); } public void put(IValidatable bean) { try { DefaultListModel model = new DefaultListModel(); List list = (List) PropertyUtils.getProperty(bean, _property); if (list != null) { for (Iterator iter = list.iterator(); iter.hasNext();) { model.addElement(iter.next()); } } _list.setModel(model); } catch (Exception e) { throw new BindingException(e); } } public void get(IValidatable bean) { try { DefaultListModel model = (DefaultListModel) _list.getModel(); final int size = model.getSize(); List list = new ArrayList(size); for (int i = 0; i < size; i++) { list.add(model.get(i)); } PropertyUtils.setProperty(bean, _property, list); } catch (Exception e) { throw new BindingException(e); } } public void markValid() { _list.setBackground(_validColor); _list.requestFocusInWindow(); } public void markInvalid() { _list.setBackground(Binding.INVALID_COLOR); } public void setEnabled(boolean enabled) { _list.setEnabled(enabled); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/Messages.java",".java","2994","79","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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 net.sf.launch4j.binding; import java.text.MessageFormat; import java.util.MissingResourceException; import java.util.ResourceBundle; public class Messages { private static final String BUNDLE_NAME = ""net.sf.launch4j.binding.messages""; private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle .getBundle(BUNDLE_NAME); private static final MessageFormat FORMATTER = new MessageFormat(""""); private Messages() { } public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } public static String getString(String key, String arg0) { return getString(key, new Object[] {arg0}); } public static String getString(String key, String arg0, String arg1) { return getString(key, new Object[] {arg0, arg1}); } public static String getString(String key, String arg0, String arg1, String arg2) { return getString(key, new Object[] {arg0, arg1, arg2}); } public static String getString(String key, Object[] args) { try { FORMATTER.applyPattern(RESOURCE_BUNDLE.getString(key)); return FORMATTER.format(args); } catch (MissingResourceException e) { return '!' + key + '!'; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/JTextComponentBinding.java",".java","3594","109","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 30, 2005 */ package net.sf.launch4j.binding; import java.awt.Color; import javax.swing.text.JTextComponent; import org.apache.commons.beanutils.BeanUtils; /** * Handles JEditorPane, JTextArea, JTextField * * @author Copyright (C) 2005 Grzegorz Kowal */ public class JTextComponentBinding implements Binding { private final String _property; private final JTextComponent _textComponent; private final String _defaultValue; private final Color _validColor; public JTextComponentBinding(String property, JTextComponent textComponent, String defaultValue) { if (property == null || textComponent == null || defaultValue == null) { throw new NullPointerException(); } if (property.equals("""")) { throw new IllegalArgumentException(); } _property = property; _textComponent = textComponent; _defaultValue = defaultValue; _validColor = _textComponent.getBackground(); } public String getProperty() { return _property; } public void clear(IValidatable bean) { _textComponent.setText(_defaultValue); } public void put(IValidatable bean) { try { String s = BeanUtils.getProperty(bean, _property); // XXX displays zeros as blank _textComponent.setText(s != null && !s.equals(""0"") ? s : """"); } catch (Exception e) { throw new BindingException(e); } } public void get(IValidatable bean) { try { BeanUtils.setProperty(bean, _property, _textComponent.getText()); } catch (Exception e) { throw new BindingException(e); } } public void markValid() { _textComponent.setBackground(_validColor); _textComponent.requestFocusInWindow(); } public void markInvalid() { _textComponent.setBackground(Binding.INVALID_COLOR); } public void setEnabled(boolean enabled) { _textComponent.setEnabled(enabled); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/JComboBoxBinding.java",".java","3678","120","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2007 Ian Roberts All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 10, 2005 */ package net.sf.launch4j.binding; import java.awt.Color; import javax.swing.JComboBox; import org.apache.commons.beanutils.PropertyUtils; /** * @author Copyright (C) 2007 Ian Roberts */ public class JComboBoxBinding implements Binding { private final String _property; private final JComboBox _combo; private final int _defaultValue; private final Color _validColor; public JComboBoxBinding(String property, JComboBox combo, int defaultValue) { if (property == null || combo == null) { throw new NullPointerException(); } if (property.equals("""") || combo.getItemCount() == 0 || defaultValue < 0 || defaultValue >= combo.getItemCount()) { throw new IllegalArgumentException(); } _property = property; _combo = combo; _defaultValue = defaultValue; _validColor = combo.getBackground(); } public String getProperty() { return _property; } public void clear(IValidatable bean) { select(_defaultValue); } public void put(IValidatable bean) { try { Integer i = (Integer) PropertyUtils.getProperty(bean, _property); if (i == null) { throw new BindingException( Messages.getString(""JComboBoxBinding.property.null"")); } select(i.intValue()); } catch (Exception e) { throw new BindingException(e); } } public void get(IValidatable bean) { try { PropertyUtils.setProperty(bean, _property, new Integer(_combo.getSelectedIndex())); return; } catch (Exception e) { throw new BindingException(e); } } private void select(int index) { if (index < 0 || index >= _combo.getItemCount()) { throw new BindingException( Messages.getString(""JComboBoxBinding.index.out.of.bounds"")); } _combo.setSelectedIndex(index); } public void markValid() { _combo.setBackground(_validColor); _combo.requestFocusInWindow(); } public void markInvalid() { _combo.setBackground(Binding.INVALID_COLOR); } public void setEnabled(boolean enabled) { _combo.setEnabled(enabled); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/BindingException.java",".java","2101","53","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 30, 2005 */ package net.sf.launch4j.binding; /** * Signals a runtime error, a missing property in a Java Bean for example. * * @author Copyright (C) 2005 Grzegorz Kowal */ public class BindingException extends RuntimeException { public BindingException(Throwable t) { super(t); } public BindingException(String msg) { super(msg); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/JToggleButtonBinding.java",".java","3476","109","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 30, 2005 */ package net.sf.launch4j.binding; import java.awt.Color; import javax.swing.JToggleButton; import org.apache.commons.beanutils.PropertyUtils; /** * Handles JToggleButton, JCheckBox * * @author Copyright (C) 2005 Grzegorz Kowal */ public class JToggleButtonBinding implements Binding { private final String _property; private final JToggleButton _button; private final boolean _defaultValue; private final Color _validColor; public JToggleButtonBinding(String property, JToggleButton button, boolean defaultValue) { if (property == null || button == null) { throw new NullPointerException(); } if (property.equals("""")) { throw new IllegalArgumentException(); } _property = property; _button = button; _defaultValue = defaultValue; _validColor = _button.getBackground(); } public String getProperty() { return _property; } public void clear(IValidatable bean) { _button.setSelected(_defaultValue); } public void put(IValidatable bean) { try { Boolean b = (Boolean) PropertyUtils.getProperty(bean, _property); _button.setSelected(b != null && b.booleanValue()); } catch (Exception e) { throw new BindingException(e); } } public void get(IValidatable bean) { try { PropertyUtils.setProperty(bean, _property, Boolean.valueOf(_button.isSelected())); } catch (Exception e) { throw new BindingException(e); } } public void markValid() { _button.setBackground(_validColor); _button.requestFocusInWindow(); } public void markInvalid() { _button.setBackground(Binding.INVALID_COLOR); } public void setEnabled(boolean enabled) { _button.setEnabled(enabled); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/Binding.java",".java","2547","63","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Apr 30, 2005 */ package net.sf.launch4j.binding; import java.awt.Color; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public interface Binding { /** Used to mark components with invalid data. */ public final static Color INVALID_COLOR = Color.PINK; /** Java Bean property bound to a component */ public String getProperty(); /** Clear component, set it to the default value */ public void clear(IValidatable bean); /** Java Bean property -> Component */ public void put(IValidatable bean); /** Component -> Java Bean property */ public void get(IValidatable bean); /** Mark component as valid */ public void markValid(); /** Mark component as invalid */ public void markInvalid(); /** Enable or disable the component */ public void setEnabled(boolean enabled); } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/OptJTextAreaBinding.java",".java","4516","142","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Sep 3, 2005 */ package net.sf.launch4j.binding; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JTextArea; import javax.swing.JToggleButton; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.beanutils.PropertyUtils; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class OptJTextAreaBinding implements Binding, ActionListener { private final String _property; private final String _stateProperty; private final JToggleButton _button; private final JTextArea _textArea; private final Color _validColor; public OptJTextAreaBinding(String property, String stateProperty, JToggleButton button, JTextArea textArea) { if (property == null || button == null || textArea == null) { throw new NullPointerException(); } if (property.equals("""")) { throw new IllegalArgumentException(); } _property = property; _stateProperty = stateProperty; _button = button; _textArea = textArea; _validColor = _textArea.getBackground(); button.addActionListener(this); } public String getProperty() { return _property; } public void clear(IValidatable bean) { put(bean); } public void put(IValidatable bean) { try { boolean selected = ""true"".equals(BeanUtils.getProperty(bean, _stateProperty)); _button.setSelected(selected); _textArea.setEnabled(selected); List list = (List) PropertyUtils.getProperty(bean, _property); StringBuffer sb = new StringBuffer(); if (list != null) { for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i < list.size() - 1) { sb.append(""\n""); } } } _textArea.setText(sb.toString()); } catch (Exception e) { throw new BindingException(e); } } public void get(IValidatable bean) { try { String text = _textArea.getText(); if (_button.isSelected() && !text.equals("""")) { String[] items = text.split(""\n""); List list = new ArrayList(); for (int i = 0; i < items.length; i++) { list.add(items[i]); } PropertyUtils.setProperty(bean, _property, list); } else { PropertyUtils.setProperty(bean, _property, null); } } catch (Exception e) { throw new BindingException(e); } } public void markValid() { _textArea.setBackground(_validColor); _textArea.requestFocusInWindow(); } public void markInvalid() { _textArea.setBackground(Binding.INVALID_COLOR); } public void setEnabled(boolean enabled) { _textArea.setEnabled(enabled); } public void actionPerformed(ActionEvent e) { _textArea.setEnabled(_button.isSelected()); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/InvariantViolationException.java",".java","2372","68","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Jun 23, 2003 */ package net.sf.launch4j.binding; /** * @author Copyright (C) 2003 Grzegorz Kowal */ public class InvariantViolationException extends RuntimeException { private final String _property; private Binding _binding; public InvariantViolationException(String msg) { super(msg); _property = null; } public InvariantViolationException(String property, String msg) { super(msg); _property = property; } public String getProperty() { return _property; } public Binding getBinding() { return _binding; } public void setBinding(Binding binding) { _binding = binding; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/JTextAreaBinding.java",".java","3817","124","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on Jun 14, 2006 */ package net.sf.launch4j.binding; import java.awt.Color; import java.util.ArrayList; import java.util.List; import javax.swing.JTextArea; import org.apache.commons.beanutils.PropertyUtils; /** * @author Copyright (C) 2006 Grzegorz Kowal */ public class JTextAreaBinding implements Binding { private final String _property; private final JTextArea _textArea; private final Color _validColor; public JTextAreaBinding(String property, JTextArea textArea) { if (property == null || textArea == null) { throw new NullPointerException(); } if (property.equals("""")) { throw new IllegalArgumentException(); } _property = property; _textArea = textArea; _validColor = _textArea.getBackground(); } public String getProperty() { return _property; } public void clear(IValidatable bean) { put(bean); } public void put(IValidatable bean) { try { List list = (List) PropertyUtils.getProperty(bean, _property); StringBuffer sb = new StringBuffer(); if (list != null) { for (int i = 0; i < list.size(); i++) { sb.append(list.get(i)); if (i < list.size() - 1) { sb.append(""\n""); } } } _textArea.setText(sb.toString()); } catch (Exception e) { throw new BindingException(e); } } public void get(IValidatable bean) { try { String text = _textArea.getText(); if (!text.equals("""")) { String[] items = text.split(""\n""); List list = new ArrayList(); for (int i = 0; i < items.length; i++) { list.add(items[i]); } PropertyUtils.setProperty(bean, _property, list); } else { PropertyUtils.setProperty(bean, _property, null); } } catch (Exception e) { throw new BindingException(e); } } public void markValid() { _textArea.setBackground(_validColor); _textArea.requestFocusInWindow(); } public void markInvalid() { _textArea.setBackground(Binding.INVALID_COLOR); } public void setEnabled(boolean enabled) { _textArea.setEnabled(enabled); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/src/net/sf/launch4j/binding/OptComponentBinding.java",".java","3966","120","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of the Launch4j nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 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 OWNER 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. */ /* * Created on May 11, 2005 */ package net.sf.launch4j.binding; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Arrays; import javax.swing.JToggleButton; import org.apache.commons.beanutils.PropertyUtils; /** * @author Copyright (C) 2005 Grzegorz Kowal */ public class OptComponentBinding implements Binding, ActionListener { private final Bindings _bindings; private final String _property; private final Class _clazz; private final JToggleButton _button; private final boolean _enabledByDefault; public OptComponentBinding(Bindings bindings, String property, Class clazz, JToggleButton button, boolean enabledByDefault) { if (property == null || clazz == null || button == null) { throw new NullPointerException(); } if (property.equals("""")) { throw new IllegalArgumentException(); } if (!Arrays.asList(clazz.getInterfaces()).contains(IValidatable.class)) { throw new IllegalArgumentException( Messages.getString(""OptComponentBinding.must.implement"") + IValidatable.class); } _bindings = bindings; _property = property; _clazz = clazz; _button = button; _button.addActionListener(this); _enabledByDefault = enabledByDefault; } public String getProperty() { return _property; } public void clear(IValidatable bean) { _button.setSelected(_enabledByDefault); updateComponents(); } public void put(IValidatable bean) { try { Object component = PropertyUtils.getProperty(bean, _property); _button.setSelected(component != null); updateComponents(); } catch (Exception e) { throw new BindingException(e); } } public void get(IValidatable bean) { try { PropertyUtils.setProperty(bean, _property, _button.isSelected() ? _clazz.newInstance() : null); } catch (Exception e) { throw new BindingException(e); } } public void markValid() {} public void markInvalid() {} public void setEnabled(boolean enabled) {} // XXX implement? public void actionPerformed(ActionEvent e) { updateComponents(); } private void updateComponents() { _bindings.setComponentsEnabled(_property, _button.isSelected()); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/head_src/head.c",".c","22283","808","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2008 Grzegorz Kowal, Ian Roberts (jdk preference patch) Sylvain Mina (single instance patch) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include ""resource.h"" #include ""head.h"" HMODULE hModule; FILE* hLog; BOOL console = FALSE; BOOL wow64 = FALSE; int foundJava = NO_JAVA_FOUND; struct _stat statBuf; PROCESS_INFORMATION pi; DWORD priority; char mutexName[STR] = {0}; char errUrl[256] = {0}; char errTitle[STR] = ""Launch4j""; char errMsg[BIG_STR] = {0}; char javaMinVer[STR] = {0}; char javaMaxVer[STR] = {0}; char foundJavaVer[STR] = {0}; char foundJavaKey[_MAX_PATH] = {0}; char oldPwd[_MAX_PATH] = {0}; char workingDir[_MAX_PATH] = {0}; char cmd[_MAX_PATH] = {0}; char args[MAX_ARGS] = {0}; FILE* openLogFile(const char* exePath, const int pathLen) { char path[_MAX_PATH] = {0}; strncpy(path, exePath, pathLen); strcat(path, ""\\launch4j.log""); return fopen(path, ""a""); } void closeLogFile() { if (hLog != NULL) { fclose(hLog); } } void setWow64Flag() { LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress( GetModuleHandle(TEXT(""kernel32"")), ""IsWow64Process""); if (fnIsWow64Process != NULL) { fnIsWow64Process(GetCurrentProcess(), &wow64); } debug(""WOW64:\t\t%s\n"", wow64 ? ""yes"" : ""no""); } void setConsoleFlag() { console = TRUE; } void msgBox(const char* text) { if (console) { printf(""%s: %s\n"", errTitle, text); } else { MessageBox(NULL, text, errTitle, MB_OK); } } void signalError() { DWORD err = GetLastError(); if (err) { LPVOID lpMsgBuf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &lpMsgBuf, 0, NULL); debug(""Error:\t\t%s\n"", (LPCTSTR) lpMsgBuf); strcat(errMsg, ""\n\n""); strcat(errMsg, (LPCTSTR) lpMsgBuf); msgBox(errMsg); LocalFree(lpMsgBuf); } else { msgBox(errMsg); } if (*errUrl) { debug(""Open URL:\t%s\n"", errUrl); ShellExecute(NULL, ""open"", errUrl, NULL, NULL, SW_SHOWNORMAL); } closeLogFile(); } BOOL loadString(const int resID, char* buffer) { HRSRC hResource; HGLOBAL hResourceLoaded; LPBYTE lpBuffer; hResource = FindResourceEx(hModule, RT_RCDATA, MAKEINTRESOURCE(resID), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT)); if (NULL != hResource) { hResourceLoaded = LoadResource(hModule, hResource); if (NULL != hResourceLoaded) { lpBuffer = (LPBYTE) LockResource(hResourceLoaded); if (NULL != lpBuffer) { int x = 0; do { buffer[x] = (char) lpBuffer[x]; } while (buffer[x++] != 0); // debug(""Resource %d:\t%s\n"", resID, buffer); return TRUE; } } } else { SetLastError(0); } return FALSE; } BOOL loadBool(const int resID) { char boolStr[20] = {0}; loadString(resID, boolStr); return strcmp(boolStr, TRUE_STR) == 0; } int loadInt(const int resID) { char intStr[20] = {0}; loadString(resID, intStr); return atoi(intStr); } BOOL regQueryValue(const char* regPath, unsigned char* buffer, unsigned long bufferLength) { HKEY hRootKey; char* key; char* value; if (strstr(regPath, HKEY_CLASSES_ROOT_STR) == regPath) { hRootKey = HKEY_CLASSES_ROOT; } else if (strstr(regPath, HKEY_CURRENT_USER_STR) == regPath) { hRootKey = HKEY_CURRENT_USER; } else if (strstr(regPath, HKEY_LOCAL_MACHINE_STR) == regPath) { hRootKey = HKEY_LOCAL_MACHINE; } else if (strstr(regPath, HKEY_USERS_STR) == regPath) { hRootKey = HKEY_USERS; } else if (strstr(regPath, HKEY_CURRENT_CONFIG_STR) == regPath) { hRootKey = HKEY_CURRENT_CONFIG; } else { return FALSE; } key = strchr(regPath, '\\') + 1; value = strrchr(regPath, '\\') + 1; *(value - 1) = 0; HKEY hKey; unsigned long datatype; BOOL result = FALSE; if ((wow64 && RegOpenKeyEx(hRootKey, key, 0, KEY_READ | KEY_WOW64_64KEY, &hKey) == ERROR_SUCCESS) || RegOpenKeyEx(hRootKey, key, 0, KEY_READ, &hKey) == ERROR_SUCCESS) { result = RegQueryValueEx(hKey, value, NULL, &datatype, buffer, &bufferLength) == ERROR_SUCCESS; RegCloseKey(hKey); } *(value - 1) = '\\'; return result; } void regSearch(const HKEY hKey, const char* keyName, const int searchType) { DWORD x = 0; unsigned long size = BIG_STR; FILETIME time; char buffer[BIG_STR] = {0}; while (RegEnumKeyEx( hKey, // handle to key to enumerate x++, // index of subkey to enumerate buffer, // address of buffer for subkey name &size, // address for size of subkey buffer NULL, // reserved NULL, // address of buffer for class string NULL, // address for size of class buffer &time) == ERROR_SUCCESS) { if (strcmp(buffer, javaMinVer) >= 0 && (!*javaMaxVer || strcmp(buffer, javaMaxVer) <= 0) && strcmp(buffer, foundJavaVer) > 0) { strcpy(foundJavaVer, buffer); strcpy(foundJavaKey, keyName); appendPath(foundJavaKey, buffer); foundJava = searchType; debug(""Match:\t\t%s\\%s\n"", keyName, buffer); } else { debug(""Ignore:\t\t%s\\%s\n"", keyName, buffer); } size = BIG_STR; } } void regSearchWow(const char* keyName, const int searchType) { HKEY hKey; debug(""64-bit search:\t%s...\n"", keyName); if (wow64 && RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_READ | KEY_WOW64_64KEY, &hKey) == ERROR_SUCCESS) { regSearch(hKey, keyName, searchType | KEY_WOW64_64KEY); RegCloseKey(hKey); if ((foundJava & KEY_WOW64_64KEY) != NO_JAVA_FOUND) { debug(""Using 64-bit runtime.\n""); return; } } debug(""32-bit search:\t%s...\n"", keyName); if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, keyName, 0, KEY_READ, &hKey) == ERROR_SUCCESS) { regSearch(hKey, keyName, searchType); RegCloseKey(hKey); } } void regSearchJreSdk(const char* jreKeyName, const char* sdkKeyName, const int jdkPreference) { if (jdkPreference == JDK_ONLY || jdkPreference == PREFER_JDK) { regSearchWow(sdkKeyName, FOUND_SDK); if (jdkPreference != JDK_ONLY) { regSearchWow(jreKeyName, FOUND_JRE); } } else { // jdkPreference == JRE_ONLY or PREFER_JRE regSearchWow(jreKeyName, FOUND_JRE); if (jdkPreference != JRE_ONLY) { regSearchWow(sdkKeyName, FOUND_SDK); } } } BOOL findJavaHome(char* path, const int jdkPreference) { regSearchJreSdk(""SOFTWARE\\JavaSoft\\Java Runtime Environment"", ""SOFTWARE\\JavaSoft\\Java Development Kit"", jdkPreference); if (foundJava == NO_JAVA_FOUND) { regSearchJreSdk(""SOFTWARE\\IBM\\Java2 Runtime Environment"", ""SOFTWARE\\IBM\\Java Development Kit"", jdkPreference); } if (foundJava != NO_JAVA_FOUND) { HKEY hKey; if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, foundJavaKey, 0, KEY_READ | (foundJava & KEY_WOW64_64KEY), &hKey) == ERROR_SUCCESS) { unsigned char buffer[BIG_STR] = {0}; unsigned long bufferlength = BIG_STR; unsigned long datatype; if (RegQueryValueEx(hKey, ""JavaHome"", NULL, &datatype, buffer, &bufferlength) == ERROR_SUCCESS) { int i = 0; do { path[i] = buffer[i]; } while (path[i++] != 0); if (foundJava & FOUND_SDK) { appendPath(path, ""jre""); } RegCloseKey(hKey); return TRUE; } RegCloseKey(hKey); } } return FALSE; } /* * Extract the executable name, returns path length. */ int getExePath(char* exePath) { if (GetModuleFileName(hModule, exePath, _MAX_PATH) == 0) { return -1; } return strrchr(exePath, '\\') - exePath; } void appendPath(char* basepath, const char* path) { if (basepath[strlen(basepath) - 1] != '\\') { strcat(basepath, ""\\""); } strcat(basepath, path); } void appendJavaw(char* jrePath) { if (console) { appendPath(jrePath, ""bin\\java.exe""); } else { appendPath(jrePath, ""bin\\javaw.exe""); } } void appendLauncher(const BOOL setProcName, char* exePath, const int pathLen, char* cmd) { if (setProcName) { char tmpspec[_MAX_PATH]; char tmpfile[_MAX_PATH]; strcpy(tmpspec, cmd); strcat(tmpspec, LAUNCH4J_TMP_DIR); tmpspec[strlen(tmpspec) - 1] = 0; if (_stat(tmpspec, &statBuf) == 0) { // Remove temp launchers and manifests struct _finddata_t c_file; long hFile; appendPath(tmpspec, ""*.exe""); strcpy(tmpfile, cmd); strcat(tmpfile, LAUNCH4J_TMP_DIR); char* filename = tmpfile + strlen(tmpfile); if ((hFile = _findfirst(tmpspec, &c_file)) != -1L) { do { strcpy(filename, c_file.name); debug(""Unlink:\t\t%s\n"", tmpfile); _unlink(tmpfile); strcat(tmpfile, MANIFEST); debug(""Unlink:\t\t%s\n"", tmpfile); _unlink(tmpfile); } while (_findnext(hFile, &c_file) == 0); } _findclose(hFile); } else { if (_mkdir(tmpspec) != 0) { debug(""Mkdir failed:\t%s\n"", tmpspec); appendJavaw(cmd); return; } } char javaw[_MAX_PATH]; strcpy(javaw, cmd); appendJavaw(javaw); strcpy(tmpfile, cmd); strcat(tmpfile, LAUNCH4J_TMP_DIR); char* tmpfilename = tmpfile + strlen(tmpfile); char* exeFilePart = exePath + pathLen + 1; // Copy manifest char manifest[_MAX_PATH] = {0}; strcpy(manifest, exePath); strcat(manifest, MANIFEST); if (_stat(manifest, &statBuf) == 0) { strcat(tmpfile, exeFilePart); strcat(tmpfile, MANIFEST); debug(""Copy:\t\t%s -> %s\n"", manifest, tmpfile); CopyFile(manifest, tmpfile, FALSE); } // Copy launcher strcpy(tmpfilename, exeFilePart); debug(""Copy:\t\t%s -> %s\n"", javaw, tmpfile); if (CopyFile(javaw, tmpfile, FALSE)) { strcpy(cmd, tmpfile); return; } else if (_stat(javaw, &statBuf) == 0) { long fs = statBuf.st_size; if (_stat(tmpfile, &statBuf) == 0 && fs == statBuf.st_size) { debug(""Reusing:\t\t%s\n"", tmpfile); strcpy(cmd, tmpfile); return; } } } appendJavaw(cmd); } void appendAppClasspath(char* dst, const char* src, const char* classpath) { strcat(dst, src); if (*classpath) { strcat(dst, "";""); } } BOOL isJrePathOk(const char* path) { char javaw[_MAX_PATH]; BOOL result = FALSE; if (*path) { strcpy(javaw, path); appendJavaw(javaw); result = _stat(javaw, &statBuf) == 0; } debug(""Check launcher:\t%s %s\n"", javaw, result ? ""(OK)"" : ""(n/a)""); return result; } /* * Expand environment %variables% */ BOOL expandVars(char *dst, const char *src, const char *exePath, const int pathLen) { char varName[STR]; char varValue[MAX_VAR_SIZE]; while (strlen(src) > 0) { char *start = strchr(src, '%'); if (start != NULL) { char *end = strchr(start + 1, '%'); if (end == NULL) { return FALSE; } // Copy content up to %VAR% strncat(dst, src, start - src); // Insert value of %VAR% *varName = 0; strncat(varName, start + 1, end - start - 1); // Remember value start for logging char *varValue = dst + strlen(dst); if (strcmp(varName, ""EXEDIR"") == 0) { strncat(dst, exePath, pathLen); } else if (strcmp(varName, ""EXEFILE"") == 0) { strcat(dst, exePath); } else if (strcmp(varName, ""PWD"") == 0) { GetCurrentDirectory(_MAX_PATH, dst + strlen(dst)); } else if (strcmp(varName, ""OLDPWD"") == 0) { strcat(dst, oldPwd); } else if (strstr(varName, HKEY_STR) == varName) { regQueryValue(varName, dst + strlen(dst), BIG_STR); } else if (GetEnvironmentVariable(varName, varValue, MAX_VAR_SIZE) > 0) { strcat(dst, varValue); } debug(""Substitute:\t%s = %s\n"", varName, varValue); src = end + 1; } else { // Copy remaining content strcat(dst, src); break; } } return TRUE; } void appendHeapSizes(char *dst) { MEMORYSTATUS m; memset(&m, 0, sizeof(m)); GlobalMemoryStatus(&m); appendHeapSize(dst, INITIAL_HEAP_SIZE, INITIAL_HEAP_PERCENT, m.dwAvailPhys, ""-Xms""); appendHeapSize(dst, MAX_HEAP_SIZE, MAX_HEAP_PERCENT, m.dwAvailPhys, ""-Xmx""); } void appendHeapSize(char *dst, const int absID, const int percentID, const DWORD freeMemory, const char *option) { const int mb = 1048576; // 1 MB int abs = loadInt(absID); int percent = loadInt(percentID); int free = (long long) freeMemory * percent / (100 * mb); // 100% * 1 MB int size = free > abs ? free : abs; if (size > 0) { debug(""Heap %s:\t%d MB / %d%%, Free: %d MB, Heap size: %d MB\n"", option, abs, percent, freeMemory / mb, size); strcat(dst, option); _itoa(size, dst + strlen(dst), 10); // 10 -- radix strcat(dst, ""m ""); } } int prepare(const char *lpCmdLine) { char tmp[MAX_ARGS] = {0}; hModule = GetModuleHandle(NULL); if (hModule == NULL) { return FALSE; } // Get executable path char exePath[_MAX_PATH] = {0}; int pathLen = getExePath(exePath); if (pathLen == -1) { return FALSE; } // Initialize logging if (strstr(lpCmdLine, ""--l4j-debug"") != NULL) { hLog = openLogFile(exePath, pathLen); if (hLog == NULL) { return FALSE; } debug(""\n\nCmdLine:\t%s %s\n"", exePath, lpCmdLine); } setWow64Flag(); // Set default error message, title and optional support web site url. loadString(SUPPORT_URL, errUrl); loadString(ERR_TITLE, errTitle); if (!loadString(STARTUP_ERR, errMsg)) { return FALSE; } // Single instance loadString(MUTEX_NAME, mutexName); if (*mutexName) { SECURITY_ATTRIBUTES security; security.nLength = sizeof(SECURITY_ATTRIBUTES); security.bInheritHandle = TRUE; security.lpSecurityDescriptor = NULL; CreateMutexA(&security, FALSE, mutexName); if (GetLastError() == ERROR_ALREADY_EXISTS) { debug(""Instance already exists.""); return ERROR_ALREADY_EXISTS; } } // Working dir char tmp_path[_MAX_PATH] = {0}; GetCurrentDirectory(_MAX_PATH, oldPwd); if (loadString(CHDIR, tmp_path)) { strncpy(workingDir, exePath, pathLen); appendPath(workingDir, tmp_path); _chdir(workingDir); debug(""Working dir:\t%s\n"", workingDir); } // Use bundled jre or find java if (loadString(JRE_PATH, tmp_path)) { char jrePath[MAX_ARGS] = {0}; expandVars(jrePath, tmp_path, exePath, pathLen); debug(""Bundled JRE:\t%s\n"", jrePath); if (jrePath[0] == '\\' || jrePath[1] == ':') { // Absolute strcpy(cmd, jrePath); } else { // Relative strncpy(cmd, exePath, pathLen); appendPath(cmd, jrePath); } } if (!isJrePathOk(cmd)) { if (!loadString(JAVA_MIN_VER, javaMinVer)) { loadString(BUNDLED_JRE_ERR, errMsg); return FALSE; } loadString(JAVA_MAX_VER, javaMaxVer); if (!findJavaHome(cmd, loadInt(JDK_PREFERENCE))) { loadString(JRE_VERSION_ERR, errMsg); strcat(errMsg, "" ""); strcat(errMsg, javaMinVer); if (*javaMaxVer) { strcat(errMsg, "" - ""); strcat(errMsg, javaMaxVer); } loadString(DOWNLOAD_URL, errUrl); return FALSE; } if (!isJrePathOk(cmd)) { loadString(LAUNCHER_ERR, errMsg); return FALSE; } } // Append a path to the Path environment variable char jreBinPath[_MAX_PATH]; strcpy(jreBinPath, cmd); strcat(jreBinPath, ""\\bin""); if (!appendToPathVar(jreBinPath)) { return FALSE; } // Set environment variables char envVars[MAX_VAR_SIZE] = {0}; loadString(ENV_VARIABLES, envVars); char *var = strtok(envVars, ""\t""); while (var != NULL) { char *varValue = strchr(var, '='); *varValue++ = 0; *tmp = 0; expandVars(tmp, varValue, exePath, pathLen); debug(""Set var:\t%s = %s\n"", var, tmp); SetEnvironmentVariable(var, tmp); var = strtok(NULL, ""\t""); } *tmp = 0; // Process priority priority = loadInt(PRIORITY_CLASS); // Custom process name const BOOL setProcName = loadBool(SET_PROC_NAME) && strstr(lpCmdLine, ""--l4j-default-proc"") == NULL; const BOOL wrapper = loadBool(WRAPPER); appendLauncher(setProcName, exePath, pathLen, cmd); // Heap sizes appendHeapSizes(args); // JVM options if (loadString(JVM_OPTIONS, tmp)) { strcat(tmp, "" ""); } else { *tmp = 0; } /* * Load additional JVM options from .l4j.ini file * Options are separated by spaces or CRLF * # starts an inline comment */ strncpy(tmp_path, exePath, strlen(exePath) - 3); strcat(tmp_path, ""l4j.ini""); long hFile; if ((hFile = _open(tmp_path, _O_RDONLY)) != -1) { const int jvmOptLen = strlen(tmp); char* src = tmp + jvmOptLen; char* dst = src; const int len = _read(hFile, src, MAX_ARGS - jvmOptLen - BIG_STR); BOOL copy = TRUE; int i; for (i = 0; i < len; i++, src++) { if (*src == '#') { copy = FALSE; } else if (*src == 13 || *src == 10) { copy = TRUE; if (dst > tmp && *(dst - 1) != ' ') { *dst++ = ' '; } } else if (copy) { *dst++ = *src; } } *dst = 0; if (len > 0 && *(dst - 1) != ' ') { strcat(tmp, "" ""); } _close(hFile); } // Expand environment %variables% expandVars(args, tmp, exePath, pathLen); // MainClass + Classpath or Jar char mainClass[STR] = {0}; char jar[_MAX_PATH] = {0}; loadString(JAR, jar); if (loadString(MAIN_CLASS, mainClass)) { if (!loadString(CLASSPATH, tmp)) { return FALSE; } char exp[MAX_ARGS] = {0}; expandVars(exp, tmp, exePath, pathLen); strcat(args, ""-classpath \""""); if (wrapper) { appendAppClasspath(args, exePath, exp); } else if (*jar) { appendAppClasspath(args, jar, exp); } // Deal with wildcards or >> strcat(args, exp); << char* cp = strtok(exp, "";""); while(cp != NULL) { debug(""Add classpath:\t%s\n"", cp); if (strpbrk(cp, ""*?"") != NULL) { int len = strrchr(cp, '\\') - cp + 1; strncpy(tmp_path, cp, len); char* filename = tmp_path + len; *filename = 0; struct _finddata_t c_file; long hFile; if ((hFile = _findfirst(cp, &c_file)) != -1L) { do { strcpy(filename, c_file.name); strcat(args, tmp_path); strcat(args, "";""); debug("" \"" :\t%s\n"", tmp_path); } while (_findnext(hFile, &c_file) == 0); } _findclose(hFile); } else { strcat(args, cp); strcat(args, "";""); } cp = strtok(NULL, "";""); } *(args + strlen(args) - 1) = 0; strcat(args, ""\"" ""); strcat(args, mainClass); } else if (wrapper) { strcat(args, ""-jar \""""); strcat(args, exePath); strcat(args, ""\""""); } else { strcat(args, ""-jar \""""); strncat(args, exePath, pathLen); appendPath(args, jar); strcat(args, ""\""""); } // Constant command line args if (loadString(CMD_LINE, tmp)) { strcat(args, "" ""); strcat(args, tmp); } // Command line args if (*lpCmdLine) { strcpy(tmp, lpCmdLine); char* dst; while ((dst = strstr(tmp, ""--l4j-"")) != NULL) { char* src = strchr(dst, ' '); if (src == NULL || *(src + 1) == 0) { *dst = 0; } else { strcpy(dst, src + 1); } } if (*tmp) { strcat(args, "" ""); strcat(args, tmp); } } debug(""Launcher:\t%s\n"", cmd); debug(""Launcher args:\t%s\n"", args); debug(""Args length:\t%d/32768 chars\n"", strlen(args)); return TRUE; } void closeHandles() { CloseHandle(pi.hThread); CloseHandle(pi.hProcess); closeLogFile(); } /* * Append a path to the Path environment variable */ BOOL appendToPathVar(const char* path) { char chBuf[MAX_VAR_SIZE] = {0}; const int pathSize = GetEnvironmentVariable(""Path"", chBuf, MAX_VAR_SIZE); if (MAX_VAR_SIZE - pathSize - 1 < strlen(path)) { return FALSE; } strcat(chBuf, "";""); strcat(chBuf, path); return SetEnvironmentVariable(""Path"", chBuf); } DWORD execute(const BOOL wait) { STARTUPINFO si; memset(&pi, 0, sizeof(pi)); memset(&si, 0, sizeof(si)); si.cb = sizeof(si); DWORD dwExitCode = -1; char cmdline[MAX_ARGS]; strcpy(cmdline, ""\""""); strcat(cmdline, cmd); strcat(cmdline, ""\"" ""); strcat(cmdline, args); if (CreateProcess(NULL, cmdline, NULL, NULL, TRUE, priority, NULL, NULL, &si, &pi)) { if (wait) { WaitForSingleObject(pi.hProcess, INFINITE); GetExitCodeProcess(pi.hProcess, &dwExitCode); debug(""Exit code:\t%d\n"", dwExitCode); closeHandles(); } else { dwExitCode = 0; } } return dwExitCode; } ","C" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/head_src/resource.h",".h","2568","72","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2008 Grzegorz Kowal Ian Roberts (jdk preference patch) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // ICON #define APP_ICON 1 // BITMAP #define SPLASH_BITMAP 1 // RCDATA #define JRE_PATH 1 #define JAVA_MIN_VER 2 #define JAVA_MAX_VER 3 #define SHOW_SPLASH 4 #define SPLASH_WAITS_FOR_WINDOW 5 #define SPLASH_TIMEOUT 6 #define SPLASH_TIMEOUT_ERR 7 #define CHDIR 8 #define SET_PROC_NAME 9 #define ERR_TITLE 10 #define GUI_HEADER_STAYS_ALIVE 11 #define JVM_OPTIONS 12 #define CMD_LINE 13 #define JAR 14 #define MAIN_CLASS 15 #define CLASSPATH 16 #define WRAPPER 17 #define JDK_PREFERENCE 18 #define ENV_VARIABLES 19 #define PRIORITY_CLASS 20 #define DOWNLOAD_URL 21 #define SUPPORT_URL 22 #define MUTEX_NAME 23 #define INSTANCE_WINDOW_TITLE 24 #define INITIAL_HEAP_SIZE 25 #define INITIAL_HEAP_PERCENT 26 #define MAX_HEAP_SIZE 27 #define MAX_HEAP_PERCENT 28 #define STARTUP_ERR 101 #define BUNDLED_JRE_ERR 102 #define JRE_VERSION_ERR 103 #define LAUNCHER_ERR 104 #define INSTANCE_ALREADY_EXISTS_MSG 105 ","Unknown" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/head_src/head.h",".h","4083","114","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2008 Grzegorz Kowal, Ian Roberts (jdk preference patch) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _LAUNCH4J_HEAD__INCLUDED_ #define _LAUNCH4J_HEAD__INCLUDED_ #define WIN32_LEAN_AND_MEAN // VC - Exclude rarely-used stuff from Windows headers // Windows Header Files: #include // C RunTime Header Files #include #include #include #include #include #include #include #include #include #include #include #define NO_JAVA_FOUND 0 #define FOUND_JRE 1 #define FOUND_SDK 2 #define JRE_ONLY 0 #define PREFER_JRE 1 #define PREFER_JDK 2 #define JDK_ONLY 3 #define LAUNCH4J_TMP_DIR ""\\launch4j-tmp\\"" #define MANIFEST "".manifest"" #define KEY_WOW64_64KEY 0x0100 #define HKEY_STR ""HKEY"" #define HKEY_CLASSES_ROOT_STR ""HKEY_CLASSES_ROOT"" #define HKEY_CURRENT_USER_STR ""HKEY_CURRENT_USER"" #define HKEY_LOCAL_MACHINE_STR ""HKEY_LOCAL_MACHINE"" #define HKEY_USERS_STR ""HKEY_USERS"" #define HKEY_CURRENT_CONFIG_STR ""HKEY_CURRENT_CONFIG"" #define STR 128 #define BIG_STR 1024 #define MAX_VAR_SIZE 32767 #define MAX_ARGS 32768 #define TRUE_STR ""true"" #define FALSE_STR ""false"" #define debug(args...) if (hLog != NULL) fprintf(hLog, ## args); typedef void (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); FILE* openLogFile(const char* exePath, const int pathLen); void closeLogFile(); void msgBox(const char* text); void signalError(); BOOL loadString(const int resID, char* buffer); BOOL loadBool(const int resID); int loadInt(const int resID); BOOL regQueryValue(const char* regPath, unsigned char* buffer, unsigned long bufferLength); void regSearch(const HKEY hKey, const char* keyName, const int searchType); void regSearchWow(const char* keyName, const int searchType); void regSearchJreSdk(const char* jreKeyName, const char* sdkKeyName, const int jdkPreference); BOOL findJavaHome(char* path, const int jdkPreference); int getExePath(char* exePath); void appendPath(char* basepath, const char* path); void appendJavaw(char* jrePath); void appendAppClasspath(char* dst, const char* src, const char* classpath); BOOL isJrePathOk(const char* path); BOOL expandVars(char *dst, const char *src, const char *exePath, const int pathLen); void appendHeapSizes(char *dst); void appendHeapSize(char *dst, const int absID, const int percentID, const DWORD freeMemory, const char *option); int prepare(const char *lpCmdLine); void closeHandles(); BOOL appendToPathVar(const char* path); DWORD execute(const BOOL wait); #endif // _LAUNCH4J_HEAD__INCLUDED_ ","Unknown" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/head_src/guihead/guihead.c",".c","5765","186","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal Sylvain Mina (single instance patch) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include ""../resource.h"" #include ""../head.h"" #include ""guihead.h"" extern FILE* hLog; extern PROCESS_INFORMATION pi; HWND hWnd; DWORD dwExitCode = 0; BOOL stayAlive = FALSE; BOOL splash = FALSE; BOOL splashTimeoutErr; BOOL waitForWindow; int splashTimeout = DEFAULT_SPLASH_TIMEOUT; int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { int result = prepare(lpCmdLine); if (result == ERROR_ALREADY_EXISTS) { HWND handle = getInstanceWindow(); ShowWindow(handle, SW_SHOW); SetForegroundWindow(handle); closeLogFile(); return 2; } if (result != TRUE) { signalError(); return 1; } splash = loadBool(SHOW_SPLASH) && strstr(lpCmdLine, ""--l4j-no-splash"") == NULL; stayAlive = loadBool(GUI_HEADER_STAYS_ALIVE) && strstr(lpCmdLine, ""--l4j-dont-wait"") == NULL; if (splash || stayAlive) { hWnd = CreateWindowEx(WS_EX_TOOLWINDOW, ""STATIC"", """", WS_POPUP | SS_BITMAP, 0, 0, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); if (splash) { char timeout[10] = {0}; if (loadString(SPLASH_TIMEOUT, timeout)) { splashTimeout = atoi(timeout); if (splashTimeout <= 0 || splashTimeout > MAX_SPLASH_TIMEOUT) { splashTimeout = DEFAULT_SPLASH_TIMEOUT; } } splashTimeoutErr = loadBool(SPLASH_TIMEOUT_ERR) && strstr(lpCmdLine, ""--l4j-no-splash-err"") == NULL; waitForWindow = loadBool(SPLASH_WAITS_FOR_WINDOW); HANDLE hImage = LoadImage(hInstance, // handle of the instance containing the image MAKEINTRESOURCE(SPLASH_BITMAP), // name or identifier of image IMAGE_BITMAP, // type of image 0, // desired width 0, // desired height LR_DEFAULTSIZE); if (hImage == NULL) { signalError(); return 1; } SendMessage(hWnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM) hImage); RECT rect; GetWindowRect(hWnd, &rect); int x = (GetSystemMetrics(SM_CXSCREEN) - (rect.right - rect.left)) / 2; int y = (GetSystemMetrics(SM_CYSCREEN) - (rect.bottom - rect.top)) / 2; SetWindowPos(hWnd, HWND_TOP, x, y, 0, 0, SWP_NOSIZE); ShowWindow(hWnd, nCmdShow); UpdateWindow (hWnd); } if (!SetTimer (hWnd, ID_TIMER, 1000 /* 1s */, TimerProc)) { signalError(); return 1; } } if (execute(FALSE) == -1) { signalError(); return 1; } if (!(splash || stayAlive)) { debug(""Exit code:\t0\n""); closeHandles(); return 0; } MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } debug(""Exit code:\t%d\n"", dwExitCode); closeHandles(); return dwExitCode; } HWND getInstanceWindow() { char windowTitle[STR]; char instWindowTitle[STR] = {0}; if (loadString(INSTANCE_WINDOW_TITLE, instWindowTitle)) { HWND handle = FindWindowEx(NULL, NULL, NULL, NULL); while (handle != NULL) { GetWindowText(handle, windowTitle, STR - 1); if (strstr(windowTitle, instWindowTitle) != NULL) { return handle; } else { handle = FindWindowEx(NULL, handle, NULL, NULL); } } } return NULL; } BOOL CALLBACK enumwndfn(HWND hwnd, LPARAM lParam) { DWORD processId; GetWindowThreadProcessId(hwnd, &processId); if (pi.dwProcessId == processId) { LONG styles = GetWindowLong(hwnd, GWL_STYLE); if ((styles & WS_VISIBLE) != 0) { splash = FALSE; ShowWindow(hWnd, SW_HIDE); return FALSE; } } return TRUE; } VOID CALLBACK TimerProc( HWND hwnd, // handle of window for timer messages UINT uMsg, // WM_TIMER message UINT idEvent, // timer identifier DWORD dwTime) { // current system time if (splash) { if (splashTimeout == 0) { splash = FALSE; ShowWindow(hWnd, SW_HIDE); if (waitForWindow && splashTimeoutErr) { KillTimer(hwnd, ID_TIMER); signalError(); PostQuitMessage(0); } } else { splashTimeout--; if (waitForWindow) { EnumWindows(enumwndfn, 0); } } } GetExitCodeProcess(pi.hProcess, &dwExitCode); if (dwExitCode != STILL_ACTIVE || !(splash || stayAlive)) { KillTimer(hWnd, ID_TIMER); PostQuitMessage(0); } } ","C" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/head_src/guihead/guihead.h",".h","1888","44","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #define ID_TIMER 1 #define DEFAULT_SPLASH_TIMEOUT 60 /* 60 seconds */ #define MAX_SPLASH_TIMEOUT 60 * 15 /* 15 minutes */ HWND getInstanceWindow(); BOOL CALLBACK enumwndfn(HWND hwnd, LPARAM lParam); VOID CALLBACK TimerProc( HWND hwnd, // handle of window for timer messages UINT uMsg, // WM_TIMER message UINT idEvent, // timer identifier DWORD dwTime // current system time ); ","Unknown" "Bio foundation model","phylogeography/SPREADv1","release/tools/launch4j/head_src/consolehead/consolehead.c",".c","2197","66","/* Launch4j (http://launch4j.sourceforge.net/) Cross-platform Java application wrapper for creating Windows native executables. Copyright (c) 2004, 2007 Grzegorz Kowal Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include ""../resource.h"" #include ""../head.h"" int main(int argc, char* argv[]) { setConsoleFlag(); LPTSTR cmdLine = GetCommandLine(); if (*cmdLine == '""') { if (*(cmdLine = strchr(cmdLine + 1, '""') + 1)) { cmdLine++; } } else if ((cmdLine = strchr(cmdLine, ' ')) != NULL) { cmdLine++; } else { cmdLine = """"; } int result = prepare(cmdLine); if (result == ERROR_ALREADY_EXISTS) { char errMsg[BIG_STR] = {0}; loadString(INSTANCE_ALREADY_EXISTS_MSG, errMsg); msgBox(errMsg); closeLogFile(); return 2; } if (result != TRUE) { signalError(); return 1; } result = (int) execute(TRUE); if (result == -1) { signalError(); } else { return result; } } ","C" "Bio foundation model","phylogeography/SPREADv1","src/utils/ExceptionHandler.java",".java","1142","46","package utils; import java.lang.Thread.UncaughtExceptionHandler; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import app.SpreadApp; public class ExceptionHandler implements UncaughtExceptionHandler { public void uncaughtException(final Thread t, final Throwable e) { if (SwingUtilities.isEventDispatchThread()) { showExceptionDialog(t, e); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { showExceptionDialog(t, e); } }); }// END: edt check }// END: uncaughtException private void showExceptionDialog(Thread t, Throwable e) { String msg = String.format(""Unexpected problem on thread %s: %s"", t.getName(), e.getMessage()); logException(t, e); JOptionPane.showMessageDialog(Utils.getActiveFrame(), // msg, // ""Error"", // JOptionPane.ERROR_MESSAGE, // SpreadApp.errorIcon); }// END: showExceptionDialog private void logException(Thread t, Throwable e) { // TODO: start a thread that logs it, also spying on the user and // planting evidence // CIA style MOFO!!! e.printStackTrace(); }// END: logException }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/utils/ThreadLocalSpreadDate.java",".java","1513","61","package utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class ThreadLocalSpreadDate { private static ThreadLocal calThreadLocal; // private Calendar cal; private SimpleDateFormat formatter; private Date stringdate; public ThreadLocalSpreadDate(String date) throws ParseException { // if no era specified assume current era String line[] = date.split("" ""); if (line.length == 1) { StringBuilder properDateStringBuilder = new StringBuilder(); date = properDateStringBuilder.append(date).append("" AD"") .toString(); } formatter = new SimpleDateFormat(""yyyy-MM-dd G"", Locale.US); stringdate = formatter.parse(date); // Make calls to Calendar class in thread safe way calThreadLocal = new ThreadLocal() { @Override protected Calendar initialValue() { return Calendar.getInstance(); } }; }// END: ThreadLocalSpreadDate() public long plus(int days) { Calendar cal = calThreadLocal.get(); cal.setTime(stringdate); cal.add(Calendar.DATE, days); return cal.getTimeInMillis(); }// END: plus public long minus(int days) { Calendar cal = calThreadLocal.get(); cal.setTime(stringdate); cal.add(Calendar.DATE, -days); return cal.getTimeInMillis(); }// END: minus public long getTime() { Calendar cal = calThreadLocal.get(); cal.setTime(stringdate); return cal.getTimeInMillis(); }// END: getDate }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/utils/ComparableDouble.java",".java","1744","69","/* * ComparableDouble.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package utils; /** * This class is unfortunate but necessary to conform to JDK 1.1 * * @version $Id: ComparableDouble.java,v 1.3 2005/05/24 20:26:01 rambaut Exp $ * * @author Alexei Drummond */ public class ComparableDouble implements Comparable { private final double value; public ComparableDouble(double d) { value = d; } public int compareTo(Object o) { ComparableDouble cd = (ComparableDouble) o; if (value < cd.value) { return -1; } else if (value > cd.value) { return 1; } else return 0; } public boolean equals(Object o) { ComparableDouble cd = (ComparableDouble) o; return cd.value == value; } public double doubleValue() { return value; } public String toString() { return value + """"; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/utils/Utils.java",".java","34904","1310","package utils; import gui.InteractiveTableModel; import java.awt.Color; import java.awt.Frame; import java.io.PrintWriter; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Random; import java.util.concurrent.ConcurrentMap; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import jebl.evolution.graphs.Node; import jebl.evolution.trees.RootedTree; import math.MultivariateNormalDistribution; import kmlframework.kml.Point; import app.SpreadApp; import readers.LocationsReader; import structure.Coordinates; import structure.Line; import structure.TimeLine; public class Utils { // Earths radius in km public static final double EARTH_RADIUS = 6371.0; // how many millisecond one day holds public static final int DAY_IN_MILLIS = 86400000; // how many days one year holds public static final int DAYS_IN_YEAR = 365; // /////////////////// // ---ENUM FIELDS---// // /////////////////// public enum PoissonPriorEnum { DEFAULT, USER } // //////////////////////////////// // ---EXCEPTION HANDLING UTILS---// // //////////////////////////////// public static void handleException(final Throwable e, final String msg) { /* * Called when exception is caught * */ final Thread t = Thread.currentThread(); if (SwingUtilities.isEventDispatchThread()) { showExceptionDialog(t, e, msg); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { showExceptionDialog(t, e, msg); } }); }// END: EDT check }// END: uncaughtException private static void showExceptionDialog(Thread t, Throwable e, String msg) { String message = String.format(""Unexpected problem on thread %s: %s"" + ""\n"" + msg, t.getName(), e.getMessage()); logException(t, e); JOptionPane.showMessageDialog(Utils.getActiveFrame(), // message, // ""Error"", // JOptionPane.ERROR_MESSAGE, // SpreadApp.errorIcon); }// END: showExceptionDialog private static void logException(Thread t, Throwable e) { // TODO: start a thread that logs it, also spying on the user and planting evidence // CIA style MOFO!!! // END: Poor attempt at humor e.printStackTrace(); }// END: logException public static void handleError(final String msg) { /* * Called when possible exception can occur * */ if (SwingUtilities.isEventDispatchThread()) { showErrorDialog(msg); } else { SwingUtilities.invokeLater(new Runnable() { public void run() { showErrorDialog(msg); } }); }// END: EDT check }// END: uncaughtException public static void showErrorDialog(final String msg) { JOptionPane.showMessageDialog(Utils.getActiveFrame(), // msg, // ""Error"", // JOptionPane.ERROR_MESSAGE, // SpreadApp.errorIcon ); } // /////////////////////////// // ---DISCRETE TREE UTILS---// // /////////////////////////// public static String pickRand(String[] array, Random generator) { int rnd = generator.nextInt(array.length); return array[rnd]; } public static List generateCircle(double centerY, double centerX, double radius, int numPoints) { List coords = new ArrayList(); double Clat = Math.toDegrees((radius / EARTH_RADIUS)); double Clong = Clat / Math.cos(Math.toRadians(centerX)); for (int i = 0; i < numPoints; i++) { double theta = 2.0 * Math.PI * (i / (double) numPoints); double Cx = centerY + (Clong * Math.cos(theta)); double Cy = centerX + (Clat * Math.sin(theta)); coords.add(new Coordinates(Cx, Cy, 0.0)); }// END: numPoints loop return coords; }// END: GenerateCircle public static float matchStateCoordinate(InteractiveTableModel table, String state, int latlon) { /** * Match state name with its coordinates * * 1 for lon, 2 for lat */ float coordinate = Float.NaN; for (int i = 0; i < table.getRowCount(); i++) { String name = String.valueOf(table.getValueAt(i, 0)); if (name.toLowerCase().equals(state.toLowerCase())) { coordinate = Float.valueOf(String.valueOf(table.getValueAt(i, latlon))); } } return coordinate; }// END: MatchStateCoordinate public static float matchStateCoordinate(LocationsReader data, String state, int latlon) { /** * Match state name with its coordinates * * 1 for lon, 0 for lat */ float coordinate = Float.NaN; for (int i = 0; i < data.locations.length; i++) { if (data.locations[i].toLowerCase().equals(state.toLowerCase())) { coordinate = data.coordinates[i][latlon]; } } return coordinate; }// END: MatchStateCoordinate // /////////////////////////// // ---BAYES FACTORS UTILS---// // /////////////////////////// public static double[] parseDouble(String[] lines) { int nrow = lines.length; double[] a = new double[nrow]; for (int i = 0; i < nrow; i++) { a[i] = Double.parseDouble(lines[i]); } return a; } public static double colMean(double a[][], int col) { double sum = 0; int nrows = a.length; for (int row = 0; row < nrows; row++) { sum += a[row][col]; } return sum / nrows; } public static double[] colMeans(double a[][]) { int ncol = a[0].length; double[] b = new double[ncol]; for (int c = 0; c < ncol; c++) { b[c] = colMean(a, c); } return b; } public static String[] subset(String line[], int start, int length) { String output[] = new String[length]; System.arraycopy(line, start, output, 0, length); return output; } // ///////////////////////////// // ---CONTINUOUS TREE UTILS---// // ///////////////////////////// public static String getModalityAttributeName(String longitudeName, String HPDString) { String coordinatesName = longitudeName.replaceAll(""[0-9.]"", """"); String modalityAttributeName = coordinatesName + ""_"" + HPDString + ""_modality""; return modalityAttributeName; }// END: getModalityAttributeName public static List parsePolygons(Object[] longitudeHPD, Object[] latitudeHPD) { List coords = new ArrayList(); for (int i = 0; i < longitudeHPD.length; i++) { coords.add(new Coordinates(Double.valueOf(longitudeHPD[i] .toString()), Double.valueOf(latitudeHPD[i].toString()), 0.0)); } return coords; }// END: parsePolygons // ///////////////////////// // ---TIME SLICER UTILS---// // ///////////////////////// public static TimeLine generateTreeTimeLine(RootedTree tree, double timescaler, int numberOfIntervals, ThreadLocalSpreadDate mrsd) { // This is a general time span for all of the trees double treeRootHeight = Utils.getNodeHeight(tree, tree.getRootNode()); double startTime = mrsd.getTime() - (treeRootHeight * DAY_IN_MILLIS * DAYS_IN_YEAR * timescaler); double endTime = mrsd.getTime(); TimeLine timeLine = new TimeLine(startTime, endTime, numberOfIntervals); return timeLine; }// END: generateTreeTimeLine public static double[] generateTreeSliceHeights(double treeRootHeight, int numberOfIntervals) { double[] timeSlices = new double[numberOfIntervals]; for (int i = 0; i < numberOfIntervals; i++) { timeSlices[i] = treeRootHeight - (treeRootHeight / (double) numberOfIntervals) * ((double) i); } return timeSlices; }// END: generateTimeSlices public static TimeLine generateCustomTimeLine(double[] timeSlices, double timescaler, ThreadLocalSpreadDate mrsd) { // This is a general time span for all of the trees int numberOfSlices = timeSlices.length; double firstSlice = timeSlices[0]; double startTime = mrsd.getTime() - (firstSlice * DAY_IN_MILLIS * DAYS_IN_YEAR * timescaler); double endTime = mrsd.getTime(); return new TimeLine(startTime, endTime, numberOfSlices); }// END: generateCustomTimeLine public static double getTreeLength(RootedTree tree, Node node) { int childCount = tree.getChildren(node).size(); if (childCount == 0) return tree.getLength(node); double length = 0; for (int i = 0; i < childCount; i++) { length += getTreeLength(tree, tree.getChildren(node).get(i)); } if (node != tree.getRootNode()) length += tree.getLength(node); return length; } public static double[] imputeValue(double[] location, double[] parentLocation, double sliceHeight, double nodeHeight, double parentHeight, double rate, boolean trueNoise, double treeNormalization, double[] precisionArray) { int dim = (int) Math.sqrt(1 + 8 * precisionArray.length) / 2; double[][] precision = new double[dim][dim]; int c = 0; for (int i = 0; i < dim; i++) { for (int j = i; j < dim; j++) { precision[j][i] = precision[i][j] = precisionArray[c++] * treeNormalization; } } dim = location.length; double[] nodeValue = new double[2]; double[] parentValue = new double[2]; for (int i = 0; i < dim; i++) { nodeValue[i] = location[i]; parentValue[i] = parentLocation[i]; } final double scaledTimeChild = (sliceHeight - nodeHeight) * rate; final double scaledTimeParent = (parentHeight - sliceHeight) * rate; final double scaledWeightTotal = (1.0 / scaledTimeChild) + (1.0 / scaledTimeParent); if (scaledTimeChild == 0) return location; if (scaledTimeParent == 0) return parentLocation; // Find mean value, weighted average double[] mean = new double[dim]; double[][] scaledPrecision = new double[dim][dim]; for (int i = 0; i < dim; i++) { mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal; if (trueNoise) { for (int j = i; j < dim; j++) scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal; } } if (trueNoise) { mean = MultivariateNormalDistribution .nextMultivariateNormalPrecision(mean, scaledPrecision); } double[] result = new double[dim]; for (int i = 0; i < dim; i++) { result[i] = mean[i]; } return result; }// END: ImputeValue // /////////////////////////// // ---KML GENERATOR UTILS---// // /////////////////////////// public static double longNormalise(double lon) { // normalise to -180...+180 return (lon + 3 * Math.PI) % (2 * Math.PI) - Math.PI; } public static float getMercatorLatitude(double lat) { double R_MAJOR = 6378137.0; double R_MINOR = 6356752.3142; if (lat > 89.5) { lat = 89.5; } if (lat < -89.5) { lat = -89.5; } double temp = R_MINOR / R_MAJOR; double es = 1.0 - (temp * temp); double eccent = Math.sqrt(es); double phi = Math.toRadians(lat); double sinphi = Math.sin(phi); double con = eccent * sinphi; double com = 0.5 * eccent; con = Math.pow(((1.0 - con) / (1.0 + con)), com); double ts = Math.tan(0.5 * ((Math.PI * 0.5) - phi)) / con; double y = 0 - R_MAJOR * Math.log(ts); return (float) y; } public static List convertToPoint(List coords) { List points = new ArrayList(); Iterator iterator = coords.iterator(); while (iterator.hasNext()) { Point point = new Point(); Coordinates coord = iterator.next(); point.setLongitude(coord.getLongitude()); point.setLatitude(coord.getLatitude()); point.setAltitude(0.0); points.add(point); } return points; }// END: convertToPoint public static double greatCircDistSpherLawCos(double startLon, double startLat, double endLon, double endLat) { /** * Calculates the geodesic distance between two points specified by * latitude/longitude using the Spherical Law of Cosines (slc) * * @param start * point Lon, Lat; end point Lon, Lat; * * @return distance in km * */ double rlon1 = Math.toRadians(startLon); double rlat1 = Math.toRadians(startLat); double rlon2 = Math.toRadians(endLon); double rlat2 = Math.toRadians(endLat); double distance = Math.acos(Math.sin(rlat1) * Math.sin(rlat2) + Math.cos(rlat1) * Math.cos(rlat2) * Math.cos(rlon2 - rlon1)) * EARTH_RADIUS; return distance; }// END: GreatCircDistSpherLawCos public static double greatCircDistHavForm(double startLon, double startLat, double endLon, double endLat) { /** * Calculates the geodesic distance between two points specified by * latitude/longitude using the Haversine formula * * @param start * point Lon, Lat; end point Lon, Lat; * * @return distance in km * */ double dLat = Math.toRadians(endLat - startLat); double dLon = Math.toRadians(endLon - startLon); double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(startLat)) * Math.cos(Math.toRadians(endLat)) * Math.sin(dLon / 2) * Math.sin(dLon / 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double distance = EARTH_RADIUS * c; return distance; }// END: GreatCircDistHavForm public static double greatCircDistVincInvForm(double startLon, double startLat, double endLon, double endLat) { /** * Calculates the geodesic distance between two points specified by * latitude/longitude using the Vincenty inverse formula for ellipsoids * * @param start * point Lon, Lat; end point Lon, Lat; * * @return distance in km * */ double rlon1 = Math.toRadians(startLon); double rlat1 = Math.toRadians(startLat); double rlon2 = Math.toRadians(endLon); double rlat2 = Math.toRadians(endLat); double a = 6378137.0; // length of major axis of the ellipsoid (radius // at equator) double b = 6356752.314245; // length of minor axis of the ellipsoid // (radius at the poles) double f = 1 / 298.257223563; // flattening of the ellipsoid double L = (rlon2 - rlon1); // difference in longitude double U1 = Math.atan((1 - f) * Math.tan(rlat1)); // reduced latitude double U2 = Math.atan((1 - f) * Math.tan(rlat2)); // reduced latitude double sinU1 = Math.sin(U1); double cosU1 = Math.cos(U1); double sinU2 = Math.sin(U2); double cosU2 = Math.cos(U2); double cosSqAlpha = Double.NaN; double sinSigma = Double.NaN; double cosSigma = Double.NaN; double cos2SigmaM = Double.NaN; double sigma = Double.NaN; double lambda = L; double lambdaP = 0.0; int iterLimit = 100; while (Math.abs(lambda - lambdaP) > 1e-12 & iterLimit > 0) { double sinLambda = Math.sin(lambda); double cosLambda = Math.cos(lambda); sinSigma = Math.sqrt((cosU2 * sinLambda) * (cosU2 * sinLambda) + (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda) * (cosU1 * sinU2 - sinU1 * cosU2 * cosLambda)); if (sinSigma == 0) { return 0.0; // Co-incident points } cosSigma = sinU1 * sinU2 + cosU1 * cosU2 * cosLambda; sigma = Math.atan2(sinSigma, cosSigma); double sinAlpha = cosU1 * cosU2 * sinLambda / sinSigma; cosSqAlpha = 1 - sinAlpha * sinAlpha; cos2SigmaM = cosSigma - 2 * sinU1 * sinU2 / cosSqAlpha; if (Double.isNaN(cos2SigmaM)) { cos2SigmaM = 0.0; // Equatorial line: cosSqAlpha=0 } double C = f / 16 * cosSqAlpha * (4 + f * (4 - 3 * cosSqAlpha)); lambdaP = lambda; lambda = L + (1 - C) * f * sinAlpha * (sigma + C * sinSigma * (cos2SigmaM + C * cosSigma * (-1 + 2 * cos2SigmaM * cos2SigmaM))); iterLimit--; }// END: convergence loop if (iterLimit == 0) { return Double.NaN; // formula failed to converge } double uSq = cosSqAlpha * (a * a - b * b) / (b * b); double A = 1 + uSq / 16384.0 * (4096.0 + uSq * (-768.0 + uSq * (320.0 - 175.0 * uSq))); double B = uSq / 1024.0 * (256.0 + uSq * (-128.0 + uSq * (74.0 - 47.0 * uSq))); double deltaSigma = B * sinSigma * (cos2SigmaM + B / 4 * (cosSigma * (-1 + 2 * Math.pow(cos2SigmaM, 2)) - B / 6 * cos2SigmaM * (-3 + 4 * Math.pow(sinSigma, 2)) * (-3 + 4 * Math.pow(cos2SigmaM, 2)))); double distance = b * A * (sigma - deltaSigma) / 1000.0; return distance; // Distance in km }// END: GreatCircDistVincInvForm public static double rhumbDistance(double startLon, double startLat, double endLon, double endLat) { /** * Returns the distance from start point to the end point in km, * travelling along a rhumb line * * @param start * point Lon, Lat; end point Lon, Lat; * * @return distance in km */ double rlon1 = Math.toRadians(startLon); double rlat1 = Math.toRadians(startLat); double rlon2 = Math.toRadians(endLon); double rlat2 = Math.toRadians(endLat); double dLat = (rlat2 - rlat1); double dLon = Math.abs(rlon2 - rlon1); double dPhi = Math.log(Math.tan(rlat2 / 2 + Math.PI / 4) / Math.tan(rlat1 / 2 + Math.PI / 4)); double q = (!Double.isNaN(dLat / dPhi)) ? dLat / dPhi : Math.cos(rlat1); // E-W // line // gives // dPhi=0 // if dLon over 180° take shorter rhumb across 180° meridian: if (dLon > Math.PI) dLon = 2 * Math.PI - dLon; double distance = Math.sqrt(dLat * dLat + q * q * dLon * dLon) * EARTH_RADIUS; return distance; } public static double bearing(double rlon1, double rlat1, double rlon2, double rlat2) { /** * Returns the (initial) bearing from start point to the destination * point, in degrees * * @param rlat1 * , rlon1 : longitude/latitude in radians of start point * rlon2, rlat2 : longitude/latitude of end point * * @returns Initial bearing in degrees from North */ double brng = Double.NaN; if ((Math.cos(rlat1) < 1 / Double.MAX_VALUE)) { if (rlat2 > 0) { // if starting from North Pole brng = Math.PI; } else { // if starting from South Pole brng = 2 * Math.PI; } } else { // if starting from points other than Poles double dLon = (rlon2 - rlon1); double y = Math.sin(dLon) * Math.cos(rlat2); double x = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dLon); // double brng = Math.abs(Math.atan2(y, x)); brng = Math.atan2(y, x); } return Math.toRadians((Math.toDegrees(brng) + 360) % 360); } public static double rhumbBearing(double rlon1, double rlat1, double rlon2, double rlat2) { /** * Returns the bearing from start point to the supplied point along a * rhumb line * * @param rlat1 * , rlon1 : longitude/latitude in radians of start point * rlon2, rlat2 : longitude/latitude of end point * * @returns Initial bearing in degrees from North */ double dLon = (rlon2 - rlon1); double dPhi = Math.log(Math.tan(rlat2 / 2 + Math.PI / 4) / Math.tan(rlat1 / 2 + Math.PI / 4)); if (Math.abs(dLon) > Math.PI) dLon = dLon > 0 ? -(2 * Math.PI - dLon) : (2 * Math.PI + dLon); double brng = Math.atan2(dLon, dPhi); return Math.toRadians((Math.toDegrees(brng) + 360) % 360); } // ///////////////// // ---GUI UTILS---// // ///////////////// public static Frame getActiveFrame() { Frame result = null; Frame[] frames = Frame.getFrames(); for (int i = 0; i < frames.length; i++) { Frame frame = frames[i]; if (frame.isVisible()) { result = frame; break; } } return result; } public static void printProgress(int percent) { StringBuilder bar = new StringBuilder(""[""); for (int i = 0; i < 50; i++) { if (i < (percent / 2)) { bar.append(""=""); } else if (i == (percent / 2)) { bar.append("">""); } else { bar.append("" ""); } } bar.append(""] "" + percent + ""% ""); System.out.print(""\r"" + bar.toString()); } public static void updateProgress(double progressPercentage) { final int width = 50; // progress bar width in chars System.out.print(""\r[""); int i = 0; for (; i <= (int) (progressPercentage * width); i++) { System.out.print("".""); } for (; i < width; i++) { System.out.print("" ""); } System.out.print(""]""); } // //////////////////// // ---COMMON UTILS---// // //////////////////// public double[][] matrixMultiply(double[][] a, double[][] b) { int nrowA = a.length; int ncolA = a[0].length; int nrowB = b.length; int ncolB = b[0].length; double c[][] = null; if (ncolA == nrowB) { c = new double[nrowA][ncolB]; for (int i = 0; i < nrowA; i++) { for (int j = 0; j < ncolB; j++) { c[i][j] = 0; for (int k = 0; k < ncolA; k++) { c[i][j] = c[i][j] + a[i][k] * b[k][j]; } } } } else { throw new RuntimeException(""non-conformable arguments""); } return c; } public static String getKMLDate(double fractionalDate) { int year = (int) fractionalDate; String yearString; if (year < 10) { yearString = ""000"" + year; } else if (year < 100) { yearString = ""00"" + year; } else if (year < 1000) { yearString = ""0"" + year; } else { yearString = """" + year; } double fractionalMonth = fractionalDate - year; int month = (int) (12.0 * fractionalMonth); String monthString; if (month < 10) { monthString = ""0"" + month; } else { monthString = """" + month; } int day = (int) Math.round(30 * (12 * fractionalMonth - month)); String dayString; if (day < 10) { dayString = ""0"" + day; } else { dayString = """" + day; } return yearString + ""-"" + monthString + ""-"" + dayString; } public static int getIntegerNodeAttribute(Node node, String attributeName) { if (node.getAttribute(attributeName) == null) { throw new RuntimeException(""Attribute, "" + attributeName + "", missing from node""); } return (Integer) node.getAttribute(attributeName); } public static int getIntegerNodeAttribute(Node node, String attributeName, int defaultValue) { if (node.getAttribute(attributeName) == null) { return defaultValue; } return (Integer) node.getAttribute(attributeName); } public static double getDoubleNodeAttribute(Node node, String attributeName) { if (node.getAttribute(attributeName) == null) { throw new RuntimeException(""Attribute, "" + attributeName + "", missing from node""); } return (Double) node.getAttribute(attributeName); } public static double getDoubleNodeAttribute(Node node, String attributeName, double defaultValue) { if (node.getAttribute(attributeName) == null) { return defaultValue; } return (Double) node.getAttribute(attributeName); } public static String getStringNodeAttribute(Node node, String attributeName) { Object attr = node.getAttribute(attributeName); if (attr == null) { throw new RuntimeException(""Attribute, "" + attributeName + "", missing from node""); } if(!attr.getClass().equals(String.class)) { throw new RuntimeException( ""Attribute, "" + attributeName + "", is not a text attribute for nodes."" ); } return attr.toString(); } public static String getStringNodeAttribute(Node node, String attributeName, String defaultValue) { if (node.getAttribute(attributeName) == null) { return defaultValue; } return (String) node.getAttribute(attributeName); } public static Object getObjectNodeAttribute(Node node, String attributeName) { if (node.getAttribute(attributeName) == null) { throw new RuntimeException(""Attribute, "" + attributeName + "", missing from node""); } return node.getAttribute(attributeName); } public static Object[] getObjectArrayNodeAttribute(Node node, String attributeName) { if (node.getAttribute(attributeName) == null) { throw new RuntimeException(""Attribute, "" + attributeName + "", missing from node""); } return (Object[]) node.getAttribute(attributeName); } public static double[] getDoubleArrayNodeAttribute(Node node, String attributeName) { if (node.getAttribute(attributeName) == null) { throw new RuntimeException(""Attribute, "" + attributeName + "", missing from node""); } Object[] o = (Object[]) node.getAttribute(attributeName); double[] array = new double[o.length]; for (int i = 0; i < o.length; i++) { array[i] = Double.valueOf(o[i].toString()); } return array; } public static Double getNodeHeight(RootedTree tree, Node node) { Double nodeHeight = tree.getHeight(node); if (nodeHeight == null) { throw new RuntimeException( ""Height attribute missing from the node. \n""); } return nodeHeight; } public static Object[] getTreeArrayAttribute(RootedTree tree, String attribute) { Object o = tree.getAttribute(attribute); if (o == null) { throw new RuntimeException(""Attribute "" + attribute + "" missing from the tree. \n""); } return (Object[]) o; } public static double[] getTreeDoubleArrayAttribute(RootedTree tree, String attribute) { Object[] o = (Object[]) tree.getAttribute(attribute); if (o == null) { throw new RuntimeException(""Attribute "" + attribute + "" missing from the tree. \n""); } double[] array = new double[o.length]; for (int i = 0; i < o.length; i++) { array[i] = Double.valueOf(o[i].toString()); } return array; } public static int getNodeCount(RootedTree tree) { int NodeCount = 0; for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { NodeCount++; } } return NodeCount; } public static int getExternalNodeCount(RootedTree tree) { int externalNodeCount = 0; for (Node node : tree.getNodes()) { if (tree.isExternal(node)) { externalNodeCount++; } } return externalNodeCount; } public static double getTreeHeightMin(RootedTree tree) { /** * Finds the min height for given tree. * * @param tree * @return min height */ double m = Double.MAX_VALUE; for (Node node : tree.getNodes()) { if (tree.getHeight(node) < m) { m = tree.getHeight(node); } } return m; }// END: getTreeHeightMin public static double getTreeHeightMax(RootedTree tree) { /** * Finds the max height for given tree. * * @param tree * @return max height */ double m = -Double.MAX_VALUE; for (Node node : tree.getNodes()) { if (tree.getHeight(node) > m) { m = tree.getHeight(node); } } return m; }// END: getTreeHeightMax public static double getListMin(List list) { double m = Double.MAX_VALUE; for (int i = 0; i < list.size(); i++) { if (list.get(i) < m) { m = list.get(i); } } return m; }// END: getDoubleListMax public static double getListMax(List list) { double m = -Double.MAX_VALUE; for (int i = 0; i < list.size(); i++) { if (list.get(i) > m) { m = list.get(i); } } return m; }// END: getDoubleListMax public static double get2DArrayMax(double[][] array) { double m = -Double.MAX_VALUE; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[0].length; j++) { if (array[i][j] > m) { m = array[i][j]; } } } return m; }// END: get2DArrayMax public static String getKMLColor(Color color) { /** * converts a Java color into a 4 channel hex color string. * * @param color * @return the color string */ String a = Integer.toHexString(color.getAlpha()); String b = Integer.toHexString(color.getBlue()); String g = Integer.toHexString(color.getGreen()); String r = Integer.toHexString(color.getRed()); return (a.length() < 2 ? ""0"" : """") + a + (b.length() < 2 ? ""0"" : """") + b + (g.length() < 2 ? ""0"" : """") + g + (r.length() < 2 ? ""0"" : """") + r; } public static String getKMLColor(Color color, double opacity) { /** * converts a Java color into a 4 channel hex color string. * * @param color * @return the color string */ int alpha = (int) (256 * (1.0 - opacity)); String a = Integer.toHexString(alpha); String b = Integer.toHexString(color.getBlue()); String g = Integer.toHexString(color.getGreen()); String r = Integer.toHexString(color.getRed()); return (a.length() < 2 ? ""0"" : """") + a + (b.length() < 2 ? ""0"" : """") + b + (g.length() < 2 ? ""0"" : """") + g + (r.length() < 2 ? ""0"" : """") + r; } public static Color getBlendedColor(float proportion, Color startColor, Color endColor) { proportion = Math.max(proportion, 0.0F); proportion = Math.min(proportion, 1.0F); float[] start = startColor.getRGBColorComponents(null); float[] end = endColor.getRGBColorComponents(null); float[] color = new float[start.length]; for (int i = 0; i < start.length; i++) { color[i] = start[i] + ((end[i] - start[i]) * proportion); } return new Color(color[0], color[1], color[2]); } public static Color getRandomColor() { /** * random color selection * * @return the Color */ int red = 127 + (int) (Math.random() * 127); int green = 127 + (int) (Math.random() * 127); int blue = 127 + (int) (Math.random() * 127); int alpha = 127 + (int) (Math.random() * 127); Color col = new Color(red, green, blue, alpha); return col; }// END: getRandomColor public static double map(double value, double low1, double high1, double low2, double high2) { /** * maps a single value from its range into another interval * * @param low1, high1 - range of value; low2, high2 - interval * @return the mapped value */ // return ((low2 - high2) / (low1 - high1)) * value - ((high1 * low2 - low1 * high2) / (low1 - high1)); return (value - low1) / (high1 - low1) * (high2 - low2) + low2; }// END: map public static int newton(int n, int k) { BigInteger newton = BigInteger.valueOf(1); String newtonString = null; for (int i = 1; i <= k; i++) { newton = newton.multiply(BigInteger.valueOf(n - i + 1)).divide( BigInteger.valueOf(i)); newtonString = newton.toString(); } return Integer.parseInt(newtonString); } // ///////////////// // ---DEBUGGING---// // ///////////////// public static void printCoordinate(Coordinates coordinate) { System.out.println(""Longitude: "" + coordinate.getLongitude()); System.out.println(""Latitude: "" + coordinate.getLatitude()); } public static void printCoordinatesList(List list) { for (Coordinates coordinate : list) { printCoordinate(coordinate); } }// END: printCoordinatesList public static void printLine(Line line) { System.out.println(""Start coords:""); System.out.println(""\t Longitude: "" + line.getStartLocation().getLongitude()); System.out.println(""\t Latitude: "" + line.getStartLocation().getLatitude()); System.out.println(""Start time: "" + line.getStartTime()); System.out.println(""End coords:""); System.out.println(""\t Longitude: "" + line.getEndLocation().getLongitude()); System.out.println(""\t Latitude: "" + line.getEndLocation().getLatitude()); System.out.println(""End time: "" + line.getEndTime()); System.out.println(""Max altitude: ""+line.getMaxAltitude()); }//END: printLine public static String getSpreadFormattedTime(double time) { SimpleDateFormat formatter = new SimpleDateFormat(""yyyy-MM-dd G"", Locale.US); return formatter.format(time); } public static void printArray(double[] x) { for (int i = 0; i < x.length; i++) { System.out.println(x[i]); } }// END: printArray public static void printArray(String[] x) { for (int i = 0; i < x.length; i++) { System.out.println(x[i]); } }// END: printArray public static void printArray(Object[] x) { for (int i = 0; i < x.length; i++) { System.out.println(x[i]); } }// END: printArray public static void headArray(Object[] array, int nrow) { for (int row = 0; row < nrow; row++) { System.out.println(array[row]); } }// END: printArray public static void print2DArray(Object[][] array) { for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { System.out.print(array[row][col] + "" ""); } System.out.print(""\n""); } }// END: print2DArray public static void print2DArray(double[][] array) { for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { System.out.print(array[row][col] + "" ""); } System.out.print(""\n""); } }// END: print2DArray public static void print2DArray(float[][] array) { for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { System.out.print(array[row][col] + "" ""); } System.out.print(""\n""); } }// END: print2DArray public static void headArray(double[] array, int nrow) { for (int row = 0; row < nrow; row++) { System.out.println(array[row]); } }// END: headArray public static void headArray(String[] array, int nrow) { for (int row = 0; row < nrow; row++) { System.out.println(array[row]); } }// END: headArray public static void head2DArray(float[][] array, int nrow) { for (int row = 0; row < nrow; row++) { for (int col = 0; col < array[row].length; col++) { System.out.print(array[row][col] + "" ""); } System.out.print(""\n""); } }// END: head2DArray public static void save2DArray(String filename, int[][] array) { try { PrintWriter pri = new PrintWriter(filename); for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { pri.print(array[row][col] + ""\t""); } pri.print(""\n""); } pri.close(); } catch (Exception e) { e.printStackTrace(); } }// END: save2DArray public static void save2DArray(String filename, double[][] array) { try { PrintWriter pri = new PrintWriter(filename); for (int row = 0; row < array.length; row++) { for (int col = 0; col < array[row].length; col++) { pri.print(array[row][col] + ""\t""); } pri.print(""\n""); } pri.close(); } catch (Exception e) { e.printStackTrace(); } }// END: save2DArray public static void printHashMap( ConcurrentMap> slicesMap) { Iterator iterator = slicesMap.keySet().iterator(); while (iterator.hasNext()) { Double sliceTime = (Double) iterator.next(); List list = slicesMap.get(sliceTime); double[][] array = new double[list.size()][2];// 3 for (int i = 0; i < list.size(); i++) { array[i][0] = list.get(i).getLatitude();// 1 array[i][1] = list.get(i).getLongitude();// 2 } System.out.println(sliceTime); System.out.println(array.length); // print2DArray(array); }// END while has next }// END: saveHashMap public static void saveHashMap( ConcurrentMap> slicesMap) { Iterator iterator = slicesMap.keySet().iterator(); int j = 0; while (iterator.hasNext()) { Double sliceTime = (Double) iterator.next(); List list = slicesMap.get(sliceTime); double[][] array = new double[list.size()][2];// 3 for (int i = 0; i < list.size(); i++) { // array[i][0] = sliceTime; array[i][0] = list.get(i).getLatitude();// 1 array[i][1] = list.get(i).getLongitude();// 2 } Utils.save2DArray( ""/home/filip/Dropbox/SPREAD/out1/true_noise_array_"" + j, array); j++; }// END while has next }// END: saveHashMap }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/utils/NumberFormatter.java",".java","4931","171","/* * NumberFormatter.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package utils; import java.text.DecimalFormat; /** * The world's most intelligent number formatter with the following features :-) *

* It guarantee's the display of a user-specified number of significant figures, * sf
* It displays decimal format for numbers with absolute values between 1 and * 10^(sf-1)
* It displays scientific notation for all other numbers (i.e. really big and * really small absolute values)
* note: Its display integers for doubles with integer value
* * @version $Id: NumberFormatter.java,v 1.6 2005/05/24 20:26:01 rambaut Exp $ * * @author Alexei Drummond */ public class NumberFormatter { private int sf; private double upperCutoff; private double[] cutoffTable; private final DecimalFormat decimalFormat = new DecimalFormat(); private DecimalFormat scientificFormat = null; private boolean isPadding = false; private int fieldWidth; public NumberFormatter(int sf) { setSignificantFigures(sf); } public NumberFormatter(int sf, int fieldWidth) { setSignificantFigures(sf); setPadding(true); setFieldWidth(fieldWidth); } public void setSignificantFigures(int sf) { this.sf = sf; upperCutoff = Math.pow(10, sf - 1); cutoffTable = new double[sf]; long num = 10; for (int i = 0; i < cutoffTable.length; i++) { cutoffTable[i] = (double) num; num *= 10; } decimalFormat.setMinimumIntegerDigits(1); decimalFormat.setMaximumFractionDigits(sf - 1); decimalFormat.setMinimumFractionDigits(sf - 1); decimalFormat.setGroupingUsed(false); scientificFormat = new DecimalFormat(getScientificPattern(sf)); fieldWidth = sf; } public void setPadding(boolean padding) { isPadding = padding; } public void setFieldWidth(int fw) { if (fw < sf + 4) throw new IllegalArgumentException(); fieldWidth = fw; } public int getFieldWidth() { return fieldWidth; } public String formatToFieldWidth(String s, int fieldWidth) { int size = fieldWidth - s.length(); StringBuffer buffer = new StringBuffer(s); for (int i = 0; i < size; i++) { buffer.append(' '); } return buffer.toString(); } /** * @return the given value formatted to have exactly then number of fraction * digits specified. */ public String formatDecimal(double value, int numFractionDigits) { decimalFormat.setMaximumFractionDigits(numFractionDigits); decimalFormat.setMinimumFractionDigits(Math.min(numFractionDigits, 1)); return decimalFormat.format(value); } /** * This method formats a number 'nicely':
* It guarantee's the display of a user-specified total significant figures, * sf
* It displays decimal format for numbers with absolute values between 1 and * 10^(sf-1)
* It displays scientific notation for all other numbers (i.e. really big * and really small absolute values)
* note: Its display integers for doubles with integer value
* * @return a nicely formatted number. */ public String format(double value) { StringBuffer buffer = new StringBuffer(); double absValue = Math.abs(value); if ((absValue > upperCutoff) || (absValue < 0.1 && absValue != 0.0)) { buffer.append(scientificFormat.format(value)); } else { int numFractionDigits = 0; if (value != (int) value) { numFractionDigits = getNumFractionDigits(value); } buffer.append(formatDecimal(value, numFractionDigits)); } if (isPadding) { int size = fieldWidth - buffer.length(); for (int i = 0; i < size; i++) { buffer.append(' '); } } return buffer.toString(); } private int getNumFractionDigits(double value) { value = Math.abs(value); for (int i = 0; i < cutoffTable.length; i++) { if (value < cutoffTable[i]) return sf - i - 1; } return sf - 1; } private String getScientificPattern(int sf) { String pattern = ""0.""; for (int i = 0; i < sf - 1; i++) { pattern += ""#""; } pattern += ""E0""; return pattern; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/utils/HeapSort.java",".java","11172","477","/* * HeapSort.java * * Copyright (C) 2002-2009 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package utils; import java.util.AbstractList; import java.util.Comparator; import java.util.Random; import java.util.Vector; /** * sorts numbers and comparable objects by treating contents of array as a * binary tree. KNOWN BUGS: There is a horrible amount of code duplication here! * * @author Alexei Drummond * @author Korbinian Strimmer * @version $Id: HeapSort.java,v 1.7 2006/02/20 17:36:23 rambaut Exp $ */ public class HeapSort { // // Public stuff // /** * Sorts an array of indices to vector of comparable objects into increasing * order. */ @SuppressWarnings({ ""rawtypes"" }) public static void sort(AbstractList array, int[] indices) { // ensures we are starting with valid indices for (int i = 0; i < indices.length; i++) { indices[i] = i; } int temp; int j, n = array.size(); // turn input array into a heap for (j = n / 2; j > 0; j--) { adjust(array, indices, j, n); } // remove largest elements and put them at the end // of the unsorted region until you are finished for (j = n - 1; j > 0; j--) { temp = indices[0]; indices[0] = indices[j]; indices[j] = temp; adjust(array, indices, 1, j); } } /** * Sorts a vector of comparable objects into increasing order. */ public static void sort(AbstractList array) { Object temp; int j, n = array.size(); // turn input array into a heap for (j = n / 2; j > 0; j--) { adjust(array, j, n); } // remove largest elements and put them at the end // of the unsorted region until you are finished for (j = n - 1; j > 0; j--) { temp = array.get(0); array.set(0, array.get(j)); array.set(j, temp); adjust(array, 1, j); } } /** * Sorts an array of comparable objects into increasing order. */ @SuppressWarnings(""rawtypes"") public static void sort(Comparable[] array) { Comparable temp; int j, n = array.length; // turn input array into a heap for (j = n / 2; j > 0; j--) { adjust(array, j, n); } // remove largest elements and put them at the end // of the unsorted region until you are finished for (j = n - 1; j > 0; j--) { temp = array[0]; array[0] = array[j]; array[j] = temp; adjust(array, 1, j); } } /** * Sorts an array of objects into increasing order given a comparator. */ public static void sort(Object[] array, Comparator c) { Object temp; int j, n = array.length; // turn input array into a heap for (j = n / 2; j > 0; j--) { adjust(array, c, j, n); } // remove largest elements and put them at the end // of the unsorted region until you are finished for (j = n - 1; j > 0; j--) { temp = array[0]; array[0] = array[j]; array[j] = temp; adjust(array, c, 1, j); } } /** * Sorts an array of doubles into increasing order. */ public static void sort(double[] array) { double temp; int j, n = array.length; // turn input array into a heap for (j = n / 2; j > 0; j--) { adjust(array, j, n); } // remove largest elements and put them at the end // of the unsorted region until you are finished for (j = n - 1; j > 0; j--) { temp = array[0]; array[0] = array[j]; array[j] = temp; adjust(array, 1, j); } } /** * Sorts an array of doubles into increasing order, ingoring sign. */ public static void sortAbs(double[] array) { double temp; int j, n = array.length; // turn input array into a heap for (j = n / 2; j > 0; j--) { adjustAbs(array, j, n); } // remove largest elements and put them at the end // of the unsorted region until you are finished for (j = n - 1; j > 0; j--) { temp = array[0]; array[0] = array[j]; array[j] = temp; adjustAbs(array, 1, j); } } /** * Sorts an array of indices into an array of doubles into increasing order. */ public static void sort(double[] array, int[] indices) { // ensures we are starting with valid indices for (int i = 0; i < indices.length; i++) { indices[i] = i; } int temp; int j, n = indices.length; // turn input array into a heap for (j = n / 2; j > 0; j--) { adjust(array, indices, j, n); } // remove largest elements and put them at the end // of the unsorted region until you are finished for (j = n - 1; j > 0; j--) { temp = indices[0]; indices[0] = indices[j]; indices[j] = temp; adjust(array, indices, 1, j); } } /** * test harness for heapsort algorithm */ @SuppressWarnings(""rawtypes"") public static void main(String[] args) { int testSize = 100; // test array of Comparable objects ComparableDouble[] test = new ComparableDouble[testSize]; Random random = new Random(); for (int i = 0; i < test.length; i++) { test[i] = new ComparableDouble(random.nextInt(testSize * 10)); } sort(test); for (ComparableDouble aTest : test) { System.out.print(aTest + "" ""); } System.out.println(); // test index to Vector of Comparable objects Vector testv = new Vector(); int[] indices = new int[testSize]; for (int i = 0; i < testSize; i++) { testv .addElement(new ComparableDouble(random .nextInt(testSize * 10))); } sort(testv, indices); for (int i = 0; i < test.length; i++) { System.out.print(testv.elementAt(indices[i]) + "" ""); } System.out.println(); // test index to array of doubles double[] testd = new double[testSize]; // int[] indices = new int[testSize]; for (int i = 0; i < testSize; i++) { testd[i] = random.nextInt(testSize * 10); } sort(testd, indices); for (int i = 0; i < test.length; i++) { System.out.print(testd[indices[i]] + "" ""); } System.out.println(); } // PRIVATE STUFF /** * helps sort an array of indices into a vector of comparable objects. * Assumes that array[lower+1] through to array[upper] is already in heap * form and then puts array[lower] to array[upper] in heap form. */ @SuppressWarnings({ ""unchecked"", ""rawtypes"" }) private static void adjust(AbstractList array, int[] indices, int lower, int upper) { int j, k; int temp; j = lower; k = lower * 2; while (k <= upper) { if ((k < upper) && (array.get(indices[k - 1]).compareTo( array.get(indices[k])) < 0)) { k += 1; } if (array.get(indices[j - 1]).compareTo(array.get(indices[k - 1])) < 0) { temp = indices[j - 1]; indices[j - 1] = indices[k - 1]; indices[k - 1] = temp; } j = k; k *= 2; } } /** * helps sort an vector of comparable objects. Assumes that array[lower+1] * through to array[upper] is already in heap form and then puts * array[lower] to array[upper] in heap form. */ @SuppressWarnings(""unchecked"") private static void adjust(AbstractList array, int lower, int upper) { int j, k; Object temp; j = lower; k = lower * 2; while (k <= upper) { if ((k < upper) && (((Comparable) array.get(k - 1)).compareTo(array.get(k)) < 0)) { k += 1; } if (((Comparable) array.get(j - 1)).compareTo(array.get(k - 1)) < 0) { temp = array.get(j - 1); array.set(j - 1, array.get(k - 1)); array.set(k - 1, temp); } j = k; k *= 2; } } /** * Assumes that array[lower+1] through to array[upper] is already in heap * form and then puts array[lower] to array[upper] in heap form. */ @SuppressWarnings({ ""unchecked"", ""rawtypes"" }) private static void adjust(Comparable[] array, int lower, int upper) { int j, k; Comparable temp; j = lower; k = lower * 2; while (k <= upper) { if ((k < upper) && (array[k - 1].compareTo(array[k]) < 0)) { k += 1; } if (array[j - 1].compareTo(array[k - 1]) < 0) { temp = array[j - 1]; array[j - 1] = array[k - 1]; array[k - 1] = temp; } j = k; k *= 2; } } /** * Assumes that array[lower+1] through to array[upper] is already in heap * form and then puts array[lower] to array[upper] in heap form. */ private static void adjust(Object[] array, Comparator c, int lower, int upper) { int j, k; Object temp; j = lower; k = lower * 2; while (k <= upper) { if ((k < upper) && (c.compare(array[k - 1], array[k]) < 0)) { k += 1; } if (c.compare(array[j - 1], array[k - 1]) < 0) { temp = array[j - 1]; array[j - 1] = array[k - 1]; array[k - 1] = temp; } j = k; k *= 2; } } /** * helps sort an array of doubles. Assumes that array[lower+1] through to * array[upper] is already in heap form and then puts array[lower] to * array[upper] in heap form. */ private static void adjust(double[] array, int lower, int upper) { int j, k; double temp; j = lower; k = lower * 2; while (k <= upper) { if ((k < upper) && (array[k - 1] < array[k])) { k += 1; } if (array[j - 1] < array[k - 1]) { temp = array[j - 1]; array[j - 1] = array[k - 1]; array[k - 1] = temp; } j = k; k *= 2; } } /** * helps sort an array of doubles. Assumes that array[lower+1] through to * array[upper] is already in heap form and then puts array[lower] to * array[upper] in heap form. */ private static void adjustAbs(double[] array, int lower, int upper) { int j, k; double temp; j = lower; k = lower * 2; while (k <= upper) { if ((k < upper) && (Math.abs(array[k - 1]) < Math.abs(array[k]))) { k += 1; } if (Math.abs(array[j - 1]) < Math.abs(array[k - 1])) { temp = array[j - 1]; array[j - 1] = array[k - 1]; array[k - 1] = temp; } j = k; k *= 2; } } /** * helps sort an array of indices into an array of doubles. Assumes that * array[lower+1] through to array[upper] is already in heap form and then * puts array[lower] to array[upper] in heap form. */ private static void adjust(double[] array, int[] indices, int lower, int upper) { int j, k; int temp; j = lower; k = lower * 2; while (k <= upper) { if ((k < upper) && (array[indices[k - 1]] < array[indices[k]])) { k += 1; } if (array[indices[j - 1]] < array[indices[k - 1]]) { temp = indices[j - 1]; indices[j - 1] = indices[k - 1]; indices[k - 1] = temp; } j = k; k *= 2; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/utils/Holder.java",".java","207","16","package utils; /* * Simulate pass-by-reference in Java * */ public class Holder { public Double value; public Holder(Double initial) { this.value = initial; }// END: Holder }// END: Holder class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/utils/GeoIntermediate.java",".java","2800","116","package utils; public class GeoIntermediate { // Earths radius in km static final double EarthRadius = 6371.0; private double coords[][]; private enum navigationEnum { RHUMB, ARC } private navigationEnum navigationSwitcher; public GeoIntermediate(double startLon, double startLat, double endLon, double endLat, int sliceCount) { navigationSwitcher = navigationEnum.RHUMB; // Calculate full distance double distance = 0; switch (navigationSwitcher) { case RHUMB: distance = Utils.rhumbDistance(startLon, startLat, endLon, endLat); break; case ARC: distance = Utils.greatCircDistSpherLawCos(startLon, startLat, endLon, endLat); break; } double distanceSlice = distance / (double) sliceCount; // Convert to radians double rlon1 = Utils.longNormalise(Math.toRadians(startLon)); double rlat1 = Math.toRadians(startLat); double rlon2 = Utils.longNormalise(Math.toRadians(endLon)); double rlat2 = Math.toRadians(endLat); coords = new double[sliceCount + 1][2]; coords[0][0] = startLon; coords[0][1] = startLat; coords[sliceCount][0] = endLon; coords[sliceCount][1] = endLat; for (int i = 1; i < sliceCount; i++) { distance = distanceSlice; double rDist = distance / EarthRadius; double bearing = 0; // Calculate the bearing switch (navigationSwitcher) { case RHUMB: bearing = Utils.rhumbBearing(rlon1, rlat1, rlon2, rlat2); break; case ARC: bearing = Utils.bearing(rlon1, rlat1, rlon2, rlat2); break; } // use the bearing and the start point to find the // destination double newLonRad = Utils.longNormalise(rlon1 + Math.atan2(Math.sin(bearing) * Math.sin(rDist) * Math.cos(rlat1), Math.cos(rDist) - Math.sin(rlat1) * Math.sin(rlat2))); double newLatRad = Math.asin(Math.sin(rlat1) * Math.cos(rDist) + Math.cos(rlat1) * Math.sin(rDist) * Math.cos(bearing)); // Convert from radians to degrees double newLat = Math.toDegrees(newLatRad); double newLon = Math.toDegrees(newLonRad); coords[i][0] = newLon; coords[i][1] = newLat; // This updates the input to calculate new bearing rlon1 = newLonRad; rlat1 = newLatRad; switch (navigationSwitcher) { case RHUMB: distance = Utils.rhumbDistance(newLon, newLat, endLon, endLat); break; case ARC: distance = Utils.greatCircDistSpherLawCos(newLon, newLat, endLon, endLat); break; } distanceSlice = distance / (sliceCount - i); }// END: sliceCount loop }// END: RhumbIntermediate() public double[][] getCoords() { return coords; } public void setRhumbNavigation() { navigationSwitcher = navigationEnum.RHUMB; } public void setArcNavigation() { navigationSwitcher = navigationEnum.ARC; } }// END: RhumbIntermediate class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/NormalDistribution.java",".java","10119","413","/* * NormalDistribution.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * normal distribution (pdf, cdf, quantile) * * @author Korbinian Strimmer * @version $Id: NormalDistribution.java,v 1.7 2005/05/24 20:26:01 rambaut Exp $ */ public class NormalDistribution implements Distribution { // // Public stuff // /** * Constructor */ public NormalDistribution(double mean, double sd) { this.m = mean; this.sd = sd; } public double getMean() { return m; } public void setMean(double value) { m = value; } public double getSD() { return sd; } public void setSD(double value) { sd = value; } public double pdf(double x) { return pdf(x, m, sd); } public double logPdf(double x) { return logPdf(x, m, sd); } public double cdf(double x) { return cdf(x, m, sd); } public double quantile(double y) { return quantile(y, m, sd); } public double mean() { return mean(m, sd); } public double variance() { return variance(m, sd); } public final UnivariateFunction getProbabilityDensityFunction() { return pdfFunction; } private final UnivariateFunction pdfFunction = new UnivariateFunction() { public final double evaluate(double x) { return pdf(x); } public final double getLowerBound() { return Double.NEGATIVE_INFINITY; } public final double getUpperBound() { return Double.POSITIVE_INFINITY; } }; /** * probability density function * * @param x * argument * @param m * mean * @param sd * standard deviation * @return pdf at x */ public static double pdf(double x, double m, double sd) { double a = 1.0 / (Math.sqrt(2.0 * Math.PI) * sd); double b = -(x - m) * (x - m) / (2.0 * sd * sd); return a * Math.exp(b); } /** * the natural log of the probability density function of the distribution * * @param x * argument * @param m * mean * @param sd * standard deviation * @return log pdf at x */ public static double logPdf(double x, double m, double sd) { double a = 1.0 / (Math.sqrt(2.0 * Math.PI) * sd); double b = -(x - m) * (x - m) / (2.0 * sd * sd); return Math.log(a) + b; } /** * cumulative density function * * @param x * argument * @param m * mean * @param sd * standard deviation * @return cdf at x */ public static double cdf(double x, double m, double sd) { double a = (x - m) / (Math.sqrt(2.0) * sd); return 0.5 * (1.0 + ErrorFunction.erf(a)); } /** * quantiles (=inverse cumulative density function) * * @param z * argument * @param m * mean * @param sd * standard deviation * @return icdf at z */ public static double quantile(double z, double m, double sd) { return m + Math.sqrt(2.0) * sd * ErrorFunction.inverseErf(2.0 * z - 1.0); } /** * mean * * @param m * mean * @param sd * standard deviation * @return mean */ public static double mean(double m, double sd) { return m; } /** * variance * * @param m * mean * @param sd * standard deviation * @return variance */ public static double variance(double m, double sd) { return sd * sd; } /** * A more accurate and faster implementation of the cdf (taken from function * pnorm in the R statistical language) This implementation has * discrepancies depending on the programming language and system * architecture In Java, returned values become zero once z reaches -37.5193 * exactly on the machine tested In the other implementation, the returned * value 0 at about z = -8 In C, this 0 value is reached approximately z = * -37.51938 * * Will later need to be optimised for BEAST * * @param x * argument * @param mu * mean * @param sigma * standard deviation * @param log_p * is p logged * @return cdf at x */ public static double cdf(double x, double mu, double sigma, boolean log_p) { boolean i_tail = false; double p, cp = Double.NaN; if (Double.isNaN(x) || Double.isNaN(mu) || Double.isNaN(sigma)) { return Double.NaN; } if (Double.isInfinite(x) && mu == x) { /* x-mu is NaN */ return Double.NaN; } if (sigma <= 0) { if (sigma < 0) { return Double.NaN; } return (x < mu) ? 0.0 : 1.0; } p = (x - mu) / sigma; if (Double.isInfinite(p)) { return (x < mu) ? 0.0 : 1.0; } x = p; if (Double.isNaN(x)) { return Double.NaN; } double xden, xnum, temp, del, eps, xsq, y; int i; boolean lower, upper; eps = DBL_EPSILON * 0.5; lower = !i_tail; upper = i_tail; y = Math.abs(x); if (y <= 0.67448975) { /* Normal.quantile(3/4, 1, 0) = 0.67448975 */ if (y > eps) { xsq = x * x; xnum = a[4] * xsq; xden = xsq; for (i = 0; i < 3; i++) { xnum = (xnum + a[i]) * xsq; xden = (xden + b[i]) * xsq; } } else { xnum = xden = 0.0; } temp = x * (xnum + a[3]) / (xden + b[3]); if (lower) { p = 0.5 + temp; } if (upper) { cp = 0.5 - temp; } if (log_p) { if (lower) { p = Math.log(p); } if (upper) { cp = Math.log(cp); } } } else if (y <= M_SQRT_32) { /* * Evaluate pnorm for 0.67448975 = Normal.quantile(3/4, 1, 0) < |x| * <= sqrt(32) ~= 5.657 */ xnum = c[8] * y; xden = y; for (i = 0; i < 7; i++) { xnum = (xnum + c[i]) * y; xden = (xden + d[i]) * y; } temp = (xnum + c[7]) / (xden + d[7]); // do_del(y); // swap_tail; // #define do_del(X) \ xsq = ((int) (y * CUTOFF)) * 1.0 / CUTOFF; del = (y - xsq) * (y + xsq); if (log_p) { p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp); if ((lower && x > 0.0) || (upper && x <= 0.0)) { cp = Math.log(1.0 - Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp); } } else { p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp; cp = 1.0 - p; } // #define swap_tail \ if (x > 0.0) { temp = p; if (lower) { p = cp; } cp = temp; } } /* * else |x| > sqrt(32) = 5.657 : the next two case differentiations were * really for lower=T, log=F Particularly *not* for log_p ! Cody had * (-37.5193 < x && x < 8.2924) ; R originally had y < 50 Note that we * do want symmetry(0), lower/upper -> hence use y */ else if (log_p || (lower && -37.5193 < x && x < 8.2924) || (upper && -8.2924 < x && x < 37.5193)) { /* Evaluate pnorm for x in (-37.5, -5.657) union (5.657, 37.5) */ xsq = 1.0 / (x * x); xnum = p_[5] * xsq; xden = xsq; for (i = 0; i < 4; i++) { xnum = (xnum + p_[i]) * xsq; xden = (xden + q[i]) * xsq; } temp = xsq * (xnum + p_[4]) / (xden + q[4]); temp = (M_1_SQRT_2PI - temp) / y; // do_del(x); xsq = ((int) (x * CUTOFF)) * 1.0 / CUTOFF; del = (x - xsq) * (x + xsq); if (log_p) { p = (-xsq * xsq * 0.5) + (-del * 0.5) + Math.log(temp); if ((lower && x > 0.0) || (upper && x <= 0.0)) { cp = Math.log(1.0 - Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp); } } else { p = Math.exp(-xsq * xsq * 0.5) * Math.exp(-del * 0.5) * temp; cp = 1.0 - p; } // swap_tail; if (x > 0.0) { temp = p; if (lower) { p = cp; } cp = temp; } } else { /* no log_p , large x such that probs are 0 or 1 */ if (x > 0) { p = 1.0; cp = 0.0; } else { p = 0.0; cp = 1.0; } } return p; } // Private protected double m, sd; private static final double[] a = { 2.2352520354606839287, 161.02823106855587881, 1067.6894854603709582, 18154.981253343561249, 0.065682337918207449113 }; private static final double[] b = { 47.20258190468824187, 976.09855173777669322, 10260.932208618978205, 45507.789335026729956 }; private static final double[] c = { 0.39894151208813466764, 8.8831497943883759412, 93.506656132177855979, 597.27027639480026226, 2494.5375852903726711, 6848.1904505362823326, 11602.651437647350124, 9842.7148383839780218, 1.0765576773720192317e-8 }; private static final double[] d = { 22.266688044328115691, 235.38790178262499861, 1519.377599407554805, 6485.558298266760755, 18615.571640885098091, 34900.952721145977266, 38912.003286093271411, 19685.429676859990727 }; private static final double[] p_ = { 0.21589853405795699, 0.1274011611602473639, 0.022235277870649807, 0.001421619193227893466, 2.9112874951168792e-5, 0.02307344176494017303 }; private static final double[] q = { 1.28426009614491121, 0.468238212480865118, 0.0659881378689285515, 0.00378239633202758244, 7.29751555083966205e-5 }; private static final int CUTOFF = 16; /* Cutoff allowing exact ""*"" and ""/"" */ private static final double M_SQRT_32 = 5.656854249492380195206754896838; /* * The * square * root * of * 32 */ private static final double M_1_SQRT_2PI = 0.398942280401432677939946059934; private static final double DBL_EPSILON = 2.2204460492503131e-016; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/MersenneTwisterFast.java",".java","27299","937","/* * MersenneTwisterFast.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; import java.io.Serializable; /** * MersenneTwisterFast: *

* A simulation quality fast random number generator (MT19937) with the same * public methods as java.util.Random. *

*

* About the Mersenne Twister. This is a Java version of the C-program for * MT19937: Integer version. next(32) generates one pseudorandom unsigned * integer (32bit) which is uniformly distributed among 0 to 2^32-1 for each * call. next(int bits) >>>'s by (32-bits) to get a value ranging between 0 and * 2^bits-1 long inclusive; hope that's correct. setSeed(seed) set initial * values to the working area of 624 words. For setSeed(seed), seed is any * 32-bit integer except for 0. *

* Reference. M. Matsumoto and T. Nishimura, ""Mersenne Twister: A * 623-Dimensionally Equidistributed Uniform Pseudo-Random Number Generator"", * ACM Transactions on Modeling and Computer Simulation, Vol. 8, No. 1, * January 1998, pp 3--30. *

*

* Bug Fixes. This implementation implements the bug fixes made in Java 1.2's * version of Random, which means it can be used with earlier versions of Java. * See * the JDK 1.2 java.util.Random documentation for further documentation on * the random-number generation contracts made. Additionally, there's an * undocumented bug in the JDK java.util.Random.nextBytes() method, which this * code fixes. *

*

* Important Note. Just like java.util.Random, this generator accepts a long * seed but doesn't use all of it. java.util.Random uses 48 bits. The Mersenne * Twister instead uses 32 bits (int size). So it's best if your seed does not * exceed the int range. *

*

* Sean Luke's web page *

*

* - added shuffling method (Alexei Drummond) *

* - added gamma RV method (Marc Suchard) *

* This is now package private - it should be accessed using the instance in * Random */ class MersenneTwisterFast implements Serializable { /** * */ private static final long serialVersionUID = 6185086957226269797L; // Period parameters private static final int N = 624; private static final int M = 397; private static final int MATRIX_A = 0x9908b0df; // private static final * // constant vector a private static final int UPPER_MASK = 0x80000000; // most significant w-r // bits private static final int LOWER_MASK = 0x7fffffff; // least significant r // bits // Tempering parameters private static final int TEMPERING_MASK_B = 0x9d2c5680; private static final int TEMPERING_MASK_C = 0xefc60000; // #define TEMPERING_SHIFT_U(y) (y >>> 11) // #define TEMPERING_SHIFT_S(y) (y << 7) // #define TEMPERING_SHIFT_T(y) (y << 15) // #define TEMPERING_SHIFT_L(y) (y >>> 18) private int mt[]; // the array for the state vector private int mti; // mti==N+1 means mt[N] is not initialized private int mag01[]; // a good initial seed (of int size, though stored in a long) private static final long GOOD_SEED = 4357; private double nextNextGaussian; private boolean haveNextNextGaussian; // The following can be accessed externally by the static accessor methods // which // inforce synchronization public static final MersenneTwisterFast DEFAULT_INSTANCE = new MersenneTwisterFast(); // Added to curernt time in default constructor, and then adjust to allow // for programs that construct // multiple MersenneTwisterFast in a short amount of time. private static long seedAdditive_ = 0; private long initializationSeed; /** * Constructor using the time of day as default seed. */ public MersenneTwisterFast() { this(System.currentTimeMillis() + seedAdditive_); seedAdditive_ += nextInt(); } /** * Constructor using a given seed. Though you pass this seed in as a long, * it's best to make sure it's actually an integer. * * @param seed * generator starting number, often the time of day. */ private MersenneTwisterFast(long seed) { if (seed == 0) { setSeed(GOOD_SEED); } else { setSeed(seed); } } /** * Initalize the pseudo random number generator. The Mersenne Twister only * uses an integer for its seed; It's best that you don't pass in a long * that's bigger than an int. * * @param seed * from constructor */ public final void setSeed(long seed) { if (seed == 0) { throw new IllegalArgumentException(""Non zero random seed required.""); } initializationSeed = seed; haveNextNextGaussian = false; mt = new int[N]; // setting initial seeds to mt[N] using // the generator Line 25 of Table 1 in // [KNUTH 1981, The Art of Computer Programming // Vol. 2 (2nd Ed.), pp102] // the 0xffffffff is commented out because in Java // ints are always 32 bits; hence i & 0xffffffff == i mt[0] = ((int) seed); // & 0xffffffff; for (mti = 1; mti < N; mti++) mt[mti] = (69069 * mt[mti - 1]); // & 0xffffffff; // mag01[x] = x * MATRIX_A for x=0,1 mag01 = new int[2]; mag01[0] = 0x0; mag01[1] = MATRIX_A; } public final long getSeed() { return initializationSeed; } public final int nextInt() { int y; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return y; } public final short nextShort() { int y; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (short) (y >>> 16); } public final char nextChar() { int y; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (char) (y >>> 16); } public final boolean nextBoolean() { int y; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return ((y >>> 31) != 0); } public final byte nextByte() { int y; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (byte) (y >>> 24); } public final void nextBytes(byte[] bytes) { int y; for (int x = 0; x < bytes.length; x++) { if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) bytes[x] = (byte) (y >>> 24); } } public final long nextLong() { int y; int z; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N - 1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) return (((long) y) << 32) + (long) z; } public final double nextDouble() { int y; int z; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N - 1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) /* derived from nextDouble documentation in jdk 1.2 docs, see top */ return ((((long) (y >>> 6)) << 27) + (z >>> 5)) / (double) (1L << 53); } public final double nextGaussian() { if (haveNextNextGaussian) { haveNextNextGaussian = false; return nextNextGaussian; } else { double v1, v2, s; do { int y; int z; int a; int b; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (z >>> 1) ^ mag01[z & 0x1]; } for (; kk < N - 1; kk++) { z = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (z >>> 1) ^ mag01[z & 0x1]; } z = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (z >>> 1) ^ mag01[z & 0x1]; mti = 0; } z = mt[mti++]; z ^= z >>> 11; // TEMPERING_SHIFT_U(z) z ^= (z << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(z) z ^= (z << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(z) z ^= (z >>> 18); // TEMPERING_SHIFT_L(z) if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { a = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (a >>> 1) ^ mag01[a & 0x1]; } for (; kk < N - 1; kk++) { a = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (a >>> 1) ^ mag01[a & 0x1]; } a = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (a >>> 1) ^ mag01[a & 0x1]; mti = 0; } a = mt[mti++]; a ^= a >>> 11; // TEMPERING_SHIFT_U(a) a ^= (a << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(a) a ^= (a << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(a) a ^= (a >>> 18); // TEMPERING_SHIFT_L(a) if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { b = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (b >>> 1) ^ mag01[b & 0x1]; } for (; kk < N - 1; kk++) { b = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (b >>> 1) ^ mag01[b & 0x1]; } b = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (b >>> 1) ^ mag01[b & 0x1]; mti = 0; } b = mt[mti++]; b ^= b >>> 11; // TEMPERING_SHIFT_U(b) b ^= (b << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(b) b ^= (b << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(b) b ^= (b >>> 18); // TEMPERING_SHIFT_L(b) /* * derived from nextDouble documentation in jdk 1.2 docs, see * top */ v1 = 2 * (((((long) (y >>> 6)) << 27) + (z >>> 5)) / (double) (1L << 53)) - 1; v2 = 2 * (((((long) (a >>> 6)) << 27) + (b >>> 5)) / (double) (1L << 53)) - 1; s = v1 * v1 + v2 * v2; } while (s >= 1); double multiplier = Math.sqrt(-2 * Math.log(s) / s); nextNextGaussian = v2 * multiplier; haveNextNextGaussian = true; return v1 * multiplier; } } public final float nextFloat() { int y; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (y >>> 8) / ((float) (1 << 24)); } /** * Returns an integer drawn uniformly from 0 to n-1. Suffice it to say, n * must be > 0, or an IllegalArgumentException is raised. */ public int nextInt(int n) { if (n <= 0) throw new IllegalArgumentException(""n must be positive""); if ((n & -n) == n) // i.e., n is a power of 2 { int y; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) return (int) ((n * (long) (y >>> 1)) >> 31); } int bits, val; do { int y; if (mti >= N) // generate N words at one time { int kk; for (kk = 0; kk < N - M; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + M] ^ (y >>> 1) ^ mag01[y & 0x1]; } for (; kk < N - 1; kk++) { y = (mt[kk] & UPPER_MASK) | (mt[kk + 1] & LOWER_MASK); mt[kk] = mt[kk + (M - N)] ^ (y >>> 1) ^ mag01[y & 0x1]; } y = (mt[N - 1] & UPPER_MASK) | (mt[0] & LOWER_MASK); mt[N - 1] = mt[M - 1] ^ (y >>> 1) ^ mag01[y & 0x1]; mti = 0; } y = mt[mti++]; y ^= y >>> 11; // TEMPERING_SHIFT_U(y) y ^= (y << 7) & TEMPERING_MASK_B; // TEMPERING_SHIFT_S(y) y ^= (y << 15) & TEMPERING_MASK_C; // TEMPERING_SHIFT_T(y) y ^= (y >>> 18); // TEMPERING_SHIFT_L(y) bits = (y >>> 1); val = bits % n; } while (bits - val + (n - 1) < 0); return val; } /** * Returns a uniform random permutation of int objects in array */ public final void permute(int[] array) { int l = array.length; for (int i = 0; i < l; i++) { int index = nextInt(l - i) + i; int temp = array[index]; array[index] = array[i]; array[i] = temp; } } /** * Shuffles an array. */ public final void shuffle(int[] array) { int l = array.length; for (int i = 0; i < l; i++) { int index = nextInt(l - i) + i; int temp = array[index]; array[index] = array[i]; array[i] = temp; } } /** * Shuffles an array. Shuffles numberOfShuffles times */ public final void shuffle(int[] array, int numberOfShuffles) { int i, j, temp, l = array.length; for (int shuffle = 0; shuffle < numberOfShuffles; shuffle++) { do { i = nextInt(l); j = nextInt(l); } while (i != j); temp = array[j]; array[j] = array[i]; array[i] = temp; } } /** * Returns an array of shuffled indices of length l. * * @param l * length of the array required. */ public int[] shuffled(int l) { int[] array = new int[l]; // initialize array for (int i = 0; i < l; i++) { array[i] = i; } shuffle(array); return array; } /** * Returns a uniform random permutation of ints 0,...,l-1 * * @param l * length of the array required. */ public int[] permuted(int l) { int[] array = new int[l]; // initialize array for (int i = 0; i < l; i++) { array[i] = i; } permute(array); return array; } public double nextGamma(double alpha, double lambda) { /****************************************************************** * * Gamma Distribution - Acceptance Rejection combined with * * Acceptance Complement * * ****************************************************************** * * FUNCTION: - gds samples a random number from the standard * gamma * distribution with parameter a > 0. * Acceptance Rejection gs for a < * 1 , * Acceptance Complement gd for a >= 1 . * REFERENCES: - J.H. * Ahrens, U. Dieter (1974): Computer methods * for sampling from gamma, * beta, Poisson and * binomial distributions, Computing 12, 223-246. * * - J.H. Ahrens, U. Dieter (1982): Generating gamma * variates by a * modified rejection technique, * Communications of the ACM 25, 47-54. * * SUBPROGRAMS: - drand(seed) ... (0,1)-Uniform generator with * * unsigned long integer *seed * - NORMAL(seed) ... Normal generator * N(0,1). * * ******************************************************************/ double a = alpha; double aa = -1.0, aaa = -1.0, b = 0.0, c = 0.0, d = 0.0, e, r, s = 0.0, si = 0.0, ss = 0.0, q0 = 0.0, q1 = 0.0416666664, q2 = 0.0208333723, q3 = 0.0079849875, q4 = 0.0015746717, q5 = -0.0003349403, q6 = 0.0003340332, q7 = 0.0006053049, q8 = -0.0004701849, q9 = 0.0001710320, a1 = 0.333333333, a2 = -0.249999949, a3 = 0.199999867, a4 = -0.166677482, a5 = 0.142873973, a6 = -0.124385581, a7 = 0.110368310, a8 = -0.112750886, a9 = 0.104089866, e1 = 1.000000000, e2 = 0.499999994, e3 = 0.166666848, e4 = 0.041664508, e5 = 0.008345522, e6 = 0.001353826, e7 = 0.000247453; double gds, p, q, t, sign_u, u, v, w, x; double v1, v2, v12; // Check for invalid input values if (a <= 0.0) throw new IllegalArgumentException(); if (lambda <= 0.0) new IllegalArgumentException(); if (a < 1.0) { // CASE A: Acceptance rejection algorithm gs b = 1.0 + 0.36788794412 * a; // Step 1 for (;;) { p = b * nextDouble(); if (p <= 1.0) { // Step 2. Case gds <= 1 gds = Math.exp(Math.log(p) / a); if (Math.log(nextDouble()) <= -gds) return (gds / lambda); } else { // Step 3. Case gds > 1 gds = -Math.log((b - p) / a); if (Math.log(nextDouble()) <= ((a - 1.0) * Math.log(gds))) return (gds / lambda); } } } else { // CASE B: Acceptance complement algorithm gd (gaussian // distribution, box muller transformation) if (a != aa) { // Step 1. Preparations aa = a; ss = a - 0.5; s = Math.sqrt(ss); d = 5.656854249 - 12.0 * s; } // Step 2. Normal deviate do { v1 = 2.0 * nextDouble() - 1.0; v2 = 2.0 * nextDouble() - 1.0; v12 = v1 * v1 + v2 * v2; } while (v12 > 1.0); t = v1 * Math.sqrt(-2.0 * Math.log(v12) / v12); x = s + 0.5 * t; gds = x * x; if (t >= 0.0) return (gds / lambda); // Immediate acceptance u = nextDouble(); // Step 3. Uniform random number if (d * u <= t * t * t) return (gds / lambda); // Squeeze acceptance if (a != aaa) { // Step 4. Set-up for hat case aaa = a; r = 1.0 / a; q0 = ((((((((q9 * r + q8) * r + q7) * r + q6) * r + q5) * r + q4) * r + q3) * r + q2) * r + q1) * r; if (a > 3.686) { if (a > 13.022) { b = 1.77; si = 0.75; c = 0.1515 / s; } else { b = 1.654 + 0.0076 * ss; si = 1.68 / s + 0.275; c = 0.062 / s + 0.024; } } else { b = 0.463 + s - 0.178 * ss; si = 1.235; c = 0.195 / s - 0.079 + 0.016 * s; } } if (x > 0.0) { // Step 5. Calculation of q v = t / (s + s); // Step 6. if (Math.abs(v) > 0.25) { q = q0 - s * t + 0.25 * t * t + (ss + ss) * Math.log(1.0 + v); } else { q = q0 + 0.5 * t * t * ((((((((a9 * v + a8) * v + a7) * v + a6) * v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v; } // Step 7. Quotient acceptance if (Math.log(1.0 - u) <= q) return (gds / lambda); } for (;;) { // Step 8. Double exponential deviate t do { e = -Math.log(nextDouble()); u = nextDouble(); u = u + u - 1.0; sign_u = (u > 0) ? 1.0 : -1.0; t = b + (e * si) * sign_u; } while (t <= -0.71874483771719); // Step 9. Rejection of t v = t / (s + s); // Step 10. New q(t) if (Math.abs(v) > 0.25) { q = q0 - s * t + 0.25 * t * t + (ss + ss) * Math.log(1.0 + v); } else { q = q0 + 0.5 * t * t * ((((((((a9 * v + a8) * v + a7) * v + a6) * v + a5) * v + a4) * v + a3) * v + a2) * v + a1) * v; } if (q <= 0.0) continue; // Step 11. if (q > 0.5) { w = Math.exp(q) - 1.0; } else { w = ((((((e7 * q + e6) * q + e5) * q + e4) * q + e3) * q + e2) * q + e1) * q; } // Step 12. Hat acceptance if (c * u * sign_u <= w * Math.exp(e - 0.5 * t * t)) { x = s + 0.5 * t; return (x * x / lambda); } } } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/Distribution.java",".java","2214","92","/* * Distribution.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * an interface for a distribution. * * @author Alexei Drummond * @author Andrew Rambaut * @version $Id: Distribution.java,v 1.7 2005/05/24 20:26:00 rambaut Exp $ */ public interface Distribution { /** * probability density function of the distribution * * @param x * argument * @return pdf value */ public double pdf(double x); /** * the natural log of the probability density function of the distribution * * @param x * argument * @return log pdf value */ public double logPdf(double x); /** * cumulative density function of the distribution * * @param x * argument * @return cdf value */ public double cdf(double x); /** * quantile (inverse cumulative density function) of the distribution * * @param y * argument * @return icdf value */ public double quantile(double y); /** * mean of the distribution * * @return mean */ public double mean(); /** * variance of the distribution * * @return variance */ public double variance(); /** * @return a probability density function representing this distribution */ public UnivariateFunction getProbabilityDensityFunction(); } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/MultivariateNormalDistribution.java",".java","6871","263","package math; /** * @author Marc Suchard */ public class MultivariateNormalDistribution implements MultivariateDistribution { public static final String TYPE = ""MultivariateNormal""; private final double[] mean; private final double[][] precision; private double[][] variance = null; private double[][] cholesky = null; private Double logDet = null; public MultivariateNormalDistribution(double[] mean, double[][] precision) { this.mean = mean; this.precision = precision; } public String getType() { return TYPE; } public double[][] getVariance() { if (variance == null) { variance = new SymmetricMatrix(precision).inverse().toComponents(); } return variance; } public double[][] getCholeskyDecomposition() { if (cholesky == null) { cholesky = getCholeskyDecomposition(getVariance()); } return cholesky; } public double getLogDet() { if (logDet == null) { logDet = Math.log(calculatePrecisionMatrixDeterminate(precision)); } return logDet; } public double[][] getScaleMatrix() { return precision; } public double[] getMean() { return mean; } public double[] nextMultivariateNormal() { return nextMultivariateNormalCholesky(mean, getCholeskyDecomposition(), 1.0); } public double[] nextMultivariateNormal(double[] x) { return nextMultivariateNormalCholesky(x, getCholeskyDecomposition(), 1.0); } // Scale lives in variance-space public double[] nextScaledMultivariateNormal(double[] mean, double scale) { return nextMultivariateNormalCholesky(mean, getCholeskyDecomposition(), Math.sqrt(scale)); } // Scale lives in variance-space public void nextScaledMultivariateNormal(double[] mean, double scale, double[] result) { nextMultivariateNormalCholesky(mean, getCholeskyDecomposition(), Math .sqrt(scale), result); } public static double calculatePrecisionMatrixDeterminate( double[][] precision) { try { return new Matrix(precision).determinant(); } catch (IllegalDimension e) { throw new RuntimeException(e.getMessage()); } } public double logPdf(double[] x) { return logPdf(x, mean, precision, getLogDet(), 1.0); } public static double logPdf(double[] x, double[] mean, double[][] precision, double logDet, double scale) { if (logDet == Double.NEGATIVE_INFINITY) return logDet; final int dim = x.length; final double[] delta = new double[dim]; final double[] tmp = new double[dim]; for (int i = 0; i < dim; i++) { delta[i] = x[i] - mean[i]; } for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { tmp[i] += delta[j] * precision[j][i]; } } double SSE = 0; for (int i = 0; i < dim; i++) SSE += tmp[i] * delta[i]; return dim * logNormalize + 0.5 * (logDet - dim * Math.log(scale) - SSE / scale); // There was // an error // here. // Variance = (scale * Precision^{-1}) } /* Equal precision, independent dimensions */ public static double logPdf(double[] x, double[] mean, double precision, double scale) { final int dim = x.length; double SSE = 0; for (int i = 0; i < dim; i++) { double delta = x[i] - mean[i]; SSE += delta * delta; } return dim * logNormalize + 0.5 * (dim * (Math.log(precision) - Math.log(scale)) - SSE * precision / scale); } private static double[][] getInverse(double[][] x) { return new SymmetricMatrix(x).inverse().toComponents(); } private static double[][] getCholeskyDecomposition(double[][] variance) { double[][] cholesky; try { cholesky = (new CholeskyDecomposition(variance)).getL(); } catch (IllegalDimension illegalDimension) { throw new RuntimeException( ""Attempted Cholesky decomposition on non-square matrix""); } return cholesky; } public static double[] nextMultivariateNormalPrecision(double[] mean, double[][] precision) { return nextMultivariateNormalVariance(mean, getInverse(precision)); } public static double[] nextMultivariateNormalVariance(double[] mean, double[][] variance) { return nextMultivariateNormalVariance(mean, variance, 1.0); } public static double[] nextMultivariateNormalVariance(double[] mean, double[][] variance, double scale) { return nextMultivariateNormalCholesky(mean, getCholeskyDecomposition(variance), Math.sqrt(scale)); } public static double[] nextMultivariateNormalCholesky(double[] mean, double[][] cholesky) { return nextMultivariateNormalCholesky(mean, cholesky, 1.0); } public static double[] nextMultivariateNormalCholesky(double[] mean, double[][] cholesky, double sqrtScale) { double[] result = new double[mean.length]; nextMultivariateNormalCholesky(mean, cholesky, sqrtScale, result); return result; } public static void nextMultivariateNormalCholesky(double[] mean, double[][] cholesky, double sqrtScale, double[] result) { final int dim = mean.length; System.arraycopy(mean, 0, result, 0, dim); double[] epsilon = new double[dim]; for (int i = 0; i < dim; i++) epsilon[i] = MathUtils.nextGaussian() * sqrtScale; for (int i = 0; i < dim; i++) { for (int j = 0; j <= i; j++) { result[i] += cholesky[i][j] * epsilon[j]; // caution: decomposition returns lower triangular } } } // TODO should be a junit test public static void main(String[] args) { testPdf(); testRandomDraws(); } public static void testPdf() { double[] start = { 1, 2 }; double[] stop = { 0, 0 }; double[][] precision = { { 2, 0.5 }, { 0.5, 1 } }; double scale = 0.2; System.err.println(""logPDF = "" + logPdf(start, stop, precision, Math .log(calculatePrecisionMatrixDeterminate(precision)), scale)); System.err.println(""Should = -19.94863\n""); System.err.println(""logPDF = "" + logPdf(start, stop, 2, 0.2)); System.err.println(""Should = -24.53529\n""); } public static void testRandomDraws() { double[] start = { 1, 2 }; double[][] precision = { { 2, 0.5 }, { 0.5, 1 } }; int length = 100000; System.err.println(""Random draws (via precision) ...""); double[] mean = new double[2]; double[] SS = new double[2]; double[] var = new double[2]; double ZZ = 0; for (int i = 0; i < length; i++) { double[] draw = nextMultivariateNormalPrecision(start, precision); for (int j = 0; j < 2; j++) { mean[j] += draw[j]; SS[j] += draw[j] * draw[j]; } ZZ += draw[0] * draw[1]; } for (int j = 0; j < 2; j++) { mean[j] /= length; SS[j] /= length; var[j] = SS[j] - mean[j] * mean[j]; } ZZ /= length; ZZ -= mean[0] * mean[1]; System.err.println(""Mean: "" + new Vector(mean)); System.err.println(""TRUE: [ 1 2 ]\n""); System.err.println(""MVar: "" + new Vector(var)); System.err.println(""TRUE: [ 0.571 1.14 ]\n""); System.err.println(""Covv: "" + ZZ); System.err.println(""TRUE: -0.286""); } public static final double logNormalize = -0.5 * Math.log(2.0 * Math.PI); } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/GammaFunction.java",".java","5169","215","/* * GammaFunction.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * gamma function * * @author Korbinian Strimmer * @version $Id: GammaFunction.java,v 1.3 2005/05/24 20:26:01 rambaut Exp $ */ public class GammaFunction { // // Public stuff // // Gamma function /** * log Gamma function: ln(gamma(alpha)) for alpha>0, accurate to 10 decimal * places * * @param alpha * argument * @return the log of the gamma function of the given alpha */ public static double lnGamma(double alpha) { // Pike MC & Hill ID (1966) Algorithm 291: Logarithm of the gamma // function. // Communications of the Association for Computing Machinery, 9:684 double x = alpha, f = 0.0, z; if (x < 7) { f = 1; z = x - 1; while (++z < 7) { f *= z; } x = z; f = -Math.log(f); } z = 1 / (x * x); return f + (x - 0.5) * Math.log(x) - x + 0.918938533204673 + (((-0.000595238095238 * z + 0.000793650793651) * z - 0.002777777777778) * z + 0.083333333333333) / x; } /** * Incomplete Gamma function Q(a,x) (a cleanroom implementation of Numerical * Recipes gammq(a,x); in Mathematica this function is called * GammaRegularized) * * @param a * parameter * @param x * argument * @return function value */ public static double incompleteGammaQ(double a, double x) { return 1.0 - incompleteGamma(x, a, lnGamma(a)); } /** * Incomplete Gamma function P(a,x) = 1-Q(a,x) (a cleanroom implementation * of Numerical Recipes gammp(a,x); in Mathematica this function is * 1-GammaRegularized) * * @param a * parameter * @param x * argument * @return function value */ public static double incompleteGammaP(double a, double x) { return incompleteGamma(x, a, lnGamma(a)); } /** * Incomplete Gamma function P(a,x) = 1-Q(a,x) (a cleanroom implementation * of Numerical Recipes gammp(a,x); in Mathematica this function is * 1-GammaRegularized) * * @param a * parameter * @param x * argument * @param lnGammaA * precomputed lnGamma(a) * @return function value */ public static double incompleteGammaP(double a, double x, double lnGammaA) { return incompleteGamma(x, a, lnGammaA); } /** * Returns the incomplete gamma ratio I(x,alpha) where x is the upper limit * of the integration and alpha is the shape parameter. * * @param x * upper limit of integration * @param alpha * shape parameter * @param ln_gamma_alpha * the log gamma function for alpha * @return the incomplete gamma ratio */ private static double incompleteGamma(double x, double alpha, double ln_gamma_alpha) { // (1) series expansion if (alpha>x || x<=1) // (2) continued fraction otherwise // RATNEST FORTRAN by // Bhattacharjee GP (1970) The incomplete gamma integral. Applied // Statistics, // 19: 285-287 (AS32) double accurate = 1e-8, overflow = 1e30; double factor, gin, rn, a, b, an, dif, term; double pn0, pn1, pn2, pn3, pn4, pn5; if (x == 0.0) { return 0.0; } if (x < 0.0 || alpha <= 0.0) { throw new IllegalArgumentException(""Arguments out of bounds""); } factor = Math.exp(alpha * Math.log(x) - x - ln_gamma_alpha); if (x > 1 && x >= alpha) { // continued fraction a = 1 - alpha; b = a + x + 1; term = 0; pn0 = 1; pn1 = x; pn2 = x + 1; pn3 = x * b; gin = pn2 / pn3; do { a++; b += 2; term++; an = a * term; pn4 = b * pn2 - an * pn0; pn5 = b * pn3 - an * pn1; if (pn5 != 0) { rn = pn4 / pn5; dif = Math.abs(gin - rn); if (dif <= accurate) { if (dif <= accurate * rn) { break; } } gin = rn; } pn0 = pn2; pn1 = pn3; pn2 = pn4; pn3 = pn5; if (Math.abs(pn4) >= overflow) { pn0 /= overflow; pn1 /= overflow; pn2 /= overflow; pn3 /= overflow; } } while (true); gin = 1 - factor * gin; } else { // series expansion gin = 1; term = 1; rn = alpha; do { rn++; term *= x / rn; gin += term; } while (term > accurate); gin *= factor / alpha; } return gin; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/NonSymmetricComponents.java",".java","1460","54","/* * NonSymmetricComponents.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * @author Didier H. Besset */ public class NonSymmetricComponents extends Exception { /** * */ private static final long serialVersionUID = 9046634992672041256L; /** * DhbNonSymmetricComponents constructor comment. */ public NonSymmetricComponents() { super(); } /** * DhbNonSymmetricComponents constructor comment. * * @param s * java.lang.String */ public NonSymmetricComponents(String s) { super(s); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/MultivariateDistribution.java",".java","227","17","package math; /** * @author Marc A. Suchard */ public interface MultivariateDistribution { public double logPdf(double[] x); public double[][] getScaleMatrix(); public double[] getMean(); public String getType(); } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/LUPDecomposition.java",".java","7449","332","/* * LUPDecomposition.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * Lower Upper Permutation (LUP) decomposition * * @author Didier H. Besset */ public class LUPDecomposition { /** * Rows of the system */ private double[][] rows; /** * Permutation */ private int[] permutation = null; /** * Permutation's parity */ private int parity = 1; /** * Constructor method * * @param components * double[][] * @throws DhbMatrixAlgebra.DhbIllegalDimension * the supplied matrix is not square */ public LUPDecomposition(double[][] components) throws IllegalDimension { int n = components.length; if (components[0].length != n) throw new IllegalDimension(""Illegal system: a"" + n + "" by "" + components[0].length + "" matrix is not a square matrix""); rows = components; initialize(); } /** * Constructor method. * * @param m * DhbMatrixAlgebra.Matrix * @throws DhbMatrixAlgebra.DhbIllegalDimension * the supplied matrix is not square */ public LUPDecomposition(Matrix m) throws IllegalDimension { if (!m.isSquare()) throw new IllegalDimension(""Supplied matrix is not a square matrix""); initialize(m.components); } /** * Constructor method. * * @param m * DhbMatrixAlgebra.DhbSymmetricMatrix */ public LUPDecomposition(SymmetricMatrix m) { initialize(m.components); } /** * @param xTilde * double[] * @return double[] */ private double[] backwardSubstitution(double[] xTilde) { int n = rows.length; double[] answer = new double[n]; for (int i = n - 1; i >= 0; i--) { answer[i] = xTilde[i]; for (int j = i + 1; j < n; j++) answer[i] -= rows[i][j] * answer[j]; answer[i] /= rows[i][i]; } return answer; } private void decompose() { int n = rows.length; permutation = new int[n]; for (int i = 0; i < n; i++) permutation[i] = i; parity = 1; try { for (int i = 0; i < n; i++) { swapRows(i, largestPivot(i)); pivot(i); } } catch (ArithmeticException e) { parity = 0; } } /** * @return boolean true if decomposition was done already */ private boolean decomposed() { if (parity == 1 && permutation == null) decompose(); return parity != 0; } /** * @param c * double[] * @return double[] */ public double determinant() { if (!decomposed()) return Double.NaN; double determinant = parity; for (int i = 0; i < rows.length; i++) determinant *= rows[i][i]; return determinant; } public boolean isPD() { for (int i = 0; i < rows.length; i++) { if (rows[i][i] <= 0) return false; } return true; } /** * @param c * double[] * @return double[] */ private double[] forwardSubstitution(double[] c) { int n = rows.length; double[] answer = new double[n]; for (int i = 0; i < n; i++) { answer[i] = c[permutation[i]]; for (int j = 0; j <= i - 1; j++) answer[i] -= rows[i][j] * answer[j]; } return answer; } private void initialize() { permutation = null; parity = 1; } /** * @param components * double[][] components obtained from constructor methods. */ private void initialize(double[][] components) { int n = components.length; rows = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) rows[i][j] = components[i][j]; } initialize(); } /** * @param c * double[] * @return double[] */ public double[][] inverseMatrixComponents() { if (!decomposed()) return null; int n = rows.length; double[][] inverseRows = new double[n][n]; double[] column = new double[n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) column[j] = 0; column[i] = 1; column = solve(column); for (int j = 0; j < n; j++) inverseRows[i][j] = column[j]; } return inverseRows; } /** * @param k * int * @return int */ private int largestPivot(int k) { double maximum = Math.abs(rows[k][k]); double abs; int index = k; for (int i = k + 1; i < rows.length; i++) { abs = Math.abs(rows[i][k]); if (abs > maximum) { maximum = abs; index = i; } } return index; } /** * @param k * int */ private void pivot(int k) { double inversePivot = 1 / rows[k][k]; int k1 = k + 1; int n = rows.length; for (int i = k1; i < n; i++) { rows[i][k] *= inversePivot; for (int j = k1; j < n; j++) rows[i][j] -= rows[i][k] * rows[k][j]; } } /** * @param c * double[] * @return double[] */ public double[] solve(double[] c) { return decomposed() ? backwardSubstitution(forwardSubstitution(c)) : null; } /** * @param c * double[] * @return double[] */ public Vector solve(Vector c) { double[] components = solve(c.components); if (components == null) return null; return components == null ? null : new Vector(components); } /** * @param i * int * @param k * int */ private void swapRows(int i, int k) { if (i != k) { double temp; for (int j = 0; j < rows.length; j++) { temp = rows[i][j]; rows[i][j] = rows[k][j]; rows[k][j] = temp; } int nTemp; nTemp = permutation[i]; permutation[i] = permutation[k]; permutation[k] = nTemp; parity = -parity; } } /** * Make sure the supplied matrix components are those of a symmetric matrix * * @param components * double */ public static void symmetrizeComponents(double[][] components) { for (int i = 0; i < components.length; i++) { for (int j = i + 1; j < components.length; j++) { components[i][j] += components[j][i]; components[i][j] *= 0.5; components[j][i] = components[i][j]; } } } /** * Returns a String that represents the value of this object. * * @return a string representation of the receiver */ public String toString() { StringBuffer sb = new StringBuffer(); char[] separator = { '[', ' ' }; int n = rows.length; for (int i = 0; i < n; i++) { separator[0] = '{'; for (int j = 0; j < n; j++) { sb.append(separator); sb.append(rows[i][j]); separator[0] = ' '; } sb.append('}'); sb.append('\n'); } if (permutation != null) { sb.append(parity == 1 ? '+' : '-'); sb.append(""( "" + permutation[0]); for (int i = 1; i < n; i++) sb.append("", "" + permutation[i]); sb.append(')'); sb.append('\n'); } return sb.toString(); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/UnivariateFunction.java",".java","1408","55","/* * UnivariateFunction.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * Interface for a function of one variable. * * @author Korbinian Strimmer */ public interface UnivariateFunction { /** * compute function value * * @param argument * * @return function value */ double evaluate(double argument); /** * * @return lower bound of argument */ double getLowerBound(); /** * * @return upper bound of argument */ double getUpperBound(); } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/Vector.java",".java","10669","380","/* * Vector.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * Vector implementation * * @author Didier H. Besset */ public class Vector { protected double[] components; /** * Create a vector of given dimension. NOTE: The supplied array of * components must not be changed. * * @param comp * double[] */ public Vector(double comp[]) throws NegativeArraySizeException { int n = comp.length; if (n <= 0) throw new NegativeArraySizeException( ""Vector components cannot be empty""); components = new double[n]; System.arraycopy(comp, 0, components, 0, n); } public Vector(int comp[]) throws NegativeArraySizeException { int n = comp.length; if (n <= 0) throw new NegativeArraySizeException( ""Vector components cannot be empty""); components = new double[n]; // System.arraycopy( comp, 0, components, 0, n); for (int i = 0; i < n; i++) components[i] = comp[i]; } /** * Create a vector of given dimension. * * @param dimension * int dimension of the vector; must be positive. */ public Vector(int dimension) throws NegativeArraySizeException { if (dimension <= 0) throw new NegativeArraySizeException(""Requested vector size: "" + dimension); components = new double[dimension]; clear(); } /** * @param v * DHBmatrixAlgebra.DhbVector * @throws DHBmatrixAlgebra.DhbIllegalDimension * if the vector and supplied vector do not have the same * dimension. */ public void accumulate(double[] x) throws IllegalDimension { if (this.dimension() != x.length) throw new IllegalDimension(""Attempt to add a "" + this.dimension() + ""-dimension vector to a "" + x.length + ""-dimension array""); for (int i = 0; i < this.dimension(); i++) components[i] += x[i]; } /** * @param v * DHBmatrixAlgebra.DhbVector * @throws DHBmatrixAlgebra.DhbIllegalDimension * if the vector and supplied vector do not have the same * dimension. */ public void accumulate(Vector v) throws IllegalDimension { if (this.dimension() != v.dimension()) throw new IllegalDimension(""Attempt to add a "" + this.dimension() + ""-dimension vector to a "" + v.dimension() + ""-dimension vector""); for (int i = 0; i < this.dimension(); i++) components[i] += v.components[i]; } /** * @param v * DHBmatrixAlgebra.DhbVector * @throws DHBmatrixAlgebra.DhbIllegalDimension * if the vector and supplied vector do not have the same * dimension. */ public void accumulateNegated(double[] x) throws IllegalDimension { if (this.dimension() != x.length) throw new IllegalDimension(""Attempt to add a "" + this.dimension() + ""-dimension vector to a "" + x.length + ""-dimension array""); for (int i = 0; i < this.dimension(); i++) components[i] -= x[i]; } /** * @param v * DHBmatrixAlgebra.DhbVector * @throws DHBmatrixAlgebra.DhbIllegalDimension * if the vector and supplied vector do not have the same * dimension. */ public void accumulateNegated(Vector v) throws IllegalDimension { if (this.dimension() != v.dimension()) throw new IllegalDimension(""Attempt to add a "" + this.dimension() + ""-dimension vector to a "" + v.dimension() + ""-dimension vector""); for (int i = 0; i < this.dimension(); i++) components[i] -= v.components[i]; } /** * @param v * DHBmatrixAlgebra.DhbVector * @return DHBmatrixAlgebra.DhbVector sum of the vector with the supplied * vector * @throws DHBmatrixAlgebra.DhbIllegalDimension * if the vector and supplied vector do not have the same * dimension. */ public Vector add(Vector v) throws IllegalDimension { if (this.dimension() != v.dimension()) throw new IllegalDimension(""Attempt to add a "" + this.dimension() + ""-dimension vector to a "" + v.dimension() + ""-dimension vector""); double[] newComponents = new double[this.dimension()]; for (int i = 0; i < this.dimension(); i++) newComponents[i] = components[i] + v.components[i]; return new Vector(newComponents); } /** * Sets all components of the receiver to 0. */ public void clear() { for (int i = 0; i < components.length; i++) components[i] = 0; } /** * @param n * int * @return double */ public double component(int n) { return components[n]; } /** * Returns the dimension of the vector. * * @return int */ public int dimension() { return components.length; } /** * @param v * DHBmatrixAlgebra.DhbVector * @return true if the supplied vector is equal to the receiver */ public boolean equals(Vector v) { int n = this.dimension(); if (v.dimension() != n) return false; for (int i = 0; i < n; i++) { if (v.components[i] != components[i]) return false; } return true; } /** * Computes the norm of a vector. */ public double norm() { double sum = 0; for (int i = 0; i < components.length; i++) sum += components[i] * components[i]; return Math.sqrt(sum); } /** * @param x * double */ public Vector normalizedBy(double x) { for (int i = 0; i < this.dimension(); i++) components[i] /= x; return this; } /** * Computes the product of the vector by a number. * * @param d * double * @return DHBmatrixAlgebra.DhbVector */ public Vector product(double d) { double newComponents[] = new double[components.length]; for (int i = 0; i < components.length; i++) newComponents[i] = d * components[i]; return new Vector(newComponents); } /** * Compute the scalar product (or dot product) of two vectors. * * @param v * DHBmatrixAlgebra.DhbVector * @return double the scalar product of the receiver with the argument * @throws DHBmatrixAlgebra.DhbIllegalDimension * if the dimension of v is not the same. */ public double product(Vector v) throws IllegalDimension { int n = v.dimension(); if (components.length != n) throw new IllegalDimension( ""Dot product with mismatched dimensions: "" + components.length + "", "" + n); return secureProduct(v); } /** * Computes the product of the transposed vector with a matrix * * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.DhbVector */ public Vector product(Matrix a) throws IllegalDimension { int n = a.rows(); int m = a.columns(); if (this.dimension() != n) throw new IllegalDimension(""Product error: transposed of a "" + this.dimension() + ""-dimension vector cannot be multiplied with a "" + n + "" by "" + m + "" matrix""); return secureProduct(a); } /** * @param x * double */ public Vector scaledBy(double x) { for (int i = 0; i < this.dimension(); i++) components[i] *= x; return this; } /** * Compute the scalar product (or dot product) of two vectors. No dimension * checking is made. * * @param v * DHBmatrixAlgebra.DhbVector * @return double the scalar product of the receiver with the argument */ protected double secureProduct(Vector v) { double sum = 0; for (int i = 0; i < v.dimension(); i++) sum += components[i] * v.components[i]; return sum; } /** * Computes the product of the transposed vector with a matrix * * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.DhbVector */ protected Vector secureProduct(Matrix a) { int n = a.rows(); int m = a.columns(); double[] vectorComponents = new double[m]; for (int j = 0; j < m; j++) { vectorComponents[j] = 0; for (int i = 0; i < n; i++) vectorComponents[j] += components[i] * a.components[i][j]; } return new Vector(vectorComponents); } /** * @param v * DHBmatrixAlgebra.DhbVector * @return DHBmatrixAlgebra.DhbVector subtract the supplied vector to the * receiver * @throws DHBmatrixAlgebra.DhbIllegalDimension * if the vector and supplied vector do not have the same * dimension. */ public Vector subtract(Vector v) throws IllegalDimension { if (this.dimension() != v.dimension()) throw new IllegalDimension(""Attempt to add a "" + this.dimension() + ""-dimension vector to a "" + v.dimension() + ""-dimension vector""); double[] newComponents = new double[this.dimension()]; for (int i = 0; i < this.dimension(); i++) newComponents[i] = components[i] - v.components[i]; return new Vector(newComponents); } /** * @param v * MatrixAlgebra.DhbVector second vector to build tensor product * with. * @return MatrixAlgebra.Matrix tensor product with the specified vector */ public Matrix tensorProduct(Vector v) { int n = dimension(); int m = v.dimension(); double[][] newComponents = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) newComponents[i][j] = components[i] * v.components[j]; } return n == m ? new SymmetricMatrix(newComponents) : new Matrix( newComponents); } /** * @return double[] a copy of the components of the receiver. */ public double[] toComponents() { int n = dimension(); double[] answer = new double[n]; System.arraycopy(components, 0, answer, 0, n); return answer; } /** * Returns a string representation of the vector. * * @return java.lang.String */ public String toString() { StringBuffer sb = new StringBuffer(); char[] separator = { '[', ' ' }; for (int i = 0; i < components.length; i++) { sb.append(separator); sb.append(components[i]); separator[0] = ','; } sb.append(']'); return sb.toString(); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/ErrorFunction.java",".java","3045","113","/* * ErrorFunction.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * error function and related stuff * * @version $Id: ErrorFunction.java,v 1.3 2005/05/24 20:26:00 rambaut Exp $ * * @author Korbinian Strimmer */ public class ErrorFunction { // // Public stuff // /** * error function * * @param x * argument * * @return function value */ public static double erf(double x) { if (x > 0.0) { return GammaFunction.incompleteGammaP(0.5, x * x); } else if (x < 0.0) { return -GammaFunction.incompleteGammaP(0.5, x * x); } else { return 0.0; } } /** * complementary error function = 1-erf(x) * * @param x * argument * * @return function value */ public static double erfc(double x) { return 1.0 - erf(x); } /** * inverse error function * * @param z * argument * * @return function value */ public static double inverseErf(double z) { return pointNormal(0.5 * z + 0.5) / Math.sqrt(2.0); } // Private // Returns z so that Prob{x 0.0); L[j][j] = Math.sqrt(Math.max(d, 0.0)); /* * for (int k = j+1; k < n; k++) { L[j][k] = 0.0; } */ } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/MathUtils.java",".java","9961","425","/* * MathUtils.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; import java.text.NumberFormat; import java.text.ParseException; import jebl.math.GammaFunction; import utils.NumberFormatter; /** * Handy utility functions which have some Mathematical relavance. * * @author Matthew Goode * @author Alexei Drummond * @author Gerton Lunter * @version $Id: MathUtils.java,v 1.13 2006/08/31 14:57:24 rambaut Exp $ */ public class MathUtils { private MathUtils() { } /** * A random number generator that is initialized with the clock when this * class is loaded into the JVM. Use this for all random numbers. Note: This * method or getting random numbers in not thread-safe. Since * MersenneTwisterFast is currently (as of 9/01) not synchronized using this * function may cause concurrency issues. Use the static get methods of the * MersenneTwisterFast class for access to a single instance of the class, * that has synchronization. */ private static final MersenneTwisterFast random = MersenneTwisterFast.DEFAULT_INSTANCE; // Chooses one category if a cumulative probability distribution is given public static int randomChoice(double[] cf) { double U = random.nextDouble(); int s; if (U <= cf[0]) { s = 0; } else { for (s = 1; s < cf.length; s++) { if (U <= cf[s] && U > cf[s - 1]) { break; } } } return s; } /** * @param pdf * array of unnormalized probabilities * @return a sample according to an unnormalized probability distribution */ public static int randomChoicePDF(double[] pdf) { double U = random.nextDouble() * getTotal(pdf); for (int i = 0; i < pdf.length; i++) { U -= pdf[i]; if (U < 0.0) { return i; } } for (int i = 0; i < pdf.length; i++) { System.out.println(i + ""\t"" + pdf[i]); } throw new Error( ""randomChoiceUnnormalized falls through -- negative components in input distribution?""); } /** * @param array * to normalize * @return a new double array where all the values sum to 1. Relative ratios * are preserved. */ public static double[] getNormalized(double[] array) { double[] newArray = new double[array.length]; double total = getTotal(array); for (int i = 0; i < array.length; i++) { newArray[i] = array[i] / total; } return newArray; } /** * @param array * entries to be summed * @param start * start position * @param end * the index of the element after the last one to be included * @return the total of a the values in a range of an array */ public static double getTotal(double[] array, int start, int end) { double total = 0.0; for (int i = start; i < end; i++) { total += array[i]; } return total; } /** * @param array * to sum over * @return the total of the values in an array */ public static double getTotal(double[] array) { return getTotal(array, 0, array.length); } // ===================== (Synchronized) Static access methods to the private // random instance =========== /** * Access a default instance of this class, access is synchronized */ public static long getSeed() { synchronized (random) { return random.getSeed(); } } /** * Access a default instance of this class, access is synchronized */ public static void setSeed(long seed) { synchronized (random) { random.setSeed(seed); } } /** * Access a default instance of this class, access is synchronized */ public static byte nextByte() { synchronized (random) { return random.nextByte(); } } /** * Access a default instance of this class, access is synchronized */ public static boolean nextBoolean() { synchronized (random) { return random.nextBoolean(); } } /** * Access a default instance of this class, access is synchronized */ public static void nextBytes(byte[] bs) { synchronized (random) { random.nextBytes(bs); } } /** * Access a default instance of this class, access is synchronized */ public static char nextChar() { synchronized (random) { return random.nextChar(); } } /** * Access a default instance of this class, access is synchronized */ public static double nextGaussian() { synchronized (random) { return random.nextGaussian(); } } // Mean = alpha / lambda // Variance = alpha / (lambda*lambda) public static double nextGamma(double alpha, double lambda) { synchronized (random) { return random.nextGamma(alpha, lambda); } } /** * Access a default instance of this class, access is synchronized * * @return a pseudo random double precision floating point number in [01) */ public static double nextDouble() { synchronized (random) { return random.nextDouble(); } } /** * @return log of random variable in [0,1] */ public static double randomLogDouble() { return Math.log(nextDouble()); } /** * Access a default instance of this class, access is synchronized */ public static double nextExponential(double lambda) { synchronized (random) { return -1.0 * Math.log(1 - random.nextDouble()) / lambda; } } /** * Access a default instance of this class, access is synchronized */ public static double nextInverseGaussian(double mu, double lambda) { synchronized (random) { /* * CODE TAKEN FROM WIKIPEDIA. TESTING DONE WITH RESULTS GENERATED IN * R AND LOOK COMPARABLE */ double v = random.nextGaussian(); // sample from a normal // distribution with a mean of 0 // and 1 standard deviation double y = v * v; double x = mu + (mu * mu * y) / (2 * lambda) - (mu / (2 * lambda)) * Math.sqrt(4 * mu * lambda * y + mu * mu * y * y); double test = MathUtils.nextDouble(); // sample from a uniform // distribution between 0 // and 1 if (test <= (mu) / (mu + x)) { return x; } else { return (mu * mu) / x; } } } /** * Access a default instance of this class, access is synchronized */ public static float nextFloat() { synchronized (random) { return random.nextFloat(); } } /** * Access a default instance of this class, access is synchronized */ public static long nextLong() { synchronized (random) { return random.nextLong(); } } /** * Access a default instance of this class, access is synchronized */ public static short nextShort() { synchronized (random) { return random.nextShort(); } } /** * Access a default instance of this class, access is synchronized */ public static int nextInt() { synchronized (random) { return random.nextInt(); } } /** * Access a default instance of this class, access is synchronized */ public static int nextInt(int n) { synchronized (random) { return random.nextInt(n); } } /** * * @param low * @param high * @return uniform between low and high */ public static double uniform(double low, double high) { return low + nextDouble() * (high - low); } /** * Shuffles an array. */ public static void shuffle(int[] array) { synchronized (random) { random.shuffle(array); } } /** * Shuffles an array. Shuffles numberOfShuffles times */ public static void shuffle(int[] array, int numberOfShuffles) { synchronized (random) { random.shuffle(array, numberOfShuffles); } } /** * Returns an array of shuffled indices of length l. * * @param l * length of the array required. */ public static int[] shuffled(int l) { synchronized (random) { return random.shuffled(l); } } public static int[] sampleIndicesWithReplacement(int length) { synchronized (random) { int[] result = new int[length]; for (int i = 0; i < length; i++) result[i] = random.nextInt(length); return result; } } /** * Permutes an array. */ public static void permute(int[] array) { synchronized (random) { random.permute(array); } } /** * Returns a uniform random permutation of 0,...,l-1 * * @param l * length of the array required. */ public static int[] permuted(int l) { synchronized (random) { return random.permuted(l); } } public static double logHyperSphereVolume(int dimension, double radius) { return dimension * (0.5723649429247001 + Math.log(radius)) + -GammaFunction.lnGamma(dimension / 2.0 + 1.0); } /** * Returns sqrt(a^2 + b^2) without under/overflow. */ public static double hypot(double a, double b) { double r; if (Math.abs(a) > Math.abs(b)) { r = b / a; r = Math.abs(a) * Math.sqrt(1 + r * r); } else if (b != 0) { r = a / b; r = Math.abs(b) * Math.sqrt(1 + r * r); } else { r = 0.0; } return r; } /** * return double *.???? * * @param value * @param sf * @return */ public static double round(double value, int sf) { NumberFormatter formatter = new NumberFormatter(sf); try { return NumberFormat.getInstance().parse(formatter.format(value)) .doubleValue(); } catch (ParseException e) { return value; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/SymmetricMatrix.java",".java","10863","368","/* * SymmetricMatrix.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * Symmetric matrix * * @author Didier H. Besset */ public class SymmetricMatrix extends Matrix { private static int lupCRLCriticalDimension = 36; /** * Creates a symmetric matrix with given components. * * @param a * double[][] */ public SymmetricMatrix(double[][] a) { super(a); } /** * @param n * int * @throws java.lang.NegativeArraySizeException * if n <= 0 */ public SymmetricMatrix(int n) throws NegativeArraySizeException { super(n, n); } /** * Constructor method. * * @param n * int * @param m * int * @throws java.lang.NegativeArraySizeException * if n,m <= 0 */ public SymmetricMatrix(int n, int m) throws NegativeArraySizeException { super(n, m); } /** * @param a * Matrix * @return SymmetricMatrix sum of the matrix with the supplied matrix. * @throws IllegalDimension * if the supplied matrix does not have the same dimensions. */ public SymmetricMatrix add(SymmetricMatrix a) throws IllegalDimension { return new SymmetricMatrix(addComponents(a)); } /** * Answers the inverse of the receiver computed via the CRL algorithm. * * @return MatrixAlgebra.SymmetricMatrix * @throws java.lang.ArithmeticException * if the matrix is singular. */ private SymmetricMatrix crlInverse() throws ArithmeticException { if (rows() == 1) return inverse1By1(); else if (rows() == 2) return inverse2By2(); Matrix[] splitMatrices = split(); SymmetricMatrix b1 = (SymmetricMatrix) splitMatrices[0].inverse(); Matrix cb1 = splitMatrices[2].secureProduct(b1); SymmetricMatrix cb1cT = new SymmetricMatrix(cb1 .productWithTransposedComponents(splitMatrices[2])); splitMatrices[1] = ((SymmetricMatrix) splitMatrices[1]).secureSubtract( cb1cT).inverse(); splitMatrices[2] = splitMatrices[1].secureProduct(cb1); splitMatrices[0] = b1.secureAdd(new SymmetricMatrix(cb1 .transposedProductComponents(splitMatrices[2]))); return SymmetricMatrix.join(splitMatrices); } /** * @return MatrixAlgebra.SymmetricMatrix * @throws matrixAlgebra.IllegalDimension * The supplied components are not those of a square matrix. * @throws matrixAlgebra.NonSymmetricComponents * The supplied components are not symmetric. * @param comp * double[][] components of the matrix */ public static SymmetricMatrix fromComponents(double[][] comp) throws IllegalDimension, NonSymmetricComponents { if (comp.length != comp[0].length) throw new IllegalDimension(""Non symmetric components: a "" + comp.length + "" by "" + comp[0].length + "" matrix cannot be symmetric""); for (int i = 0; i < comp.length; i++) { for (int j = 0; j < i; j++) { if (comp[i][j] != comp[j][i]) throw new NonSymmetricComponents( ""Non symmetric components: a["" + i + ""]["" + j + ""]= "" + comp[i][j] + "", a["" + j + ""]["" + i + ""]= "" + comp[j][i]); } } return new SymmetricMatrix(comp); } /** * @param n * int * @return SymmetricMatrix an identity matrix of size n */ public static SymmetricMatrix identityMatrix(int n) { double[][] a = new double[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) a[i][j] = 0; a[i][i] = 1; } return new SymmetricMatrix(a); } /** * @return Matrix inverse of the receiver. * @throws java.lang.ArithmeticException * if the receiver is a singular matrix. */ public Matrix inverse() throws ArithmeticException { return rows() < lupCRLCriticalDimension ? new SymmetricMatrix( (new LUPDecomposition(this)).inverseMatrixComponents()) : crlInverse(); } /** * Compute the inverse of the receiver in the case of a 1 by 1 matrix. * Internal use only: no check is made. * * @return MatrixAlgebra.SymmetricMatrix */ private SymmetricMatrix inverse1By1() { double[][] newComponents = new double[1][1]; newComponents[0][0] = 1 / components[0][0]; return new SymmetricMatrix(newComponents); } /** * Compute the inverse of the receiver in the case of a 2 by 2 matrix. * Internal use only: no check is made. * * @return MatrixAlgebra.SymmetricMatrix */ private SymmetricMatrix inverse2By2() { double[][] newComponents = new double[2][2]; double inverseDeterminant = 1 / (components[0][0] * components[1][1] - components[0][1] * components[1][0]); newComponents[0][0] = inverseDeterminant * components[1][1]; newComponents[1][1] = inverseDeterminant * components[0][0]; newComponents[0][1] = newComponents[1][0] = -inverseDeterminant * components[1][0]; return new SymmetricMatrix(newComponents); } /** * Build a matrix from 3 parts (inverse of split). * * @param a * MatrixAlgebra.Matrix[] * @return MatrixAlgebra.SymmetricMatrix */ private static SymmetricMatrix join(Matrix[] a) { int p = a[0].rows(); int n = p + a[1].rows(); double[][] newComponents = new double[n][n]; for (int i = 0; i < p; i++) { for (int j = 0; j < p; j++) newComponents[i][j] = a[0].components[i][j]; for (int j = p; j < n; j++) newComponents[i][j] = newComponents[j][i] = -a[2].components[j - p][i]; } for (int i = p; i < n; i++) { for (int j = p; j < n; j++) newComponents[i][j] = a[1].components[i - p][j - p]; } return new SymmetricMatrix(newComponents); } /** * @param n * int * @return int */ private int largestPowerOf2SmallerThan(int n) { int m = 2; int m2; while (true) { m2 = 2 * m; if (m2 >= n) return m; m = m2; } } /** * @param a * double * @return MatrixAlgebra.SymmetricMatrix */ public Matrix product(double a) { return new SymmetricMatrix(productComponents(a)); } /** * @param a * Matrix * @return Matrix product of the receiver with the supplied matrix * @throws IllegalDimension * If the number of columns of the receivers are not equal to * the number of rows of the supplied matrix. */ public SymmetricMatrix product(SymmetricMatrix a) throws IllegalDimension { return new SymmetricMatrix(productComponents(a)); } /** * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.Matrix product of the receiver with the transpose * of the supplied matrix * @throws MatrixAlgebra.IllegalDimension * If the number of columns of the receiver are not equal to the * number of columns of the supplied matrix. */ public SymmetricMatrix productWithTransposed(SymmetricMatrix a) throws IllegalDimension { if (a.columns() != columns()) throw new IllegalDimension(""Operation error: cannot multiply a "" + rows() + "" by "" + columns() + "" matrix with the transpose of a "" + a.rows() + "" by "" + a.columns() + "" matrix""); return new SymmetricMatrix(productWithTransposedComponents(a)); } /** * Same as add ( SymmetricMatrix a), but without dimension checking. * * @param a * MatrixAlgebra.SymmetricMatrix * @return MatrixAlgebra.SymmetricMatrix */ protected SymmetricMatrix secureAdd(SymmetricMatrix a) { return new SymmetricMatrix(addComponents(a)); } /** * Same as product(SymmetricMatrix a), but without dimension checking. * * @param a * MatrixAlgebra.SymmetricMatrix * @return MatrixAlgebra.SymmetricMatrix */ protected SymmetricMatrix secureProduct(SymmetricMatrix a) { return new SymmetricMatrix(productComponents(a)); } /** * Same as subtract ( SymmetricMatrix a), but without dimension checking. * * @param a * MatrixAlgebra.SymmetricMatrix * @return MatrixAlgebra.SymmetricMatrix */ protected SymmetricMatrix secureSubtract(SymmetricMatrix a) { return new SymmetricMatrix(subtractComponents(a)); } /** * Divide the receiver into 3 matrices of approximately equal dimension. * * @return MatrixAlgebra.Matrix[] Array of splitted matrices */ private Matrix[] split() { int n = rows(); int p = largestPowerOf2SmallerThan(n); int q = n - p; double[][] a = new double[p][p]; double[][] b = new double[q][q]; double[][] c = new double[q][p]; for (int i = 0; i < p; i++) { for (int j = 0; j < p; j++) a[i][j] = components[i][j]; for (int j = p; j < n; j++) c[j - p][i] = components[i][j]; } for (int i = p; i < n; i++) { for (int j = p; j < n; j++) b[i - p][j - p] = components[i][j]; } Matrix[] answer = new Matrix[3]; answer[0] = new SymmetricMatrix(a); answer[1] = new SymmetricMatrix(b); answer[2] = new Matrix(c); return answer; } /** * @param a * matrixAlgebra.SymmetricMatrix * @return matrixAlgebra.SymmetricMatrix * @throws matrixAlgebra.IllegalDimension * (from constructor). */ public SymmetricMatrix subtract(SymmetricMatrix a) throws IllegalDimension { return new SymmetricMatrix(subtractComponents(a)); } /** * @return matrixAlgebra.Matrix the same matrix */ public Matrix transpose() { return this; } /** * @param a * MatrixAlgebra.SymmetricMatrix * @return MatrixAlgebra.SymmetricMatrix product of the tranpose of the * receiver with the supplied matrix * @throws MatrixAlgebra.IllegalDimension * If the number of rows of the receiver are not equal to the * number of rows of the supplied matrix. */ public SymmetricMatrix transposedProduct(SymmetricMatrix a) throws IllegalDimension { if (a.rows() != rows()) throw new IllegalDimension( ""Operation error: cannot multiply a tranposed "" + rows() + "" by "" + columns() + "" matrix with a "" + a.rows() + "" by "" + a.columns() + "" matrix""); return new SymmetricMatrix(transposedProductComponents(a)); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/Matrix.java",".java","15146","557","/* * Matrix.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; /** * Class representing matrix * * @author Didier H. Besset */ public class Matrix { protected double[][] components; protected LUPDecomposition lupDecomposition = null; /** * Creates a matrix with given components. NOTE: the components must not be * altered after the definition. * * @param a * double[][] */ public Matrix(double[][] a) { components = a; } /** * Creates a matrix with given components. NOTE: the components must not be * altered after the definition. * * @param a * double[] */ public Matrix(double[] a, int n, int m) { if (n <= 0 || m <= 0) throw new NegativeArraySizeException(""Requested matrix size: "" + n + "" by "" + m); if (n * m != a.length) { throw new IllegalArgumentException(""Requested matrix size: "" + n + "" by "" + m + "" doesn't match array size: "" + a.length); } components = new double[n][m]; int k = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { components[i][j] = a[k]; k++; } } } /** * Creates a null matrix of given dimensions. * * @param n * int number of rows * @param m * int number of columns * @throws NegativeArraySizeException */ public Matrix(int n, int m) throws NegativeArraySizeException { if (n <= 0 || m <= 0) throw new NegativeArraySizeException(""Requested matrix size: "" + n + "" by "" + m); components = new double[n][m]; clear(); } /** * @param a * MatrixAlgebra.Matrix * @throws dr.math.matrixAlgebra.IllegalDimension * if the supplied matrix does not have the same dimensions. */ public void accumulate(Matrix a) throws IllegalDimension { if (a.rows() != rows() || a.columns() != columns()) throw new IllegalDimension(""Operation error: cannot add a"" + a.rows() + "" by "" + a.columns() + "" matrix to a "" + rows() + "" by "" + columns() + "" matrix""); int m = components[0].length; for (int i = 0; i < components.length; i++) { for (int j = 0; j < m; j++) components[i][j] += a.component(i, j); } } /** * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.Matrix sum of the receiver with the supplied * matrix. * @throws dr.math.matrixAlgebra.IllegalDimension * if the supplied matrix does not have the same dimensions. */ public Matrix add(Matrix a) throws IllegalDimension { if (a.rows() != rows() || a.columns() != columns()) throw new IllegalDimension(""Operation error: cannot add a"" + a.rows() + "" by "" + a.columns() + "" matrix to a "" + rows() + "" by "" + columns() + "" matrix""); return new Matrix(addComponents(a)); } /** * Computes the components of the sum of the receiver and a supplied matrix. * * @param a * MatrixAlgebra.Matrix * @return double[][] */ protected double[][] addComponents(Matrix a) { int n = this.rows(); int m = this.columns(); double[][] newComponents = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) newComponents[i][j] = components[i][j] + a.components[i][j]; } return newComponents; } public void clear() { int m = components[0].length; for (int i = 0; i < components.length; i++) { for (int j = 0; j < m; j++) components[i][j] = 0; } } /** * @return int the number of columns of the matrix */ public int columns() { return components[0].length; } /** * @param n * int * @param m * int * @return double */ public double component(int n, int m) { return components[n][m]; } /** * @return double * @throws dr.math.matrixAlgebra.IllegalDimension * if the supplied matrix is not square. */ public double determinant() throws IllegalDimension { return lupDecomposition().determinant(); } public boolean isPD() throws IllegalDimension { return lupDecomposition().isPD(); } /** * @param a * MatrixAlgebra.Matrix * @return true if the supplied matrix is equal to the receiver. */ public boolean equals(Matrix a) { int n = this.rows(); if (a.rows() != n) return false; int m = this.columns(); if (a.columns() != m) return false; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (a.components[i][j] != components[i][j]) return false; } } return true; } /** * @return MatrixAlgebra.Matrix inverse of the receiver or pseudoinverse if * the receiver is not a square matrix. * @throws java.lang.ArithmeticException * if the receiver is a singular matrix. */ public Matrix inverse() throws ArithmeticException { try { return new Matrix(lupDecomposition().inverseMatrixComponents()); } catch (IllegalDimension e) { return new Matrix(transposedProduct().inverse() .productWithTransposedComponents(this)); } } /** * @return boolean */ public boolean isSquare() { return rows() == columns(); } /** * @return LUPDecomposition the LUP decomposition of the receiver. * @throws IllegalDimension * if the receiver is not a square matrix. */ protected LUPDecomposition lupDecomposition() throws IllegalDimension { if (lupDecomposition == null) lupDecomposition = new LUPDecomposition(this); return lupDecomposition; } /** * @param a * double multiplicand. * @return MatrixAlgebra.Matrix product of the matrix with a supplied number */ public Matrix product(double a) { return new Matrix(productComponents(a)); } /** * Computes the product of the matrix with a vector. * * @param v * matrixAlgebra.Vector * @return matrixAlgebra.Vector */ public Vector product(Vector v) throws IllegalDimension { int n = this.rows(); int m = this.columns(); if (v.dimension() != m) throw new IllegalDimension(""Product error: "" + n + "" by "" + m + "" matrix cannot by multiplied with vector of dimension "" + v.dimension()); return secureProduct(v); } /** * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.Matrix product of the receiver with the supplied * matrix * @throws dr.math.matrixAlgebra.IllegalDimension * If the number of columns of the receiver are not equal to the * number of rows of the supplied matrix. */ public Matrix product(Matrix a) throws IllegalDimension { if (a.rows() != columns()) throw new IllegalDimension(""Operation error: cannot multiply a"" + rows() + "" by "" + columns() + "" matrix with a "" + a.rows() + "" by "" + a.columns() + "" matrix""); return new Matrix(productComponents(a)); } /** * @param a * double * @return double[][] */ protected double[][] productComponents(double a) { int n = this.rows(); int m = this.columns(); double[][] newComponents = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) newComponents[i][j] = a * components[i][j]; } return newComponents; } /** * @param a * MatrixAlgebra.Matrix * @return double[][] the components of the product of the receiver with the * supplied matrix */ protected double[][] productComponents(Matrix a) { int p = this.columns(); int n = this.rows(); int m = a.columns(); double[][] newComponents = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { double sum = 0; for (int k = 0; k < p; k++) sum += components[i][k] * a.components[k][j]; newComponents[i][j] = sum; } } return newComponents; } /** * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.Matrix product of the receiver with the tranpose of * the supplied matrix * @throws dr.math.matrixAlgebra.IllegalDimension * If the number of columns of the receiver are not equal to the * number of columns of the supplied matrix. */ public Matrix productWithTransposed(Matrix a) throws IllegalDimension { if (a.columns() != columns()) throw new IllegalDimension(""Operation error: cannot multiply a "" + rows() + "" by "" + columns() + "" matrix with the transpose of a "" + a.rows() + "" by "" + a.columns() + "" matrix""); return new Matrix(productWithTransposedComponents(a)); } /** * @param a * MatrixAlgebra.Matrix * @return double[][] the components of the product of the receiver with the * transpose of the supplied matrix */ protected double[][] productWithTransposedComponents(Matrix a) { int p = this.columns(); int n = this.rows(); int m = a.rows(); double[][] newComponents = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { double sum = 0; for (int k = 0; k < p; k++) sum += components[i][k] * a.components[j][k]; newComponents[i][j] = sum; } } return newComponents; } /** * @return int the number of rows of the matrix */ public int rows() { return components.length; } /** * Computes the product of the matrix with a vector. * * @param v * matrixAlgebra.Vector * @return matrixAlgebra.Vector */ protected Vector secureProduct(Vector v) { int n = this.rows(); int m = this.columns(); double[] vectorComponents = new double[n]; for (int i = 0; i < n; i++) { vectorComponents[i] = 0; for (int j = 0; j < m; j++) vectorComponents[i] += components[i][j] * v.components[j]; } return new Vector(vectorComponents); } /** * Same as product(Matrix a), but without dimension checking. * * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.Matrix product of the receiver with the supplied * matrix */ protected Matrix secureProduct(Matrix a) { return new Matrix(productComponents(a)); } /** * Same as subtract ( Marix a), but without dimension checking. * * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.Matrix */ protected Matrix secureSubtract(Matrix a) { return new Matrix(subtractComponents(a)); } /** * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.Matrix subtract the supplied matrix to the * receiver. * @throws dr.math.matrixAlgebra.IllegalDimension * if the supplied matrix does not have the same dimensions. */ public Matrix subtract(Matrix a) throws IllegalDimension { if (a.rows() != rows() || a.columns() != columns()) throw new IllegalDimension(""Product error: cannot subtract a"" + a.rows() + "" by "" + a.columns() + "" matrix to a "" + rows() + "" by "" + columns() + "" matrix""); return new Matrix(subtractComponents(a)); } /** * @param a * MatrixAlgebra.Matrix * @return double[][] */ protected double[][] subtractComponents(Matrix a) { int n = this.rows(); int m = this.columns(); double[][] newComponents = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) newComponents[i][j] = components[i][j] - a.components[i][j]; } return newComponents; } /** * @return double[][] a copy of the components of the receiver. */ public double[][] toComponents() { int n = rows(); int m = columns(); double[][] answer = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) answer[i][j] = components[i][j]; } return answer; } /** * Returns a string representation of the system. * * @return java.lang.String */ public String toString() { StringBuffer sb = new StringBuffer(); char[] separator = { '[', ' ' }; int n = rows(); int m = columns(); for (int i = 0; i < n; i++) { separator[0] = '{'; for (int j = 0; j < m; j++) { sb.append(separator); sb.append(components[i][j]); separator[0] = ' '; } sb.append('}'); sb.append('\n'); } return sb.toString(); } public String toStringOctave() { StringBuffer sb = new StringBuffer(); int n = rows(); int m = columns(); sb.append(""[ ""); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { sb.append(components[i][j]); if (j == m - 1) { if (i == n - 1) sb.append("" ""); else sb.append(""; ""); } else sb.append("", ""); } } sb.append(""]""); return sb.toString(); } /** * @return MatrixAlgebra.Matrix transpose of the receiver */ public Matrix transpose() { int n = rows(); int m = columns(); double[][] newComponents = new double[m][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) newComponents[j][i] = components[i][j]; } return new Matrix(newComponents); } /** * @return MatrixAlgebra.SymmetricMatrix the transposed product of the * receiver with itself. */ public SymmetricMatrix transposedProduct() { return new SymmetricMatrix(transposedProductComponents(this)); } /** * @param a * MatrixAlgebra.Matrix * @return MatrixAlgebra.Matrix product of the tranpose of the receiver with * the supplied matrix * @throws dr.math.matrixAlgebra.IllegalDimension * If the number of rows of the receiver are not equal to the * number of rows of the supplied matrix. */ public Matrix transposedProduct(Matrix a) throws IllegalDimension { if (a.rows() != rows()) throw new IllegalDimension( ""Operation error: cannot multiply a tranposed "" + rows() + "" by "" + columns() + "" matrix with a "" + a.rows() + "" by "" + a.columns() + "" matrix""); return new Matrix(transposedProductComponents(a)); } /** * @param a * MatrixAlgebra.Matrix * @return double[][] the components of the product of the transpose of the * receiver with the supplied matrix. */ protected double[][] transposedProductComponents(Matrix a) { int p = this.rows(); int n = this.columns(); int m = a.columns(); double[][] newComponents = new double[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { double sum = 0; for (int k = 0; k < p; k++) sum += components[k][i] * a.components[k][j]; newComponents[i][j] = sum; } } return newComponents; } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/math/DiscreteStatistics.java",".java","9873","437","/* * DiscreteStatistics.java * * Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package math; import utils.HeapSort; /** * simple discrete statistics (mean, variance, cumulative probability, quantiles * etc.) * * @author Korbinian Strimmer * @author Alexei Drummond * @version $Id: DiscreteStatistics.java,v 1.11 2006/07/02 21:14:53 rambaut Exp * $ */ public class DiscreteStatistics { /** * compute mean * * @param x * list of numbers * @return mean */ public static double mean(double[] x) { double m = 0; int count = x.length; for (double aX : x) { if (Double.isNaN(aX)) { count--; } else { m += aX; } } return m / (double) count; } /** * compute median * * @param x * list of numbers * @param indices * index sorting x * @return median */ public static double median(double[] x, int[] indices) { int pos = x.length / 2; if (x.length % 2 == 1) { return x[indices[pos]]; } else { return (x[indices[pos - 1]] + x[indices[pos]]) / 2.0; } } /** * compute the mean squared error * * @param x * list of numbers * @param trueValue * truth * @return MSE */ public static double meanSquaredError(double[] x, double trueValue) { if (x == null || x.length == 0) { throw new IllegalArgumentException(); } double total = 0; for (double sample : x) { total += (sample - trueValue) * (sample - trueValue); } total /= x.length; return total; } /** * compute median * * @param x * list of numbers * @return median */ public static double median(double[] x) { if (x == null || x.length == 0) { throw new IllegalArgumentException(); } int[] indices = new int[x.length]; HeapSort.sort(x, indices); return median(x, indices); } /** * compute variance (ML estimator) * * @param x * list of numbers * @param mean * assumed mean of x * @return variance of x (ML estimator) */ public static double variance(double[] x, double mean) { double var = 0; int count = x.length; for (double aX : x) { if (Double.isNaN(aX)) { count--; } else { double diff = aX - mean; var += diff * diff; } } if (count < 2) { count = 1; // to avoid division by zero } else { count = count - 1; // for ML estimate } return var / (double) count; } /** * compute covariance * * @param x * list of numbers * @param y * list of numbers * @return covariance of x and y */ public static double covariance(double[] x, double[] y) { return covariance(x, y, mean(x), mean(y), stdev(x), stdev(y)); } /** * compute covariance * * @param x * list of numbers * @param y * list of numbers * @param xmean * assumed mean of x * @param ymean * assumed mean of y * @param xstdev * assumed stdev of x * @param ystdev * assumed stdev of y * @return covariance of x and y */ public static double covariance(double[] x, double[] y, double xmean, double ymean, double xstdev, double ystdev) { if (x.length != y.length) throw new IllegalArgumentException( ""x and y arrays must be same length!""); int count = x.length; double covar = 0.0; for (int i = 0; i < x.length; i++) { if (Double.isNaN(x[i]) || Double.isNaN(y[i])) { count--; } else { covar += (x[i] - xmean) * (y[i] - ymean); } } covar /= count; covar /= (xstdev * ystdev); return covar; } /** * compute fisher skewness * * @param x * list of numbers * @return skewness of x */ public static double skewness(double[] x) { double mean = mean(x); double stdev = stdev(x); double skew = 0.0; double len = x.length; for (double xv : x) { double diff = xv - mean; diff /= stdev; skew += (diff * diff * diff); } skew *= (len / ((len - 1) * (len - 2))); return skew; } /** * compute standard deviation * * @param x * list of numbers * @return standard deviation of x */ public static double stdev(double[] x) { return Math.sqrt(variance(x)); } /** * compute variance (ML estimator) * * @param x * list of numbers * @return variance of x (ML estimator) */ public static double variance(double[] x) { final double m = mean(x); return variance(x, m); } /** * compute variance of sample mean (ML estimator) * * @param x * list of numbers * @param mean * assumed mean of x * @return variance of x (ML estimator) */ public static double varianceSampleMean(double[] x, double mean) { return variance(x, mean) / (double) x.length; } /** * compute variance of sample mean (ML estimator) * * @param x * list of numbers * @return variance of x (ML estimator) */ public static double varianceSampleMean(double[] x) { return variance(x) / (double) x.length; } /** * compute the q-th quantile for a distribution of x (= inverse cdf) * * @param q * quantile (0 < q <= 1) * @param x * discrete distribution (an unordered list of numbers) * @param indices * index sorting x * @return q-th quantile */ public static double quantile(double q, double[] x, int[] indices) { if (q < 0.0 || q > 1.0) throw new IllegalArgumentException(""Quantile out of range""); if (q == 0.0) { // for q==0 we have to ""invent"" an entry smaller than the smallest x return x[indices[0]] - 1.0; } return x[indices[(int) Math.ceil(q * indices.length) - 1]]; } /** * compute the q-th quantile for a distribution of x (= inverse cdf) * * @param q * quantile (0 <= q <= 1) * @param x * discrete distribution (an unordered list of numbers) * @return q-th quantile */ public static double quantile(double q, double[] x) { int[] indices = new int[x.length]; HeapSort.sort(x, indices); return quantile(q, x, indices); } /** * compute the q-th quantile for a distribution of x (= inverse cdf) * * @param q * quantile (0 <= q <= 1) * @param x * discrete distribution (an unordered list of numbers) * @param count * use only first count entries in x * @return q-th quantile */ public static double quantile(double q, double[] x, int count) { int[] indices = new int[count]; HeapSort.sort(x, indices); return quantile(q, x, indices); } /** * Determine the highest posterior density for a list of values. The HPD is * the smallest interval containing the required amount of elements. * * @param proportion * of elements inside the interval * @param x * values * @param indices * index sorting x * @return the interval, an array of {low, high} values. */ public static double[] HPDInterval(double proportion, double[] x, int[] indices) { double minRange = Double.MAX_VALUE; int hpdIndex = 0; final int diff = (int) Math.round(proportion * (double) x.length); for (int i = 0; i <= (x.length - diff); i++) { final double minValue = x[indices[i]]; final double maxValue = x[indices[i + diff - 1]]; final double range = Math.abs(maxValue - minValue); if (range < minRange) { minRange = range; hpdIndex = i; } } return new double[] { x[indices[hpdIndex]], x[indices[hpdIndex + diff - 1]] }; } /** * compute the cumulative probability Pr(x <= z) for a given z and a * distribution of x * * @param z * threshold value * @param x * discrete distribution (an unordered list of numbers) * @param indices * index sorting x * @return cumulative probability */ public static double cdf(double z, double[] x, int[] indices) { int i; for (i = 0; i < x.length; i++) { if (x[indices[i]] > z) break; } return (double) i / (double) x.length; } /** * compute the cumulative probability Pr(x <= z) for a given z and a * distribution of x * * @param z * threshold value * @param x * discrete distribution (an unordered list of numbers) * @return cumulative probability */ public static double cdf(double z, double[] x) { int[] indices = new int[x.length]; HeapSort.sort(x, indices); return cdf(z, x, indices); } public static double max(double[] x) { double max = x[0]; for (int i = 1; i < x.length; i++) { if (x[i] > max) max = x[i]; } return max; } public static double min(double[] x) { double min = x[0]; for (int i = 1; i < x.length; i++) { if (x[i] < min) min = x[i]; } return min; } public static double geometricMean(double[] x) { double gm = 0; int len = x.length; for (int i = 0; i < len; i++) { gm += Math.log(x[i]); } return Math.exp(gm / (double) len); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/checks/DiscreteSanityCheck.java",".java","2637","106","package checks; import gui.InteractiveTableModel; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.HashSet; import java.util.Set; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.trees.RootedTree; import utils.Utils; public class DiscreteSanityCheck { private boolean notNull = false; public boolean check(String treeFilename, String stateAttName, InteractiveTableModel table) throws IOException, ImportException, ParseException { NexusImporter importer = new NexusImporter(new FileReader(treeFilename)); RootedTree tree = (RootedTree) importer.importNextTree(); String uniqueState; double nodeCount = Utils.getNodeCount(tree); double unannotatedNodeCount = 0; Set uniqueTreeStates = new HashSet(); for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { uniqueState = (String) node.getAttribute(stateAttName); uniqueTreeStates.add(uniqueState); if (uniqueState == null) { unannotatedNodeCount++; }// unannotated internal nodes check }// END: root check }// END: node loop if (unannotatedNodeCount == nodeCount) { notNull = false; throw new RuntimeException(""Attribute, "" + stateAttName + "", missing from node""); } else if (unannotatedNodeCount == 0) { notNull = true; } else if (unannotatedNodeCount < nodeCount) { notNull = true; System.out.println(""Spread detected unannotated branches "" + ""and will continue by skipping them. Consider "" + ""annotating all of the branches of your tree.""); } else { notNull = false; throw new RuntimeException(""Bad juju""); } fitLocations(table, uniqueTreeStates); return notNull; }// END: check() private void fitLocations(InteractiveTableModel table, Set uniqueTreeStates) { Object[] uniqueTreeStatesArray = uniqueTreeStates.toArray(); for (int i = 0; i < table.getRowCount(); i++) { String state = null; for (int j = 0; j < uniqueTreeStatesArray.length; j++) { String name = String.valueOf(table.getValueAt(i, 0)); if (name.toLowerCase().equals( ((String) uniqueTreeStatesArray[j]).toLowerCase())) { state = name; }// END: if location and discrete states match }// END: unique discrete states loop if (state == null) { // if none matches System.out.println(""Location "" + String.valueOf(table.getValueAt(i, 0)) + "" does not fit any of the discrete states""); } }// END: locations loop }// END: fitLocations() }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/checks/TimeSlicerSanityCheck.java",".java","3367","141","package checks; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.trees.RootedTree; import templates.TimeSlicerToKML; import utils.Utils; public class TimeSlicerSanityCheck { private boolean notNull = false; public boolean check(String treeFilename, String coordinatesName, String treesFilename, int analysisType) throws IOException, ImportException { switch (analysisType) { case TimeSlicerToKML.FIRST_ANALYSIS: if (checkMccTree(treeFilename, coordinatesName) && checkFirstPosteriorTree(treesFilename, coordinatesName)) { notNull = true; } break; case TimeSlicerToKML.SECOND_ANALYSIS: if (checkFirstPosteriorTree(treesFilename, coordinatesName)) { // TODO: sanity check for slice heights here notNull = true; } break; } return notNull; }// END: check private boolean checkMccTree(String treeFilename, String coordinatesName) throws FileNotFoundException, IOException, ImportException { RootedTree tree = (RootedTree) new NexusImporter(new FileReader( treeFilename)).importNextTree(); boolean flag = false; double nodeCount = Utils.getNodeCount(tree); double unannotatedNodeCount = 0; for (Node node : tree.getNodes()) { /////////// // Set set = tree.getAttributeNames(); // Iterator it = set.iterator(); // while (it.hasNext()) { // // Get element // Object element = it.next(); // // System.out.println(element); // // } ////////// if (!tree.isRoot(node)) { Double longitude = (Double) node .getAttribute(coordinatesName + 2); Double latitude = (Double) node .getAttribute(coordinatesName + 1); if (longitude == null || latitude == null) { unannotatedNodeCount++; }// unannotated nodes check }// END: root check }// END: node loop if (unannotatedNodeCount == nodeCount) { flag = false; throw new RuntimeException(""Attribute, "" + coordinatesName + "", missing from node""); } else if (unannotatedNodeCount == 0) { flag = true; } else if (unannotatedNodeCount < nodeCount) { notNull = true; System.out.println(""Spread detected unannotated branches "" + ""and will continue by skipping them. Consider "" + ""annotating all of the branches of your MCC tree.""); } else { notNull = false; throw new RuntimeException(""Bad juju""); } return flag; }// END: checkMccTree private boolean checkFirstPosteriorTree(String treesFilename, String coordinatesName) throws FileNotFoundException, IOException, ImportException { boolean flag = false; RootedTree currentTree = (RootedTree) new NexusImporter(new FileReader( treesFilename)).importNextTree(); for (Node node : currentTree.getNodes()) { if (!currentTree.isRoot(node)) { Object[] location = (Object[]) Utils .getObjectArrayNodeAttribute(node, coordinatesName); if (location == null) { flag = false; break; } else { flag = true; } }// END: root check }// END: node loop return flag; }// END: checkFirstPosteriorTree // TODO sanity check for sliceHeights (are they sorted? Is the max == // tree.height?) }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/checks/ContinuousSanityCheck.java",".java","4009","159","package checks; import java.io.FileReader; import java.io.IOException; import java.util.Set; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.trees.RootedTree; import utils.Utils; public class ContinuousSanityCheck { private boolean notNull = false; private String HPDString = null; public boolean check(String treeFilename, String longitudeName, String latitudeName) throws IOException, ImportException { NexusImporter importer = new NexusImporter(new FileReader(treeFilename)); RootedTree tree = (RootedTree) importer.importNextTree(); Double longitude = null; Double latitude = null; double nodeCount = Utils.getNodeCount(tree); double unannotatedNodeCount = 0; for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { longitude = (Double) node.getAttribute(longitudeName); latitude = (Double) node.getAttribute(latitudeName); if (longitude == null || latitude == null) { unannotatedNodeCount++; }// unannotated nodes check if (HPDString == null) { // we could check if(!tree.isExternal(node)) Set attSet = node.getAttributeNames(); for (String name : attSet) { if (name.contains(""HPD"") && name.contains(""modality"")) { HPDString = name.split(""_"")[1]; System.out.println(""Found highest posterior "" + ""density attribute: "" + HPDString); } } }// END: if HPDString not defined }// END: root check }// END: node loop // TODO throw HPD attribute missing exception if HPDString == null if (unannotatedNodeCount == nodeCount) { notNull = false; // throw new RuntimeException(""Attribute, "" + coordinatesName // + "", missing from node""); } else if (unannotatedNodeCount == 0) { notNull = true; } else if (unannotatedNodeCount < nodeCount) { notNull = true; System.out.println(""Spread detected unannotated branches "" + ""and will continue by skipping them. Consider "" + ""annotating all branches of your tree.""); } else { notNull = false; throw new RuntimeException(""Bad juju""); } return notNull; }// END: check public boolean check(RootedTree tree, String coordinatesName) throws IOException, ImportException { String longitudeName = (coordinatesName + 2); String latitudeName = (coordinatesName + 1); Double longitude = null; Double latitude = null; double nodeCount = Utils.getNodeCount(tree); double unannotatedNodeCount = 0; for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { longitude = (Double) node.getAttribute(longitudeName); latitude = (Double) node.getAttribute(latitudeName); if (longitude == null || latitude == null) { unannotatedNodeCount++; }// unannotated nodes check if (HPDString == null) { // we could check if(!tree.isExternal(node)) Set attSet = node.getAttributeNames(); for (String name : attSet) { if (name.contains(""HPD"") && name.contains(""modality"")) { HPDString = name.split(""_"")[1]; System.out.println(""Found highest posterior "" + ""density attribute: "" + HPDString); } } }// END: if HPDString not defined }// END: root check }// END: node loop // TODO throw HPD attribute missing exception if HPDString == null if (unannotatedNodeCount == nodeCount) { notNull = false; throw new RuntimeException(""Attribute, "" + coordinatesName + "", missing from node""); } else if (unannotatedNodeCount == 0) { notNull = true; } else if (unannotatedNodeCount < nodeCount) { notNull = true; System.out.println(""Spread detected unannotated branches "" + ""and will continue by skipping them. Consider "" + ""annotating all branches of your tree.""); } else { notNull = false; throw new RuntimeException(""Bad juju""); } return notNull; }// END: check public String getHPDString() { return HPDString; } }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/TimeSlicerTab.java",".java","36294","1233","package gui; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.ScrollPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.LinkedHashSet; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingWorker; import javax.swing.border.TitledBorder; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.trees.RootedTree; import templates.MapBackground; import templates.TimeSlicerToKML; import templates.TimeSlicerToProcessing; import utils.Utils; import app.SpreadApp; import checks.TimeSlicerSanityCheck; import colorpicker.swing.ColorPicker; @SuppressWarnings(""serial"") public class TimeSlicerTab extends JPanel { // Shared frame private SpreadApp frame; // Sizing constants private final int leftPanelWidth = 260; private final int leftPanelHeight = 1000; private final int spinningPanelHeight = 20; private final int mapImageWidth = MapBackground.MAP_IMAGE_WIDTH; private final int mapImageHeight = MapBackground.MAP_IMAGE_HEIGHT; private final Dimension minimumDimension = new Dimension(0, 0); // Colors private Color backgroundColor; private Color polygonsMaxColor; private Color branchesMaxColor; private Color polygonsMinColor; private Color branchesMinColor; // Strings for paths private String treeFilename; private String treesFilename; private String sliceHeightsFilename; private File workingDirectory; // Radio buttons private JRadioButton firstAnalysisRadioButton; private JRadioButton secondAnalysisRadioButton; // Switchers private int analysisType; // Strings for radio buttons private String firstAnalysis; private String secondAnalysis; // Text fields private JTextField burnInParser; private JTextField numberOfIntervalsParser; private JTextField kmlPathParser; private JTextField maxAltMappingParser; private JTextField HPDParser; private JTextField timescalerParser; // Spinners private DateSpinner dateSpinner; // Buttons private JButton generateKml; private JButton openTree; private JButton openTrees; private JButton generateProcessing; private JButton saveProcessingPlot; private JButton polygonsMaxColorChooser; private JButton branchesMaxColorChooser; private JButton polygonsMinColorChooser; private JButton branchesMinColorChooser; private JButton loadTimeSlices; // Sliders private JSlider branchesWidthParser; private JSlider gridSizeParser; // Combo boxes private JComboBox eraParser; private JComboBox coordinatesNameParser; private JComboBox rateAttNameParser; private JComboBox precisionAttNameParser; // checkboxes private JCheckBox trueNoiseParser; // left tools pane private JPanel leftPanel; private JPanel tmpPanel; private SpinningPanel sp; private JPanel tmpPanelsHolder; // Processing pane private TimeSlicerToProcessing timeSlicerToProcessing; // Progress bar private JProgressBar progressBar; public TimeSlicerTab(SpreadApp spreadApp) { this.frame = spreadApp; // Setup miscallenous setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); GridBagConstraints c = new GridBagConstraints(); // Setup colors backgroundColor = new Color(231, 237, 246); polygonsMaxColor = new Color(50, 255, 255, 255); branchesMaxColor = new Color(255, 5, 50, 255); polygonsMinColor = new Color(0, 0, 0, 100); branchesMinColor = new Color(0, 0, 0, 255); // Setup strings for paths treeFilename = null; treesFilename = null; sliceHeightsFilename = null; workingDirectory = null; // Setup strings for radio buttons firstAnalysis = new String(""MCC tree slice heights""); secondAnalysis = new String(""Custom slice heights""); // Setup radio buttons firstAnalysisRadioButton = new JRadioButton(firstAnalysis); secondAnalysisRadioButton = new JRadioButton(secondAnalysis); // Setup switchers analysisType = TimeSlicerToKML.FIRST_ANALYSIS; // Setup text fields burnInParser = new JTextField(""500"", 10); coordinatesNameParser = new JComboBox(new String[] {""location""}); rateAttNameParser = new JComboBox(new String[] {""rate""}); precisionAttNameParser = new JComboBox(new String[] {""precision""}); numberOfIntervalsParser = new JTextField(""10"", 5); maxAltMappingParser = new JTextField(""500000"", 5); kmlPathParser = new JTextField(""output.kml"", 10); HPDParser = new JTextField(""0.8"", 5); timescalerParser = new JTextField(""1.0"", 10); // Setup buttons generateKml = new JButton(""Generate"", SpreadApp.nuclearIcon); openTree = new JButton(""Open"", SpreadApp.treeIcon); openTrees = new JButton(""Open"", SpreadApp.treesIcon); generateProcessing = new JButton(""Plot"", SpreadApp.processingIcon); saveProcessingPlot = new JButton(""Save"", SpreadApp.saveIcon); polygonsMaxColorChooser = new JButton(""Setup max""); branchesMaxColorChooser = new JButton(""Setup max""); polygonsMinColorChooser = new JButton(""Setup min""); branchesMinColorChooser = new JButton(""Setup min""); loadTimeSlices = new JButton(""Load"", SpreadApp.timeSlicesIcon); // Setup sliders branchesWidthParser = new JSlider(JSlider.HORIZONTAL, 2, 10, 4); branchesWidthParser.setMajorTickSpacing(2); branchesWidthParser.setMinorTickSpacing(1); branchesWidthParser.setPaintTicks(true); branchesWidthParser.setPaintLabels(true); gridSizeParser = new JSlider(JSlider.HORIZONTAL, 100, 200, 100); gridSizeParser.setMajorTickSpacing(50); gridSizeParser.setMinorTickSpacing(10); gridSizeParser.setPaintTicks(true); gridSizeParser.setPaintLabels(true); // Setup progress bar & checkboxes progressBar = new JProgressBar(); trueNoiseParser = new JCheckBox(); // Left tools pane leftPanel = new JPanel(); leftPanel.setBackground(backgroundColor); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS)); // Action listeners openTree.addActionListener(new ListenOpenTree()); openTrees.addActionListener(new ListenOpenTrees()); generateKml.addActionListener(new ListenGenerateKml()); generateProcessing.addActionListener(new ListenGenerateProcessing()); saveProcessingPlot.addActionListener(new ListenSaveProcessingPlot()); polygonsMaxColorChooser .addActionListener(new ListenPolygonsMaxColorChooser()); branchesMaxColorChooser .addActionListener(new ListenBranchesMaxColorChooser()); polygonsMinColorChooser .addActionListener(new ListenPolygonsMinColorChooser()); branchesMinColorChooser .addActionListener(new ListenBranchesMinColorChooser()); loadTimeSlices.addActionListener(new ListenLoadTimeSlices()); // //////////////////////////// // ---CHOOSE ANALYSIS TYPE---// // //////////////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setLayout(new GridLayout(2, 1)); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Choose analysis type:"")); ButtonGroup buttonGroup = new ButtonGroup(); firstAnalysisRadioButton.setToolTipText(firstAnalysis); firstAnalysisRadioButton.setActionCommand(firstAnalysis); firstAnalysisRadioButton .addActionListener(new ChooseAnalysisTypeListener()); firstAnalysisRadioButton.setSelected(true); buttonGroup.add(firstAnalysisRadioButton); tmpPanel.add(firstAnalysisRadioButton); secondAnalysisRadioButton.setToolTipText(secondAnalysis); secondAnalysisRadioButton.setActionCommand(secondAnalysis); secondAnalysisRadioButton .addActionListener(new ChooseAnalysisTypeListener()); buttonGroup.add(secondAnalysisRadioButton); tmpPanel.add(secondAnalysisRadioButton); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Analysis"", new Dimension( leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // ///////////// // ---INPUT---// // ///////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Load slice heights / tree file:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; loadTimeSlices.setEnabled(false); tmpPanel.add(loadTimeSlices, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(openTree, c); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Load trees file:"")); tmpPanel.add(openTrees); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Most recent sampling date:"")); dateSpinner = new DateSpinner(); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(dateSpinner, c); String era[] = { ""AD"", ""BC"" }; eraParser = new JComboBox(era); c.gridx = 2; c.gridy = 0; tmpPanel.add(eraParser, c); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Coordinate attribute name:"")); tmpPanel.add(coordinatesNameParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Rate attribute name:"")); tmpPanel.add(rateAttNameParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Precision attribute name:"")); tmpPanel.add(precisionAttNameParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Input"", new Dimension( leftPanelWidth, spinningPanelHeight)); sp.showBottom(true); leftPanel.add(sp); // //////////////////////// // ---BRANCHES MAPPING---// // //////////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); // Branches color mapping: tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBorder(new TitledBorder(""Branches color mapping:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(branchesMinColorChooser, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(branchesMaxColorChooser, c); tmpPanelsHolder.add(tmpPanel); // Branches width: tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Branches width:"")); tmpPanel.add(branchesWidthParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Maximal altitude mapping:"")); tmpPanel.add(maxAltMappingParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Branches mapping"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////////// // ---POLYGONS MAPPING---// // //////////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); // Polygons color mapping: tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Polygons color mapping:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(polygonsMinColorChooser, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(polygonsMaxColorChooser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Polygons mapping"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////// // ---COMPUTATIONS---// // //////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Use true noise:"")); trueNoiseParser.setSelected(true); tmpPanel.add(trueNoiseParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Specify burn-in:"")); tmpPanel.add(burnInParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""HPD:"")); tmpPanel.add(HPDParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Time scale multiplier:"")); tmpPanel.add(timescalerParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Number of intervals:"")); tmpPanel.add(numberOfIntervalsParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Grid size:"")); tmpPanel.add(gridSizeParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Computations"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // ////////////// // ---OUTPUT---// // ////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""KML name:"")); tmpPanel.add(kmlPathParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Generate KML / Plot map:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(generateKml, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(generateProcessing, c); c.ipady = 7; c.gridwidth = 3; c.gridx = 0; c.gridy = 1; tmpPanel.add(progressBar, c); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Save plot:"")); tmpPanel.add(saveProcessingPlot); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Output"", new Dimension( leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////////// // ---LEFT SCROLL PANE---// // //////////////////////// JScrollPane leftScrollPane = new JScrollPane(leftPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); leftScrollPane.setMinimumSize(minimumDimension); leftScrollPane.setMaximumSize(new Dimension(leftPanelWidth, leftPanelHeight)); /** * Processing pane * */ timeSlicerToProcessing = new TimeSlicerToProcessing(); timeSlicerToProcessing.setPreferredSize(new Dimension(mapImageWidth, mapImageHeight)); // if (System.getProperty(""java.runtime.name"").toLowerCase().startsWith( // ""openjdk"")) { // // JScrollPane rightScrollPane = new JScrollPane( // timeSlicerToProcessing, // JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, // JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); // rightScrollPane.setMinimumSize(minimumDimension); // // SplitPane splitPane = new SplitPane(JSplitPane.HORIZONTAL_SPLIT, // leftScrollPane, rightScrollPane); // splitPane.setDividerLocation(leftPanelWidth); // // this.add(splitPane); // // } else { ScrollPane rightScrollPane = new ScrollPane( ScrollPane.SCROLLBARS_ALWAYS); rightScrollPane.add(timeSlicerToProcessing); rightScrollPane.setMinimumSize(minimumDimension); SplitPane splitPane = new SplitPane(JSplitPane.HORIZONTAL_SPLIT, leftScrollPane, rightScrollPane); splitPane.setDividerLocation(leftPanelWidth); this.add(splitPane); // } }// END: Constructor class ChooseAnalysisTypeListener implements ActionListener { public void actionPerformed(ActionEvent ev) { if (ev.getActionCommand() == firstAnalysis) { loadTimeSlices.setEnabled(false); openTree.setEnabled(true); branchesMinColorChooser.setEnabled(true); branchesMaxColorChooser.setEnabled(true); branchesWidthParser.setEnabled(true); maxAltMappingParser.setEnabled(true); numberOfIntervalsParser.setEnabled(true); analysisType = TimeSlicerToKML.FIRST_ANALYSIS; frame.setStatus(firstAnalysis + "" analysis selected""); } else if (ev.getActionCommand() == secondAnalysis) { loadTimeSlices.setEnabled(true); openTree.setEnabled(false); branchesMinColorChooser.setEnabled(false); branchesMaxColorChooser.setEnabled(false); branchesWidthParser.setEnabled(false); maxAltMappingParser.setEnabled(false); numberOfIntervalsParser.setEnabled(false); analysisType = TimeSlicerToKML.SECOND_ANALYSIS; frame.setStatus(secondAnalysis + "" analysis selected""); } else { throw new RuntimeException(""Unimplemented analysis type selected!""); } }// END: actionPerformed }// END: ChooseAnalysisTypeListener private class ListenLoadTimeSlices implements ActionListener { public void actionPerformed(ActionEvent ev) { try { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Loading slice heights file...""); chooser.setCurrentDirectory(workingDirectory); int returnVal = chooser.showOpenDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); sliceHeightsFilename = file.getAbsolutePath(); frame.setStatus(""Opened "" + sliceHeightsFilename); File tmpDir = chooser.getCurrentDirectory(); if (tmpDir != null) { workingDirectory = tmpDir; } } else { System.out.println(""Could not Open!""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block } }// END: ListenLoadTimeSlices private class ListenOpenTree implements ActionListener { public void actionPerformed(ActionEvent ev) { try { String[] treeFiles = new String[] { ""tre"", ""tree"", ""trees"" }; JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Opening tree file...""); chooser.setMultiSelectionEnabled(false); chooser.addChoosableFileFilter(new SimpleFileFilter(treeFiles, ""Tree files (*.tree(s), *.tre)"")); chooser.setCurrentDirectory(workingDirectory); int returnVal = chooser.showOpenDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); treeFilename = file.getAbsolutePath(); frame.setStatus(""Opened "" + treeFilename + ""\n""); File tmpDir = chooser.getCurrentDirectory(); if (tmpDir != null) { workingDirectory = tmpDir; } } else { System.out.println(""Could not Open! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenOpenTree //TODO: move all the tree parsing to separate tree parser class with getters for all the attributes we need private void populateAttributeComboboxes() { try { NexusImporter importer = new NexusImporter(new FileReader(treesFilename)); RootedTree tree = (RootedTree) importer.importNextTree(); LinkedHashSet uniqueAttributes = new LinkedHashSet(); for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { uniqueAttributes.addAll(node.getAttributeNames()); } } // re-initialise comboboxes ComboBoxModel coordinatesNameParserModel = new DefaultComboBoxModel(uniqueAttributes.toArray(new String[0])); coordinatesNameParser.setModel(coordinatesNameParserModel); ComboBoxModel rateAttNameParserModel = new DefaultComboBoxModel(uniqueAttributes.toArray(new String[0])); rateAttNameParser.setModel(rateAttNameParserModel); ComboBoxModel precisionAttNameParserModel = new DefaultComboBoxModel(tree.getAttributeNames().toArray(new String[0])); precisionAttNameParser.setModel(precisionAttNameParserModel); } catch (FileNotFoundException e) { Utils.handleException(e, e.getMessage()); } catch (IOException e) { Utils.handleException(e, e.getMessage()); } catch (ImportException e) { Utils.handleException(e, e.getMessage()); } }//END: populateAttributeCombobox private class ListenOpenTrees implements ActionListener { public void actionPerformed(ActionEvent ev) { try { String[] treesFiles = new String[] { ""trees"" }; JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Loading trees file...""); chooser.setMultiSelectionEnabled(false); chooser.addChoosableFileFilter(new SimpleFileFilter(treesFiles, ""Tree files (*.trees)"")); chooser.setCurrentDirectory(workingDirectory); int returnVal = chooser.showOpenDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); treesFilename = file.getAbsolutePath(); frame.setStatus(""Opened "" + treesFilename + ""\n""); File tmpDir = chooser.getCurrentDirectory(); if (tmpDir != null) { workingDirectory = tmpDir; } populateAttributeComboboxes(); } else { frame.setStatus(""Could not Open! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenOpenTrees private class ListenPolygonsMinColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose minimum polygons color..."", polygonsMinColor, true); if (c != null) polygonsMinColor = c; } } private class ListenPolygonsMaxColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose maximum polygons color..."", polygonsMaxColor, true); if (c != null) polygonsMaxColor = c; } } private class ListenBranchesMinColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose minimum branches color..."", branchesMinColor, true); if (c != null) branchesMinColor = c; } } private class ListenBranchesMaxColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose maximum branches color..."", branchesMaxColor, true); if (c != null) branchesMaxColor = c; } } private class ListenGenerateKml implements ActionListener { public void actionPerformed(ActionEvent ev) { if (openTree.isEnabled() && treeFilename == null) { new ListenOpenTree().actionPerformed(ev); } else if (treesFilename == null) { new ListenOpenTrees().actionPerformed(ev); } else { generateKml.setEnabled(false); progressBar.setIndeterminate(true); SwingWorker worker = new SwingWorker() { // Executed in background thread public Void doInBackground() { try { if (new TimeSlicerSanityCheck().check(treeFilename, coordinatesNameParser.getSelectedItem().toString(), treesFilename, analysisType)) { TimeSlicerToKML timeSlicerToKML = new TimeSlicerToKML(); timeSlicerToKML.setAnalysisType(analysisType); if (analysisType == TimeSlicerToKML.FIRST_ANALYSIS) { timeSlicerToKML.setTreePath(treeFilename); timeSlicerToKML .setNumberOfIntervals(Integer .valueOf(numberOfIntervalsParser .getText())); timeSlicerToKML .setMinBranchRedMapping(branchesMinColor .getRed()); timeSlicerToKML .setMinBranchGreenMapping(branchesMinColor .getGreen()); timeSlicerToKML .setMinBranchBlueMapping(branchesMinColor .getBlue()); timeSlicerToKML .setMinBranchOpacityMapping(branchesMinColor .getAlpha()); timeSlicerToKML .setMaxBranchRedMapping(branchesMaxColor .getRed()); timeSlicerToKML .setMaxBranchGreenMapping(branchesMaxColor .getGreen()); timeSlicerToKML .setMaxBranchBlueMapping(branchesMaxColor .getBlue()); timeSlicerToKML .setMaxBranchOpacityMapping(branchesMaxColor .getAlpha()); timeSlicerToKML .setBranchWidth(branchesWidthParser .getValue()); timeSlicerToKML .setMaxAltitudeMapping(Double .valueOf(maxAltMappingParser .getText())); } else if (analysisType == TimeSlicerToKML.SECOND_ANALYSIS) { timeSlicerToKML .setCustomSliceHeightsPath(sliceHeightsFilename); } else { throw new RuntimeException( ""Unknown analysis type selected""); } timeSlicerToKML.setTreesPath(treesFilename); timeSlicerToKML.setHPD(Double.valueOf(HPDParser .getText())); timeSlicerToKML.setGridSize(gridSizeParser .getValue()); timeSlicerToKML.setBurnIn(Integer .valueOf(burnInParser.getText())); timeSlicerToKML .setLocationAttributeName(coordinatesNameParser .getSelectedItem().toString()); timeSlicerToKML .setRateAttributeName(rateAttNameParser .getSelectedItem().toString()); timeSlicerToKML .setPrecisionAttName(precisionAttNameParser .getSelectedItem().toString()); timeSlicerToKML.setUseTrueNoise(trueNoiseParser .isSelected()); timeSlicerToKML .setMrsdString(dateSpinner.getValue() + "" "" + (eraParser.getSelectedIndex() == 0 ? ""AD"" : ""BC"")); timeSlicerToKML.setTimescaler(Double .valueOf(timescalerParser.getText())); timeSlicerToKML .setKmlWriterPath(workingDirectory .toString() .concat(""/"") .concat(kmlPathParser.getText())); timeSlicerToKML .setMinPolygonRedMapping(polygonsMinColor .getRed()); timeSlicerToKML .setMinPolygonGreenMapping(polygonsMinColor .getGreen()); timeSlicerToKML .setMinPolygonBlueMapping(polygonsMinColor .getBlue()); timeSlicerToKML .setMinPolygonOpacityMapping(polygonsMinColor .getAlpha()); timeSlicerToKML .setMaxPolygonRedMapping(polygonsMaxColor .getRed()); timeSlicerToKML .setMaxPolygonGreenMapping(polygonsMaxColor .getGreen()); timeSlicerToKML .setMaxPolygonBlueMapping(polygonsMaxColor .getBlue()); timeSlicerToKML .setMaxPolygonOpacityMapping(polygonsMaxColor .getAlpha()); timeSlicerToKML.GenerateKML(); System.out.println(""Finished in: "" + timeSlicerToKML.time + "" msec \n""); }// END: check } catch (final OutOfMemoryError e) { Utils.handleException(e, ""Increase Java Heap Space""); } catch (final Exception e) { Utils.handleException(e, e.getMessage()); } return null; }// END: doInBackground() // Executed in event dispatch thread public void done() { generateKml.setEnabled(true); progressBar.setIndeterminate(false); frame.setStatus(""Generated "" + workingDirectory.toString().concat(""/"") .concat(kmlPathParser.getText())); System.gc(); } }; worker.execute(); }// END: if not loaded }// END: actionPerformed }// END: ListenGenerateKml private class ListenGenerateProcessing implements ActionListener { public void actionPerformed(ActionEvent ev) { if (openTree.isEnabled() && treeFilename == null) { new ListenOpenTree().actionPerformed(ev); } else if (treesFilename == null) { new ListenOpenTrees().actionPerformed(ev); } else { generateProcessing.setEnabled(false); progressBar.setIndeterminate(true); SwingWorker worker = new SwingWorker() { // Executed in background thread public Void doInBackground() { try { if (new TimeSlicerSanityCheck().check(treeFilename, coordinatesNameParser.getSelectedItem().toString(), treesFilename, analysisType)) { timeSlicerToProcessing .setAnalysisType(analysisType); if (analysisType == TimeSlicerToProcessing.FIRST_ANALYSIS) { timeSlicerToProcessing .setTreePath(treeFilename); timeSlicerToProcessing .setNumberOfIntervals(Integer .valueOf(numberOfIntervalsParser .getText())); timeSlicerToProcessing .setMinBranchRedMapping(branchesMinColor .getRed()); timeSlicerToProcessing .setMinBranchGreenMapping(branchesMinColor .getGreen()); timeSlicerToProcessing .setMinBranchBlueMapping(branchesMinColor .getBlue()); timeSlicerToProcessing .setMinBranchOpacityMapping(branchesMinColor .getAlpha()); timeSlicerToProcessing .setMaxBranchRedMapping(branchesMaxColor .getRed()); timeSlicerToProcessing .setMaxBranchGreenMapping(branchesMaxColor .getGreen()); timeSlicerToProcessing .setMaxBranchBlueMapping(branchesMaxColor .getBlue()); timeSlicerToProcessing .setMaxBranchOpacityMapping(branchesMaxColor .getAlpha()); timeSlicerToProcessing .setBranchWidth(branchesWidthParser .getValue() / 2); } else if (analysisType == TimeSlicerToProcessing.SECOND_ANALYSIS) { timeSlicerToProcessing .setCustomSliceHeightsPath(sliceHeightsFilename); } else { throw new RuntimeException( ""Unknown analysis type selected""); } timeSlicerToProcessing .setTreesPath(treesFilename); timeSlicerToProcessing.setHPD(Double .valueOf(HPDParser.getText())); timeSlicerToProcessing .setGridSize(gridSizeParser.getValue()); timeSlicerToProcessing.setBurnIn(Integer .valueOf(burnInParser.getText())); timeSlicerToProcessing .setCoordinatesName(coordinatesNameParser .getSelectedItem().toString()); timeSlicerToProcessing .setRateAttributeName(rateAttNameParser .getSelectedItem().toString()); timeSlicerToProcessing .setPrecisionAttributeName(precisionAttNameParser .getSelectedItem().toString()); timeSlicerToProcessing .setUseTrueNoise(trueNoiseParser .isSelected()); timeSlicerToProcessing .setMrsdString(dateSpinner.getValue() + "" "" + (eraParser.getSelectedIndex() == 0 ? ""AD"" : ""BC"")); timeSlicerToProcessing.setTimescaler(Double .valueOf(timescalerParser.getText())); timeSlicerToProcessing .setMinPolygonRedMapping(polygonsMinColor .getRed()); timeSlicerToProcessing .setMinPolygonGreenMapping(polygonsMinColor .getGreen()); timeSlicerToProcessing .setMinPolygonBlueMapping(polygonsMinColor .getBlue()); timeSlicerToProcessing .setMinPolygonOpacityMapping(polygonsMinColor .getAlpha()); timeSlicerToProcessing .setMaxPolygonRedMapping(polygonsMaxColor .getRed()); timeSlicerToProcessing .setMaxPolygonGreenMapping(polygonsMaxColor .getGreen()); timeSlicerToProcessing .setMaxPolygonBlueMapping(polygonsMaxColor .getBlue()); timeSlicerToProcessing .setMaxPolygonOpacityMapping(polygonsMaxColor .getAlpha()); timeSlicerToProcessing.analyzeTrees(); timeSlicerToProcessing.init(); // System.out.println(""Finished. \n""); }// END: check } catch (final OutOfMemoryError e) { Utils.handleException(e, ""Increase Java Heap Space""); } catch (final Exception e) { Utils.handleException(e, null); } return null; }// END: doInBackground() // Executed in event dispatch thread public void done() { generateProcessing.setEnabled(true); progressBar.setIndeterminate(false); // frame.setStatus(""Finished. \n""); System.gc(); }// END: done }; worker.execute(); }// END: if not loaded }// END: actionPerformed }// END: ListenGenerateProcessing private class ListenSaveProcessingPlot implements ActionListener { public void actionPerformed(ActionEvent ev) { try { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Saving as png file...""); int returnVal = chooser.showSaveDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String filename = file.getAbsolutePath(); timeSlicerToProcessing.save(filename); frame.setStatus(""Saved "" + filename + ""\n""); } else { frame.setStatus(""Could not Save! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenSaveProcessingPlot }// END class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/SplitPane.java",".java","2041","91","package gui; import java.awt.*; import javax.swing.*; @SuppressWarnings(""serial"") class SplitPane extends JSplitPane { SplitPane() { super(); } SplitPane(int newOrientation) { super(newOrientation); } SplitPane(int newOrientation, boolean newContinuousLayout) { super(newOrientation, newContinuousLayout); } SplitPane(int newOrientation, boolean newContinuousLayout, Component newLeftComponent, Component newRightComponent) { super(newOrientation, newContinuousLayout, newLeftComponent, newRightComponent); } SplitPane(int newOrientation, Component newLeftComponent, Component newRightComponent) { super(newOrientation, newLeftComponent, newRightComponent); } /** * Override this method to prevent setting a location that violates the * maximum size of either component in the splitter, if setMaximumSize() has * been called. */ public void setDividerLocation(int requested) { int currentLoc = getDividerLocation(); if (currentLoc == requested) { super.setDividerLocation(requested); return; } boolean growing = requested > currentLoc; Component maxComp = growing ? getLeftComponent() : getRightComponent(); if (maxComp == null) { super.setDividerLocation(requested); return; } Dimension maxDim = maxComp.getMaximumSize(); if (maxDim == null) { super.setDividerLocation(requested); return; } int maxCompSize = getSizeForPrimaryAxis(maxDim); if (growing) { if (requested > maxCompSize) { super.setDividerLocation(maxCompSize); return; } } else { int totalSize = getSizeForPrimaryAxis(getSize()); int minPos = totalSize - maxCompSize - getDividerSize(); if (requested < minPos) { super.setDividerLocation(minPos); return; } } super.setDividerLocation(requested); } /** * If the orientation is Horizontal, the width is returned, otherwise the * height. */ private int getSizeForPrimaryAxis(Dimension size) { return (getOrientation() == HORIZONTAL_SPLIT) ? size.width : size.height; } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/DateSpinner.java",".java","792","39","package gui; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.SpinnerDateModel; @SuppressWarnings(""serial"") public class DateSpinner extends JPanel { private Date today; private JSpinner spinner; private SimpleDateFormat formatter; public DateSpinner() { formatter = new SimpleDateFormat(""yyyy-MM-dd"", Locale.US); today = new Date(); spinner = new JSpinner(new SpinnerDateModel(today, null, null, Calendar.MONTH)); spinner.setEditor(new JSpinner.DateEditor(spinner, ""yyyy-MM-dd"")); spinner.setOpaque(false); add(spinner); setOpaque(false); } public String getValue() { return formatter.format(spinner.getValue()); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/TerminalTab.java",".java","1607","65","package gui; import java.awt.BorderLayout; import java.awt.ScrollPane; import java.io.PrintStream; import javax.swing.BoxLayout; import javax.swing.JPanel; import javax.swing.JTextArea; @SuppressWarnings(""serial"") public class TerminalTab extends JPanel { private JTextArea textArea; public TerminalTab() { // Setup miscallenous setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); // Setup text area textArea = new JTextArea(); textArea.setEditable(true); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); // if (System.getProperty(""java.runtime.name"").toLowerCase() // .startsWith(""openjdk"")) { // // JScrollPane scrollPane = new JScrollPane(textArea, // ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, // ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); // add(scrollPane, BorderLayout.CENTER); // // } else { ScrollPane scrollPane = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS); scrollPane.add(textArea); add(scrollPane, BorderLayout.CENTER); // } // Redirect streams System.setOut(new PrintStream(new JTextAreaOutputStream(textArea))); //for dev it's easier to catch them in console // System.setErr(new PrintStream(new JTextAreaOutputStream(textArea))); // //TODO: check how to append and use JEditorPane for text, hyperlinks handling etc // JEditorPane textAreaTest = new JEditorPane(); // textAreaTest.setContentType(""text/html""); // textAreaTest.setText(""kutas""); } public void setText(String text) { textArea.append(text); } public void clearTerminal() { textArea.setText(""""); } }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/JTextAreaOutputStream.java",".java","519","29","package gui; import java.io.OutputStream; import javax.swing.JTextArea; public class JTextAreaOutputStream extends OutputStream { JTextArea textArea; public JTextAreaOutputStream(JTextArea t) { super(); textArea = t; } public void write(int i) { char[] chars = new char[1]; chars[0] = (char) i; String s = new String(chars); textArea.append(s); } public void write(char[] buf, int off, int len) { String s = new String(buf, off, len); textArea.append(s); } }// END: JTextAreaOutputStream ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/GradientPanel.java",".java","1273","57","package gui; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JPanel; @SuppressWarnings(""serial"") public class GradientPanel extends JPanel { public final static int HORIZONTAL = 0; public final static int VERTICAL = 1; private Color startColor; private Color endColor; private int direction; public GradientPanel(Color startColor, Color endColor, int direction) { super(); this.startColor = startColor; this.endColor = endColor; this.direction = direction; } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); int panelHeight = this.getHeight(); int panelWidth = this.getWidth(); GradientPaint gradientPaint = null; switch (direction) { case HORIZONTAL: gradientPaint = new GradientPaint(0, panelHeight / 2, startColor, panelWidth, panelHeight / 2, endColor); break; case VERTICAL: gradientPaint = new GradientPaint(panelWidth / 2, 0, endColor, panelWidth / 2, panelHeight, startColor); break; } if (g instanceof Graphics2D) { Graphics2D graphics2D = (Graphics2D) g; graphics2D.setPaint(gradientPaint); graphics2D.fillRect(0, 0, panelWidth, panelHeight); } }// END: paintComponent } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/SpinningPanel.java",".java","4124","182","package gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Polygon; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; @SuppressWarnings(""serial"") public class SpinningPanel extends JPanel { private Dimension dimension; private Component bottomComponent; private String label; private SpinWidget spinWidget; private Color gradientPanelStartColor; private Color gradientPanelEndColor; private Color gradientPanelBorderColor; private Color SpinWidgetColor; public SpinningPanel(Component bottomComponent, String label, Dimension dimension) { this.bottomComponent = bottomComponent; this.label = label; this.dimension = dimension; gradientPanelStartColor = new Color(182, 192, 207); gradientPanelEndColor = new Color(202, 209, 220); gradientPanelBorderColor = new Color(154, 164, 183); SpinWidgetColor = new Color(100, 104, 111); doMyLayout(); } protected void doMyLayout() { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); GradientPanel labelPanel = new GradientPanel(gradientPanelStartColor, gradientPanelEndColor, GradientPanel.VERTICAL); labelPanel.setMaximumSize(dimension); labelPanel.setLayout(new BorderLayout()); spinWidget = new SpinWidget(); spinWidget.setName(label.trim() + "".spinWidget""); labelPanel.add(spinWidget, BorderLayout.LINE_START); JLabel jlabel = new JLabel(label); labelPanel.add(jlabel, BorderLayout.CENTER); labelPanel.setBorder(BorderFactory .createLineBorder(gradientPanelBorderColor)); add(labelPanel); add(bottomComponent); resetBottomVisibility(); }// END: doMyLayout private void resetBottomVisibility() { if ((bottomComponent == null) || (spinWidget == null)) return; bottomComponent.setVisible(spinWidget.isOpen()); revalidate(); } public void showBottom(boolean b) { spinWidget.setOpen(b); } public boolean isBottomShowing() { return spinWidget.isOpen(); } public class SpinWidget extends JPanel { private final int SPIN_WIDGET_HEIGHT = 15; private final int HALF_HEIGHT = SPIN_WIDGET_HEIGHT / 2; private Dimension mySize = new Dimension(SPIN_WIDGET_HEIGHT, SPIN_WIDGET_HEIGHT); private boolean open; private boolean mouseOver; private int[] openXPoints = { 1, HALF_HEIGHT, SPIN_WIDGET_HEIGHT - 1 }; private int[] openYPoints = { HALF_HEIGHT, SPIN_WIDGET_HEIGHT - 1, HALF_HEIGHT }; private int[] closedXPoints = { 1, 1, HALF_HEIGHT }; private int[] closedYPoints = { 1, SPIN_WIDGET_HEIGHT - 1, HALF_HEIGHT }; private Polygon openTriangle = new Polygon(openXPoints, openYPoints, 3); private Polygon closedTriangle = new Polygon(closedXPoints, closedYPoints, 3); public SpinWidget() { setOpen(false); addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { handleClick(); } public void mouseEntered(MouseEvent e) { handleMouseOver(); } public void mouseExited(MouseEvent e) { handleMouseOver(); } }); } public void handleClick() { setOpen(!isOpen()); } public boolean isOpen() { return open; } public void setOpen(boolean o) { open = o; resetBottomVisibility(); } public void handleMouseOver() { setIsMouseOver(!isMouseOver()); } public boolean isMouseOver() { return mouseOver; } public void setIsMouseOver(boolean o) { mouseOver = o; repaint(); } public Dimension getMinimumSize() { return mySize; } public Dimension getPreferredSize() { return mySize; } public void paint(Graphics g) { if (!isMouseOver()) { g.setColor(SpinWidgetColor); } else { g.setColor(SpinWidgetColor.darker()); } if (isOpen()) { // TODO: animate opening here g.fillPolygon(openTriangle); } else { // TODO: animate closing here g.fillPolygon(closedTriangle); } }// END: paint }// END: SpinWidget class }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/ContinuousModelTab.java",".java","26132","867","package gui; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.ScrollPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.LinkedHashSet; import javax.swing.BoxLayout; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingWorker; import javax.swing.border.TitledBorder; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.trees.RootedTree; import templates.ContinuousTreeToKML; import templates.ContinuousTreeToProcessing; import templates.MapBackground; import utils.Utils; import app.SpreadApp; import checks.ContinuousSanityCheck; import colorpicker.swing.ColorPicker; @SuppressWarnings(""serial"") public class ContinuousModelTab extends JPanel { // Shared Frame private SpreadApp frame; // Sizing constants private final int leftPanelWidth = 260; private final int leftPanelHeight = 1000; private final int spinningPanelHeight = 20; private final int mapImageWidth = MapBackground.MAP_IMAGE_WIDTH; private final int mapImageHeight = MapBackground.MAP_IMAGE_HEIGHT; private final Dimension minimumDimension = new Dimension(0, 0); // Colors private Color backgroundColor; private Color polygonsMaxColor; private Color branchesMaxColor; private Color polygonsMinColor; private Color branchesMinColor; // Strings for paths private String treeFilename = null; private File workingDirectory = null; // Text fields private JTextField numberOfIntervalsParser; private JTextField maxAltMappingParser; private JTextField kmlPathParser; private JTextField timescalerParser; // Spinners private DateSpinner dateSpinner; // Buttons private JButton generateKml; private JButton openTree; private JButton generateProcessing; private JButton saveProcessingPlot; private JButton polygonsMaxColorChooser; private JButton branchesMaxColorChooser; private JButton polygonsMinColorChooser; private JButton branchesMinColorChooser; // Sliders private JSlider branchesWidthParser; // Combo boxes private JComboBox eraParser; private JComboBox latitudeAttributeNameParser; private JComboBox longitudeAttributeNameParser; // Left tools pane private JPanel leftPanel; private JPanel tmpPanel; private SpinningPanel sp; private JPanel tmpPanelsHolder; // Processing pane private ContinuousTreeToProcessing continuousTreeToProcessing; // Progress bar private JProgressBar progressBar; public ContinuousModelTab(SpreadApp spreadApp) { this.frame = spreadApp; // Setup miscallenous setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); backgroundColor = new Color(231, 237, 246); polygonsMaxColor = new Color(50, 255, 255, 255); branchesMaxColor = new Color(255, 5, 50, 255); polygonsMinColor = new Color(0, 0, 0, 100); branchesMinColor = new Color(0, 0, 0, 255); GridBagConstraints c = new GridBagConstraints(); // Setup text fields numberOfIntervalsParser = new JTextField(""100"", 10); maxAltMappingParser = new JTextField(""5000000"", 10); kmlPathParser = new JTextField(""output.kml"", 10); timescalerParser = new JTextField(""1.0"", 10); // Setup buttons generateKml = new JButton(""Generate"", SpreadApp.nuclearIcon); openTree = new JButton(""Open"", SpreadApp.treeIcon); generateProcessing = new JButton(""Plot"", SpreadApp.processingIcon); saveProcessingPlot = new JButton(""Save"", SpreadApp.saveIcon); polygonsMaxColorChooser = new JButton(""Setup max""); branchesMaxColorChooser = new JButton(""Setup max""); polygonsMinColorChooser = new JButton(""Setup min""); branchesMinColorChooser = new JButton(""Setup min""); // Setup sliders branchesWidthParser = new JSlider(JSlider.HORIZONTAL, 2, 10, 4); branchesWidthParser.setMajorTickSpacing(2); branchesWidthParser.setMinorTickSpacing(1); branchesWidthParser.setPaintTicks(true); branchesWidthParser.setPaintLabels(true); // Setup Combo boxes latitudeAttributeNameParser = new JComboBox(new String[] {""location1""}); latitudeAttributeNameParser.setName(""latitudeComboBox""); latitudeAttributeNameParser.setToolTipText(""Choose latitude attribute name. "" + ""This attribute name is typically followed by number 1.""); longitudeAttributeNameParser = new JComboBox(new String[] {""location2""}); longitudeAttributeNameParser.setName(""longitudeComboBox""); longitudeAttributeNameParser.setToolTipText(""Choose longitude attribute name. "" + ""This attribute name is typically followed by number 2.""); // Setup progress bar progressBar = new JProgressBar(); // Setup left tools pane leftPanel = new JPanel(); leftPanel.setBackground(backgroundColor); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS)); // Add Listeners openTree.addActionListener(new ListenOpenTree()); generateKml.addActionListener(new ListenGenerateKml()); generateProcessing.addActionListener(new ListenGenerateProcessing()); saveProcessingPlot.addActionListener(new ListenSaveProcessingPlot()); polygonsMaxColorChooser .addActionListener(new ListenPolygonsMaxColorChooser()); branchesMaxColorChooser .addActionListener(new ListenBranchesMaxColorChooser()); polygonsMinColorChooser .addActionListener(new ListenPolygonsMinColorChooser()); branchesMinColorChooser .addActionListener(new ListenBranchesMinColorChooser()); // ///////////// // ---INPUT---// // ///////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Load tree file:"")); tmpPanel.add(openTree); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Most recent sampling date:"")); dateSpinner = new DateSpinner(); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(dateSpinner, c); String era[] = { ""AD"", ""BC"" }; eraParser = new JComboBox(era); c.gridx = 2; c.gridy = 0; tmpPanel.add(eraParser, c); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Latitude attribute name:"")); tmpPanel.add(latitudeAttributeNameParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Longitude attribute name:"")); tmpPanel.add(longitudeAttributeNameParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Input"", new Dimension( leftPanelWidth, spinningPanelHeight)); sp.showBottom(true); leftPanel.add(sp); // //////////////////////// // ---BRANCHES MAPPING---// // //////////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); // Branches color mapping tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBorder(new TitledBorder(""Branches color mapping:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(branchesMinColorChooser, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(branchesMaxColorChooser, c); tmpPanelsHolder.add(tmpPanel); // Branches width tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Branches width:"")); tmpPanel.add(branchesWidthParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Maximal altitude mapping:"")); tmpPanel.add(maxAltMappingParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Branches mapping"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////////// // ---POLYGONS MAPPING---// // //////////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); // Polygons color mapping tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBorder(new TitledBorder(""Polygons color mapping:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(polygonsMinColorChooser, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(polygonsMaxColorChooser, c); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Polygons mapping"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////// // ---COMPUTATIONS---// // //////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Number of intervals:"")); tmpPanel.add(numberOfIntervalsParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Time scale multiplier:"")); tmpPanel.add(timescalerParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Computations"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // ////////////// // ---OUTPUT---// // ////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""KML name:"")); tmpPanel.add(kmlPathParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Generate KML / Plot map:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(generateKml, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(generateProcessing, c); c.ipady = 7; c.gridwidth = 3; c.gridx = 0; c.gridy = 1; tmpPanel.add(progressBar, c); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Save plot:"")); tmpPanel.add(saveProcessingPlot); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Output"", new Dimension( leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////////// // ---LEFT SCROLL PANE---// // //////////////////////// JScrollPane leftScrollPane = new JScrollPane(leftPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); leftScrollPane.setMinimumSize(minimumDimension); leftScrollPane.setMaximumSize(new Dimension(leftPanelWidth, leftPanelHeight)); // Setup Processing pane continuousTreeToProcessing = new ContinuousTreeToProcessing(); continuousTreeToProcessing.setPreferredSize(new Dimension( mapImageWidth, mapImageHeight)); // if (System.getProperty(""java.runtime.name"").toLowerCase().startsWith( // ""openjdk"")) { // // JScrollPane rightScrollPane = new JScrollPane( // continuousTreeToProcessing, // JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, // JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); // rightScrollPane.setMinimumSize(minimumDimension); // // SplitPane splitPane = new SplitPane(JSplitPane.HORIZONTAL_SPLIT, // leftScrollPane, rightScrollPane); // splitPane.setDividerLocation(leftPanelWidth); // // this.add(splitPane); // // } else { ScrollPane rightScrollPane = new ScrollPane( ScrollPane.SCROLLBARS_ALWAYS); rightScrollPane.add(continuousTreeToProcessing); rightScrollPane.setMinimumSize(minimumDimension); SplitPane splitPane = new SplitPane(JSplitPane.HORIZONTAL_SPLIT, leftScrollPane, rightScrollPane); splitPane.setDividerLocation(leftPanelWidth); this.add(splitPane); // } }// END: Constructor //TODO: move all the tree parsing to separate tree parser class with getters for all the attributes we need private void populateAttributeComboboxes() { try { NexusImporter importer = new NexusImporter(new FileReader(treeFilename)); RootedTree tree = (RootedTree) importer.importNextTree(); LinkedHashSet uniqueAttributes = new LinkedHashSet(); for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { uniqueAttributes.addAll(node.getAttributeNames()); } } // re-initialise comboboxes ComboBoxModel latitudeNameParserModel = new DefaultComboBoxModel(uniqueAttributes.toArray(new String[0])); latitudeAttributeNameParser.setModel(latitudeNameParserModel); ComboBoxModel longitudeNameParserModel = new DefaultComboBoxModel(uniqueAttributes.toArray(new String[0])); longitudeAttributeNameParser.setModel(longitudeNameParserModel); } catch (FileNotFoundException e) { Utils.handleException(e, e.getMessage()); } catch (IOException e) { Utils.handleException(e, e.getMessage()); } catch (ImportException e) { Utils.handleException(e, e.getMessage()); } }//END: populateAttributeCombobox private class ListenOpenTree implements ActionListener { public void actionPerformed(ActionEvent ev) { try { String[] treeFiles = new String[] { ""tre"", ""tree"", ""trees"" }; final JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Loading tree file...""); chooser.setMultiSelectionEnabled(false); chooser.addChoosableFileFilter(new SimpleFileFilter(treeFiles, ""Tree files (*.tree(s), *.tre)"")); chooser.setCurrentDirectory(workingDirectory); int returnVal = chooser.showOpenDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); treeFilename = file.getAbsolutePath(); frame.setStatus(""Opened "" + treeFilename + ""\n""); File tmpDir = chooser.getCurrentDirectory(); if (tmpDir != null) { workingDirectory = tmpDir; } populateAttributeComboboxes(); } else { System.out.println(""Could not Open! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenOpenTree private class ListenPolygonsMinColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose minimum polygons color..."", polygonsMinColor, true); if (c != null) polygonsMinColor = c; } } private class ListenPolygonsMaxColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose maximum polygons color..."", polygonsMaxColor, true); if (c != null) polygonsMaxColor = c; } } private class ListenBranchesMinColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose minimum branches color..."", branchesMinColor, true); if (c != null) branchesMinColor = c; } } private class ListenBranchesMaxColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose maximum branches color..."", branchesMaxColor, true); if (c != null) branchesMaxColor = c; } } private class ListenGenerateKml implements ActionListener { public void actionPerformed(ActionEvent ev) { if (treeFilename == null) { new ListenOpenTree().actionPerformed(ev); } else { generateKml.setEnabled(false); progressBar.setIndeterminate(true); SwingWorker worker = new SwingWorker() { // Executed in background thread public Void doInBackground() { try { //TODO: move the checks to tree parser ContinuousSanityCheck contSanCheck = new ContinuousSanityCheck(); if (contSanCheck.check(treeFilename, longitudeAttributeNameParser.getSelectedItem().toString(), latitudeAttributeNameParser.getSelectedItem().toString() )) { ContinuousTreeToKML continuousTreeToKML = new ContinuousTreeToKML(); continuousTreeToKML.setHPDString(contSanCheck .getHPDString()); continuousTreeToKML.setLongitudeName(longitudeAttributeNameParser.getSelectedItem().toString()); continuousTreeToKML.setLatitudeName(latitudeAttributeNameParser.getSelectedItem().toString()); continuousTreeToKML .setMaxAltitudeMapping(Double .valueOf(maxAltMappingParser .getText())); continuousTreeToKML .setMinPolygonRedMapping(polygonsMinColor .getRed()); continuousTreeToKML .setMinPolygonGreenMapping(polygonsMinColor .getGreen()); continuousTreeToKML .setMinPolygonBlueMapping(polygonsMinColor .getBlue()); continuousTreeToKML .setMinPolygonOpacityMapping(polygonsMinColor .getAlpha()); continuousTreeToKML .setMaxPolygonRedMapping(polygonsMaxColor .getRed()); continuousTreeToKML .setMaxPolygonGreenMapping(polygonsMaxColor .getGreen()); continuousTreeToKML .setMaxPolygonBlueMapping(polygonsMaxColor .getBlue()); continuousTreeToKML .setMaxPolygonOpacityMapping(polygonsMaxColor .getAlpha()); continuousTreeToKML .setMinBranchRedMapping(branchesMinColor .getRed()); continuousTreeToKML .setMinBranchGreenMapping(branchesMinColor .getGreen()); continuousTreeToKML .setMinBranchBlueMapping(branchesMinColor .getBlue()); continuousTreeToKML .setMinBranchOpacityMapping(branchesMinColor .getAlpha()); continuousTreeToKML .setMaxBranchRedMapping(branchesMaxColor .getRed()); continuousTreeToKML .setMaxBranchGreenMapping(branchesMaxColor .getGreen()); continuousTreeToKML .setMaxBranchBlueMapping(branchesMaxColor .getBlue()); continuousTreeToKML .setMaxBranchOpacityMapping(branchesMaxColor .getAlpha()); continuousTreeToKML .setBranchWidth(branchesWidthParser .getValue()); continuousTreeToKML .setMrsdString(dateSpinner.getValue() + "" "" + (eraParser.getSelectedIndex() == 0 ? ""AD"" : ""BC"")); continuousTreeToKML.setTimescaler(Double .valueOf(timescalerParser.getText())); continuousTreeToKML .setNumberOfIntervals(Integer .valueOf(numberOfIntervalsParser .getText())); continuousTreeToKML .setKmlWriterPath(workingDirectory .toString() .concat(""/"") .concat(kmlPathParser.getText())); continuousTreeToKML.setTreePath(treeFilename); continuousTreeToKML.GenerateKML(); System.out .println(""Finished in: "" + continuousTreeToKML.time + "" msec \n""); }// END: check } catch (final Exception e) { Utils.handleException(e, null); }// END: try-catch return null; }// END: doInBackground() // Executed in event dispatch thread public void done() { generateKml.setEnabled(true); progressBar.setIndeterminate(false); frame.setStatus(""Generated "" + workingDirectory.toString().concat(""/"") .concat(kmlPathParser.getText())); } }; worker.execute(); }// END: if not loaded }// END: actionPerformed }// END: ListenGenerateKml private class ListenGenerateProcessing implements ActionListener { public void actionPerformed(ActionEvent ev) { if (treeFilename == null) { new ListenOpenTree().actionPerformed(ev); } else { generateProcessing.setEnabled(false); progressBar.setIndeterminate(true); SwingWorker worker = new SwingWorker() { // Executed in background thread public Void doInBackground() { try { ContinuousSanityCheck contSanCheck = new ContinuousSanityCheck(); if (contSanCheck.check(treeFilename, longitudeAttributeNameParser.getSelectedItem().toString(), latitudeAttributeNameParser.getSelectedItem().toString() )) { continuousTreeToProcessing .setTreePath(treeFilename); continuousTreeToProcessing.setLongitudeName(longitudeAttributeNameParser.getSelectedItem().toString()); continuousTreeToProcessing.setLatitudeName(latitudeAttributeNameParser.getSelectedItem().toString()); continuousTreeToProcessing .setHPDString(contSanCheck .getHPDString()); continuousTreeToProcessing .setMinPolygonRedMapping(polygonsMinColor .getRed()); continuousTreeToProcessing .setMinPolygonGreenMapping(polygonsMinColor .getGreen()); continuousTreeToProcessing .setMinPolygonBlueMapping(polygonsMinColor .getBlue()); continuousTreeToProcessing .setMinPolygonOpacityMapping(polygonsMinColor .getAlpha()); continuousTreeToProcessing .setMaxPolygonRedMapping(polygonsMaxColor .getRed()); continuousTreeToProcessing .setMaxPolygonGreenMapping(polygonsMaxColor .getGreen()); continuousTreeToProcessing .setMaxPolygonBlueMapping(polygonsMaxColor .getBlue()); continuousTreeToProcessing .setMaxPolygonOpacityMapping(polygonsMaxColor .getAlpha()); continuousTreeToProcessing .setMinBranchRedMapping(branchesMinColor .getRed()); continuousTreeToProcessing .setMinBranchGreenMapping(branchesMinColor .getGreen()); continuousTreeToProcessing .setMinBranchBlueMapping(branchesMinColor .getBlue()); continuousTreeToProcessing .setMinBranchOpacityMapping(branchesMinColor .getAlpha()); continuousTreeToProcessing .setMaxBranchRedMapping(branchesMaxColor .getRed()); continuousTreeToProcessing .setMaxBranchGreenMapping(branchesMaxColor .getGreen()); continuousTreeToProcessing .setMaxBranchBlueMapping(branchesMaxColor .getBlue()); continuousTreeToProcessing .setMaxBranchOpacityMapping(branchesMaxColor .getAlpha()); continuousTreeToProcessing .setBranchWidth(branchesWidthParser .getValue() / 2); continuousTreeToProcessing.init(); }// END: check } catch (final Exception e) { Utils.handleException(e, null); }// END: try-catch return null; }// END: doInBackground() // Executed in event dispatch thread public void done() { generateProcessing.setEnabled(true); progressBar.setIndeterminate(false); frame.setStatus(""Finished. \n""); } }; worker.execute(); }// END: if not loaded }// END: actionPerformed }// END: ListenGenerateProcessing private class ListenSaveProcessingPlot implements ActionListener { public void actionPerformed(ActionEvent ev) { try { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Saving as png file...""); int returnVal = chooser.showSaveDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String filename = file.getAbsolutePath(); continuousTreeToProcessing.save(filename); frame.setStatus(""Saved "" + filename + ""\n""); } else { frame.setStatus(""Could not Save! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenSaveProcessingPlot }// END class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/SimpleFileFilter.java",".java","1065","49","package gui; import java.io.File; import javax.swing.filechooser.FileFilter; public class SimpleFileFilter extends FileFilter { private String[] extensions; private String description; public SimpleFileFilter(String ext) { this(new String[] { ext }, null); } public SimpleFileFilter(String[] exts, String descr) { // clone and lowercase the extensions extensions = new String[exts.length]; for (int i = exts.length - 1; i >= 0; i--) { extensions[i] = exts[i].toLowerCase(); } // make sure we have a valid (if simplistic) description description = (descr == null ? exts[0] + "" files"" : descr); } public boolean accept(File f) { // we always allow directories, regardless of their extension if (f.isDirectory()) { return true; } // ok, it's a regular file so check the extension String name = f.getName().toLowerCase(); for (int i = extensions.length - 1; i >= 0; i--) { if (name.endsWith(extensions[i])) { return true; } } return false; } public String getDescription() { return description; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/DiscreteModelTab.java",".java","27318","926","package gui; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.ScrollPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.LinkedHashSet; import javax.swing.BoxLayout; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingWorker; import javax.swing.border.TitledBorder; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.trees.RootedTree; import templates.DiscreteTreeToKML; import templates.DiscreteTreeToProcessing; import templates.MapBackground; import utils.Utils; import app.SpreadApp; import checks.DiscreteSanityCheck; import colorpicker.swing.ColorPicker; @SuppressWarnings(""serial"") public class DiscreteModelTab extends JPanel { //Shared Frame private SpreadApp frame; // Sizing constants private final int leftPanelWidth = 260; private final int leftPanelHeight = 1000; private final int spinningPanelHeight = 20; private final int mapImageWidth = MapBackground.MAP_IMAGE_WIDTH; private final int mapImageHeight = MapBackground.MAP_IMAGE_HEIGHT; private final Dimension minimumDimension = new Dimension(0, 0); // Colors private Color backgroundColor; private Color polygonsMaxColor; private Color branchesMaxColor; private Color polygonsMinColor; private Color branchesMinColor; // Locations & coordinates table private InteractiveTableModel table = null; // Strings for paths private String treeFilename = null; private File workingDirectory = null; // Text fields private JTextField numberOfIntervalsParser; private JTextField maxAltMappingParser; private JTextField kmlPathParser; private JTextField timescalerParser; // Spinners private DateSpinner dateSpinner; // Buttons private JButton generateKml; private JButton openTree; private JButton openLocationCoordinatesEditor; private JButton generateProcessing; private JButton saveProcessingPlot; private JButton polygonsMaxColorChooser; private JButton branchesMaxColorChooser; private JButton polygonsMinColorChooser; private JButton branchesMinColorChooser; // Sliders private JSlider branchesWidthParser; private JSlider polygonsRadiusMultiplierParser; // Combo boxes private JComboBox eraParser; private JComboBox stateAttributeNameParser; // left tools pane private JPanel leftPanel; private JPanel tmpPanel; private SpinningPanel sp; private JPanel tmpPanelsHolder; // Processing pane private DiscreteTreeToProcessing discreteTreeToProcessing; // Progress bar private JProgressBar progressBar; public DiscreteModelTab(SpreadApp spreadApp) { this.frame = spreadApp; // Setup miscallenous setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); backgroundColor = new Color(231, 237, 246); polygonsMinColor = new Color(0, 0, 0, 100); polygonsMaxColor = new Color(50, 255, 255, 255); branchesMinColor = new Color(0, 0, 0, 255); branchesMaxColor = new Color(255, 5, 50, 255); GridBagConstraints c = new GridBagConstraints(); // Setup text fields numberOfIntervalsParser = new JTextField(""100"", 10); maxAltMappingParser = new JTextField(""5000000"", 10); kmlPathParser = new JTextField(""output.kml"", 10); timescalerParser = new JTextField(""1"", 10); // Setup buttons for tab generateKml = new JButton(""Generate"", SpreadApp.nuclearIcon); openTree = new JButton(""Open"", SpreadApp.treeIcon); openLocationCoordinatesEditor = new JButton(""Setup"", SpreadApp.locationsIcon); generateProcessing = new JButton(""Plot"", SpreadApp.processingIcon); saveProcessingPlot = new JButton(""Save"", SpreadApp.saveIcon); polygonsMaxColorChooser = new JButton(""Setup max""); branchesMaxColorChooser = new JButton(""Setup max""); polygonsMinColorChooser = new JButton(""Setup min""); branchesMinColorChooser = new JButton(""Setup min""); // Setup sliders branchesWidthParser = new JSlider(JSlider.HORIZONTAL, 2, 10, 4); branchesWidthParser.setMajorTickSpacing(2); branchesWidthParser.setMinorTickSpacing(1); branchesWidthParser.setPaintTicks(true); branchesWidthParser.setPaintLabels(true); polygonsRadiusMultiplierParser = new JSlider(JSlider.HORIZONTAL, 1, 11, 1); polygonsRadiusMultiplierParser.setMajorTickSpacing(2); polygonsRadiusMultiplierParser.setMinorTickSpacing(1); polygonsRadiusMultiplierParser.setPaintTicks(true); polygonsRadiusMultiplierParser.setPaintLabels(true); // Setup Combo boxes stateAttributeNameParser = new JComboBox(new String[] {"" ""}); stateAttributeNameParser.setName("" ""); // Setup progress bar progressBar = new JProgressBar(); // Left tools pane leftPanel = new JPanel(); leftPanel.setBackground(backgroundColor); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.Y_AXIS)); openTree.addActionListener(new ListenOpenTree()); generateKml.addActionListener(new ListenGenerateKml()); openLocationCoordinatesEditor .addActionListener(new ListenOpenLocationCoordinatesEditor()); generateProcessing.addActionListener(new ListenGenerateProcessing()); saveProcessingPlot.addActionListener(new ListenSaveProcessingPlot()); polygonsMaxColorChooser .addActionListener(new ListenPolygonsMaxColorChooser()); branchesMaxColorChooser .addActionListener(new ListenBranchesMaxColorChooser()); polygonsMinColorChooser .addActionListener(new ListenPolygonsMinColorChooser()); branchesMinColorChooser .addActionListener(new ListenBranchesMinColorChooser()); // ///////////// // ---INPUT---// // ///////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Load tree file:"")); tmpPanel.add(openTree); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""State attribute name:"")); tmpPanel.add(stateAttributeNameParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Setup location coordinates:"")); tmpPanel.add(openLocationCoordinatesEditor); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Most recent sampling date:"")); dateSpinner = new DateSpinner(); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(dateSpinner, c); String era[] = { ""AD"", ""BC"" }; eraParser = new JComboBox(era); c.gridx = 2; c.gridy = 0; tmpPanel.add(eraParser, c); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Input"", new Dimension( leftPanelWidth, spinningPanelHeight)); sp.showBottom(true); leftPanel.add(sp); // //////////////////////// // ---BRANCHES MAPPING---// // //////////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); // Branches color mapping: tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Branches color mapping:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(branchesMinColorChooser, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(branchesMaxColorChooser, c); tmpPanelsHolder.add(tmpPanel); // Branches width: tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Branches width:"")); tmpPanel.add(branchesWidthParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Maximal altitude:"")); tmpPanel.add(maxAltMappingParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Branches mapping"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////////// // ---POLYGONS MAPPING---// // //////////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); // Circles color mapping: tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Circles color mapping:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(polygonsMinColorChooser, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(polygonsMaxColorChooser, c); tmpPanelsHolder.add(tmpPanel); // Circles radius multiplier: tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Circles radius multiplier:"")); tmpPanel.add(polygonsRadiusMultiplierParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Circles mapping"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////// // ---COMPUTATIONS---// // //////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Number of intervals:"")); tmpPanel.add(numberOfIntervalsParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Time scale multiplier:"")); tmpPanel.add(timescalerParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Computations"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // ////////////// // ---OUTPUT---// // ////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""KML name:"")); tmpPanel.add(kmlPathParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Generate KML / Plot map:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(generateKml, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(generateProcessing, c); c.ipady = 7; c.gridwidth = 3; c.gridx = 0; c.gridy = 1; tmpPanel.add(progressBar, c); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Save plot:"")); tmpPanel.add(saveProcessingPlot); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Output"", new Dimension( leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////////// // ---LEFT SCROLL PANE---// // //////////////////////// JScrollPane leftScrollPane = new JScrollPane(leftPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); leftScrollPane.setMinimumSize(minimumDimension); leftScrollPane.setMaximumSize(new Dimension(leftPanelWidth, leftPanelHeight)); /** * Processing pane * */ discreteTreeToProcessing = new DiscreteTreeToProcessing(); discreteTreeToProcessing.setPreferredSize(new Dimension(mapImageWidth, mapImageHeight)); // if (System.getProperty(""java.runtime.name"").toLowerCase().startsWith( // ""openjdk"")) { // // JScrollPane rightScrollPane = new JScrollPane( // discreteTreeToProcessing, // JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, // JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); // rightScrollPane.setMinimumSize(minimumDimension); // // SplitPane splitPane = new SplitPane(JSplitPane.HORIZONTAL_SPLIT, // leftScrollPane, rightScrollPane); // splitPane.setDividerLocation(leftPanelWidth); // // this.add(splitPane); // // } else { ScrollPane rightScrollPane = new ScrollPane( ScrollPane.SCROLLBARS_ALWAYS); rightScrollPane.add(discreteTreeToProcessing); rightScrollPane.setMinimumSize(minimumDimension); SplitPane splitPane = new SplitPane(JSplitPane.HORIZONTAL_SPLIT, leftScrollPane, rightScrollPane); splitPane.setDividerLocation(leftPanelWidth); this.add(splitPane); // } } // END: discreteModelTab private void populateAttributeComboboxes() { try { NexusImporter importer = new NexusImporter(new FileReader( treeFilename)); RootedTree tree = (RootedTree) importer.importNextTree(); LinkedHashSet uniqueAttributes = new LinkedHashSet(); for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { uniqueAttributes.addAll(node.getAttributeNames()); }// END: root check }// END: nodeloop // re-initialise comboboxes ComboBoxModel stateNameParserModel = new DefaultComboBoxModel(uniqueAttributes.toArray(new String[0])); stateAttributeNameParser.setModel(stateNameParserModel); } catch (FileNotFoundException e) { Utils.handleException(e, e.getMessage()); } catch (IOException e) { Utils.handleException(e, e.getMessage()); } catch (ImportException e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: populateAttributeComboboxes private class ListenOpenTree implements ActionListener { public void actionPerformed(ActionEvent ev) { try { String[] treeFiles = new String[] { ""tre"", ""tree"", ""trees"" }; final JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Loading tree file...""); chooser.setMultiSelectionEnabled(false); chooser.addChoosableFileFilter(new SimpleFileFilter(treeFiles, ""Tree files (*.tree(s), *.tre)"")); chooser.setCurrentDirectory(workingDirectory); int returnVal = chooser.showOpenDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); treeFilename = file.getAbsolutePath(); frame.setStatus(""Opened "" + treeFilename + ""\n""); File tmpDir = chooser.getCurrentDirectory(); if (tmpDir != null) { workingDirectory = tmpDir; } populateAttributeComboboxes(); } else { frame.setStatus(""Could not Open! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenOpenTree private class ListenOpenLocationCoordinatesEditor implements ActionListener { public void actionPerformed(ActionEvent ev) { try { LocationCoordinatesEditor locationCoordinatesEditor = new LocationCoordinatesEditor(frame); locationCoordinatesEditor.launch(treeFilename, stateAttributeNameParser.getSelectedItem().toString(), workingDirectory); table = locationCoordinatesEditor.getTable(); } catch (NullPointerException e) { Utils.handleException(e, ""Have you imported the proper tree file?""); } catch (RuntimeException e) { Utils.handleException( e, ""Have you specified proper state attribute name?"" + ""\nHave you set the posterior probability limit in treeAnnotator to zero?""); }// END: try-catch block }// END: actionPerformed }// END: ListenOpenLocations private class ListenPolygonsMinColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose minimum polygons color..."", polygonsMinColor, true); if (c != null) polygonsMinColor = c; } } private class ListenPolygonsMaxColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose maximum polygons color..."", polygonsMaxColor, true); if (c != null) polygonsMaxColor = c; } } private class ListenBranchesMinColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose minimum branches color..."", branchesMinColor, true); if (c != null) branchesMinColor = c; } } private class ListenBranchesMaxColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose maximum branches color..."", branchesMaxColor, true); if (c != null) branchesMaxColor = c; } } private class ListenGenerateKml implements ActionListener { public void actionPerformed(ActionEvent ev) { if (treeFilename == null) { new ListenOpenTree().actionPerformed(ev); } else if (table == null) { new ListenOpenLocationCoordinatesEditor().actionPerformed(ev); } else { generateKml.setEnabled(false); progressBar.setIndeterminate(true); SwingWorker worker = new SwingWorker() { // Executed in background thread public Void doInBackground() { try { if (new DiscreteSanityCheck().check(treeFilename, stateAttributeNameParser.getSelectedItem().toString(), table)) { DiscreteTreeToKML discreteTreeToKML = new DiscreteTreeToKML(); discreteTreeToKML.setTable(table); discreteTreeToKML .setStateAttName(stateAttributeNameParser.getSelectedItem().toString()); discreteTreeToKML .setMaxAltitudeMapping(Double .valueOf(maxAltMappingParser .getText())); discreteTreeToKML .setMrsdString(dateSpinner.getValue() + "" "" + (eraParser.getSelectedIndex() == 0 ? ""AD"" : ""BC"")); discreteTreeToKML.setTimescaler(Integer .valueOf(timescalerParser.getText())); discreteTreeToKML.setNumberOfIntervals(Integer .valueOf(numberOfIntervalsParser .getText())); discreteTreeToKML .setKmlWriterPath(workingDirectory .toString() .concat(""/"") .concat(kmlPathParser.getText())); discreteTreeToKML.setTreePath(treeFilename); discreteTreeToKML .setMinPolygonRedMapping(polygonsMinColor .getRed()); discreteTreeToKML .setMinPolygonGreenMapping(polygonsMinColor .getGreen()); discreteTreeToKML .setMinPolygonBlueMapping(polygonsMinColor .getBlue()); discreteTreeToKML .setMinPolygonOpacityMapping(polygonsMinColor .getAlpha()); discreteTreeToKML .setMaxPolygonRedMapping(polygonsMaxColor .getRed()); discreteTreeToKML .setMaxPolygonGreenMapping(polygonsMaxColor .getGreen()); discreteTreeToKML .setMaxPolygonBlueMapping(polygonsMaxColor .getBlue()); discreteTreeToKML .setMaxPolygonOpacityMapping(polygonsMaxColor .getAlpha()); discreteTreeToKML .setPolygonsRadiusMultiplier(polygonsRadiusMultiplierParser .getValue()); discreteTreeToKML .setMinBranchRedMapping(branchesMinColor .getRed()); discreteTreeToKML .setMinBranchGreenMapping(branchesMinColor .getGreen()); discreteTreeToKML .setMinBranchBlueMapping(branchesMinColor .getBlue()); discreteTreeToKML .setMinBranchOpacityMapping(branchesMinColor .getAlpha()); discreteTreeToKML .setMaxBranchRedMapping(branchesMaxColor .getRed()); discreteTreeToKML .setMaxBranchGreenMapping(branchesMaxColor .getGreen()); discreteTreeToKML .setMaxBranchBlueMapping(branchesMaxColor .getBlue()); discreteTreeToKML .setMaxBranchOpacityMapping(branchesMaxColor .getAlpha()); discreteTreeToKML .setBranchWidth(branchesWidthParser .getValue()); discreteTreeToKML.GenerateKML(); System.out.println(""Finished in: "" + discreteTreeToKML.time + "" msec \n""); }// END: check } catch (final Exception e) { Utils.handleException(e, null); } return null; }// END: doInBackground() // Executed in event dispatch thread public void done() { generateKml.setEnabled(true); progressBar.setIndeterminate(false); frame.setStatus(""Generated "" + workingDirectory.toString().concat(""/"") .concat(kmlPathParser.getText())); } }; worker.execute(); }// END: if not loaded }// END: actionPerformed }// END: ListenGenerateKml private class ListenGenerateProcessing implements ActionListener { public void actionPerformed(ActionEvent ev) { if (treeFilename == null) { new ListenOpenTree().actionPerformed(ev); } else if (table == null) { new ListenOpenLocationCoordinatesEditor().actionPerformed(ev); } else { generateProcessing.setEnabled(false); progressBar.setIndeterminate(true); SwingWorker worker = new SwingWorker() { // Executed in background thread public Void doInBackground() { // TODO This work should be activated after each option // changes (automatic responsive plotting); will make // for a much slicker program try { if (new DiscreteSanityCheck().check(treeFilename, stateAttributeNameParser.getSelectedItem().toString(), table)) { // TODO Should only be done with state data // changes, not with each draw discreteTreeToProcessing .setStateAttName(stateAttributeNameParser.getSelectedItem().toString()); // TODO Should only be done when changed, // not with each draw discreteTreeToProcessing.setTable(table); // TODO Should only be done when changed, // not with each draw discreteTreeToProcessing .setTreePath(treeFilename); discreteTreeToProcessing .setNumberOfIntervals(Integer .valueOf(numberOfIntervalsParser .getText())); discreteTreeToProcessing .setMinPolygonRedMapping(polygonsMinColor .getRed()); discreteTreeToProcessing .setMinPolygonGreenMapping(polygonsMinColor .getGreen()); discreteTreeToProcessing .setMinPolygonBlueMapping(polygonsMinColor .getBlue()); discreteTreeToProcessing .setMinPolygonOpacityMapping(polygonsMinColor .getAlpha()); discreteTreeToProcessing .setMaxPolygonRedMapping(polygonsMaxColor .getRed()); discreteTreeToProcessing .setMaxPolygonGreenMapping(polygonsMaxColor .getGreen()); discreteTreeToProcessing .setMaxPolygonBlueMapping(polygonsMaxColor .getBlue()); discreteTreeToProcessing .setMaxPolygonOpacityMapping(polygonsMaxColor .getAlpha()); discreteTreeToProcessing .setPolygonsRadiusMultiplier(polygonsRadiusMultiplierParser .getValue()); discreteTreeToProcessing .setMinBranchRedMapping(branchesMinColor .getRed()); discreteTreeToProcessing .setMinBranchGreenMapping(branchesMinColor .getGreen()); discreteTreeToProcessing .setMinBranchBlueMapping(branchesMinColor .getBlue()); discreteTreeToProcessing .setMinBranchOpacityMapping(branchesMinColor .getAlpha()); discreteTreeToProcessing .setMaxBranchRedMapping(branchesMaxColor .getRed()); discreteTreeToProcessing .setMaxBranchGreenMapping(branchesMaxColor .getGreen()); discreteTreeToProcessing .setMaxBranchBlueMapping(branchesMaxColor .getBlue()); discreteTreeToProcessing .setMaxBranchOpacityMapping(branchesMaxColor .getAlpha()); discreteTreeToProcessing .setBranchWidth(branchesWidthParser .getValue() / 2); discreteTreeToProcessing.init(); }// END: check } catch (final Exception e) { Utils.handleException(e, null); } return null; }// END: doInBackground // Executed in event dispatch thread public void done() { generateProcessing.setEnabled(true); progressBar.setIndeterminate(false); frame.setStatus(""Finished. \n""); } }; worker.execute(); }// END: if not loaded }// END: actionPerformed }// END: ListenGenerateProcessing private class ListenSaveProcessingPlot implements ActionListener { public void actionPerformed(ActionEvent ev) { try { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Saving as png file...""); int returnVal = chooser.showSaveDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String filename = file.getAbsolutePath(); discreteTreeToProcessing.save(filename); frame.setStatus(""Saved "" + filename + ""\n""); } else { frame.setStatus(""Could not Save! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenSaveProcessingPlot }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/InteractiveTableModel.java",".java","3344","149","package gui; import java.util.Vector; import javax.swing.table.AbstractTableModel; @SuppressWarnings(""serial"") public class InteractiveTableModel extends AbstractTableModel { public static final int LOCATION_INDEX = 0; public static final int LONGITUDE_INDEX = 1; public static final int LATITUDE_INDEX = 2; public static final int HIDDEN_INDEX = 3; private String[] columnNames; private Vector dataVector; public InteractiveTableModel(String[] columnNames) { this.columnNames = columnNames; dataVector = new Vector(); } public String getColumnName(int column) { return columnNames[column]; } public String[] getColumn(int index) { String[] column = new String[dataVector.size()]; for (int i = 0; i < dataVector.size(); i++) { column[i] = String.valueOf(getValueAt(i, index)); } return column; } public boolean isCellEditable(int row, int column) { if (column == HIDDEN_INDEX) return false; else return true; } public Class getColumnClass(int column) { switch (column) { case LOCATION_INDEX: case LONGITUDE_INDEX: case LATITUDE_INDEX: return String.class; default: return Object.class; } } public Object getValueAt(int row, int column) { TableRecord record = (TableRecord) dataVector.get(row); switch (column) { case LOCATION_INDEX: return record.getLocation(); case LONGITUDE_INDEX: return record.getLongitude(); case LATITUDE_INDEX: return record.getLatitude(); default: return new Object(); } } public void setValueAt(Object value, int row, int column) { TableRecord record = (TableRecord) dataVector.get(row); switch (column) { case LOCATION_INDEX: record.setLocation((String) value); break; case LONGITUDE_INDEX: record.setLongitude((String) value); break; case LATITUDE_INDEX: record.setLatitude((String) value); break; default: System.out.println(""invalid index""); } fireTableCellUpdated(row, column); } public void printTable() { for (int i = 0; i < this.getRowCount(); i++) { for (int j = 0; j < this.getColumnCount() - 1; j++) { System.out.print(this.getValueAt(i, j) + ""\t""); } System.out.println(); } } public int getRowCount() { return dataVector.size(); } public int getColumnCount() { return columnNames.length; } // This appends a row public void addRow(TableRecord row) { dataVector.add(row); this.fireTableDataChanged(); } // This inserts a row at specified index public void insertRow(int index, TableRecord row) { dataVector.add(index, row); this.fireTableDataChanged(); } public void deleteRow(int row) { dataVector.remove(row); this.fireTableDataChanged(); } public void cleanTable() { // dataVector.clear(); for (int i = 0; i < dataVector.size(); i++) { deleteRow(i); } } public boolean hasEmptyRow() { if (dataVector.size() == 0) return false; TableRecord tableRecord = (TableRecord) dataVector.get(dataVector .size() - 1); if (tableRecord.getLocation().trim().equals("""") && tableRecord.getLongitude().trim().equals("""") && tableRecord.getLatitude().trim().equals("""")) { return true; } else return false; } public void addEmptyRow() { dataVector.add(new TableRecord()); fireTableRowsInserted(dataVector.size() - 1, dataVector.size() - 1); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/RowNumberTable.java",".java","3817","151","package gui; import java.awt.Component; import java.awt.Font; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JViewport; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.JTableHeader; import javax.swing.table.TableColumn; /* * Use a JTable as a renderer for row numbers of a given main table. * This table must be added to the row header of the scrollpane that * contains the main table. */ @SuppressWarnings(""serial"") public class RowNumberTable extends JTable implements ChangeListener, PropertyChangeListener { private JTable main; public RowNumberTable(JTable table) { main = table; main.addPropertyChangeListener(this); setFocusable(false); setAutoCreateColumnsFromModel(false); setModel(main.getModel()); setSelectionModel(main.getSelectionModel()); TableColumn column = new TableColumn(); column.setHeaderValue("" ""); addColumn(column); column.setCellRenderer(new RowNumberRenderer()); getColumnModel().getColumn(0).setPreferredWidth(50); setPreferredScrollableViewportSize(getPreferredSize()); } @Override public void addNotify() { super.addNotify(); Component c = getParent(); // Keep scrolling of the row table in sync with the main table. if (c instanceof JViewport) { JViewport viewport = (JViewport) c; viewport.addChangeListener(this); } } /* * Delegate method to main table */ @Override public int getRowCount() { return main.getRowCount(); } @Override public int getRowHeight(int row) { return main.getRowHeight(row); } /* * This table does not use any data from the main TableModel, so just return * a value based on the row parameter. */ @Override public Object getValueAt(int row, int column) { return Integer.toString(row + 1); } /* * Don't edit data in the main TableModel by mistake */ @Override public boolean isCellEditable(int row, int column) { return false; } // // Implement the ChangeListener // public void stateChanged(ChangeEvent e) { // Keep the scrolling of the row table in sync with main table JViewport viewport = (JViewport) e.getSource(); JScrollPane scrollPane = (JScrollPane) viewport.getParent(); scrollPane.getVerticalScrollBar() .setValue(viewport.getViewPosition().y); } // // Implement the PropertyChangeListener // public void propertyChange(PropertyChangeEvent e) { // Keep the row table in sync with the main table if (""selectionModel"".equals(e.getPropertyName())) { setSelectionModel(main.getSelectionModel()); } if (""model"".equals(e.getPropertyName())) { setModel(main.getModel()); } } /* * Borrow the renderer from JDK1.4.2 table header */ private static class RowNumberRenderer extends DefaultTableCellRenderer { public RowNumberRenderer() { setHorizontalAlignment(JLabel.CENTER); } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (table != null) { JTableHeader header = table.getTableHeader(); if (header != null) { setForeground(header.getForeground()); setBackground(header.getBackground()); setFont(header.getFont()); } } if (isSelected) { setFont(getFont().deriveFont(Font.BOLD)); } setText((value == null) ? """" : value.toString()); setBorder(UIManager.getBorder(""TableHeader.cellBorder"")); return this; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/TableRecord.java",".java","769","45","package gui; public class TableRecord { protected String location; protected String longitude; protected String latitude; public TableRecord() { location = """"; longitude = """"; latitude = """"; } public TableRecord(String location, String longitude, String latitude) { this.location = location; this.longitude = longitude; this.latitude = latitude; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getLongitude() { return longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getLatitude() { return latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/LocationCoordinatesEditor.java",".java","10385","389","package gui; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileReader; import java.io.PrintWriter; import java.util.HashSet; import java.util.Set; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ScrollPaneConstants; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumn; import jebl.evolution.graphs.Node; import jebl.evolution.io.NexusImporter; import jebl.evolution.trees.RootedTree; import readers.LocationsReader; import utils.Utils; import app.SpreadApp; public class LocationCoordinatesEditor { private InteractiveTableModel returnValue = null; private SpreadApp frame; // Window private JDialog window; private Frame owner; // Menubar private JMenuBar menu; // Buttons with options private JButton load; private JButton save; private JButton done; // Strings for paths private String locationsFilename; private File workingDirectory; // Data, model & stuff for JTable private JTable table; private InteractiveTableModel tableModel; private String[] COLUMN_NAMES = { ""Location"", ""Latitude"", ""Longitude"", """" }; public LocationCoordinatesEditor(SpreadApp frame) { this.frame = frame; // Setup Main Menu buttons load = new JButton(""Load"", SpreadApp.loadIcon); save = new JButton(""Save"", SpreadApp.saveIcon); done = new JButton(""Done"", SpreadApp.doneIcon); // Add Main Menu buttons listeners load.addActionListener(new ListenOpenLocations()); save.addActionListener(new ListenSaveLocationCoordinates()); done.addActionListener(new ListenOk()); // Setup menu menu = new JMenuBar(); menu.setLayout(new BorderLayout()); JPanel buttonsHolder = new JPanel(); buttonsHolder.setOpaque(false); buttonsHolder.add(load); buttonsHolder.add(save); buttonsHolder.add(done); menu.add(buttonsHolder, BorderLayout.WEST); // Setup table tableModel = new InteractiveTableModel(COLUMN_NAMES); tableModel.addTableModelListener(new InteractiveTableModelListener()); table = new JTable(tableModel); table.setModel(tableModel); table.setSurrendersFocusOnKeystroke(true); TableColumn hidden = table.getColumnModel().getColumn( InteractiveTableModel.HIDDEN_INDEX); hidden.setMinWidth(2); hidden.setPreferredWidth(2); hidden.setMaxWidth(2); hidden.setCellRenderer(new InteractiveRenderer( InteractiveTableModel.HIDDEN_INDEX)); JScrollPane scrollPane = new JScrollPane(table, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); RowNumberTable rowNumberTable = new RowNumberTable(table); scrollPane.setRowHeaderView(rowNumberTable); scrollPane.setCorner(JScrollPane.UPPER_LEFT_CORNER, rowNumberTable .getTableHeader()); // Setup window owner = Utils.getActiveFrame(); window = new JDialog(owner, ""Setup location coordinates...""); window.getContentPane().add(menu, BorderLayout.NORTH); window.getContentPane().add(scrollPane); window.pack(); window.setLocationRelativeTo(owner); }// END: LocationCoordinatesEditor() private class ListenOpenLocations implements ActionListener { public void actionPerformed(ActionEvent ev) { try { final JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Loading location file...""); chooser.setMultiSelectionEnabled(false); chooser.setCurrentDirectory(workingDirectory); int returnVal = chooser.showOpenDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); locationsFilename = file.getAbsolutePath(); frame.setStatus(""Opened "" + locationsFilename + ""\n""); File tmpDir = chooser.getCurrentDirectory(); if (tmpDir != null) { workingDirectory = tmpDir; LocationsReader data = new LocationsReader( locationsFilename); if (tableModel.getRowCount() < data.nrow) { for (int i = 0; i < data.nrow - 1; i++) { tableModel.addEmptyRow(); } } for (int i = 0; i < data.nrow; i++) { tableModel.setValueAt(data.locations[i], i, 0); for (int j = 0; j < 2; j++) { tableModel.setValueAt( String.valueOf(data.coordinates[i][j]), i, j + 1); }// END: col loop }// END: row loop }// END: null check } else { frame.setStatus(""Could not Open! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenOpenLocations private class ListenSaveLocationCoordinates implements ActionListener { public void actionPerformed(ActionEvent ev) { try { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Saving as tab delimited file...""); int returnVal = chooser.showSaveDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String filename = file.getAbsolutePath(); JTableToTDV(filename, tableModel); frame.setStatus(""Saved "" + filename + ""\n""); } else { frame.setStatus(""Could not Save! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenSaveLocationCoordinates private class ListenOk implements ActionListener { public void actionPerformed(ActionEvent ev) { window.setVisible(false); returnValue = tableModel; frame.setStatus(""Loaded "" + returnValue.getRowCount() + "" discrete locations:""); returnValue.printTable(); }// END: actionPerformed }// END: ListenSaveLocationCoordinates private class InteractiveTableModelListener implements TableModelListener { public void tableChanged(TableModelEvent ev) { if (ev.getType() == TableModelEvent.UPDATE) { int column = ev.getColumn(); int row = ev.getFirstRow(); table.setColumnSelectionInterval(column + 1, column + 1); table.setRowSelectionInterval(row, row); } } }// END: InteractiveTableModelListener @SuppressWarnings(""serial"") private class InteractiveRenderer extends DefaultTableCellRenderer { protected int interactiveColumn; public InteractiveRenderer(int interactiveColumn) { this.interactiveColumn = interactiveColumn; } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (column == interactiveColumn && hasFocus) { if ((tableModel.getRowCount() - 1) == row && !tableModel.hasEmptyRow()) { tableModel.addEmptyRow(); } highlightLastRow(row); } return c; } }// END: getTableCellRendererComponent private void highlightLastRow(int row) { int lastrow = tableModel.getRowCount(); if (row == lastrow - 1) { table.setRowSelectionInterval(lastrow - 1, lastrow - 1); } else { table.setRowSelectionInterval(row + 1, row + 1); } table.setColumnSelectionInterval(0, 0); }// END: highlightLastRow private void JTableToTDV(String filename, InteractiveTableModel model) { boolean empty = false; try { PrintWriter printWriter = new PrintWriter(filename); for (int i = 0; i < model.getRowCount(); i++) { for (int j = 0; j < model.getColumnCount() - 1; j++) { String s = model.getValueAt(i, j).toString(); empty = s.trim().equals(""""); if (!empty) { printWriter.print(s + ""\t""); }// END: check for empty values }// END: col loop if (!empty) { printWriter.println(""""); }// END: check for empty values }// END: row loop printWriter.close(); } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: JTableToTDV private Object[] getUniqueTreeStates(RootedTree tree, String stateAttName) { Set uniqueTreeStates = new HashSet(); for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { String[] states = Utils.getStringNodeAttribute(node, stateAttName).split(""\\+""); for (int i = 0; i < states.length; i++) { uniqueTreeStates.add(states[i]); } }// END: isRoot }// END: node loop Object[] uniqueTreeStatesArray = uniqueTreeStates.toArray(); return uniqueTreeStatesArray; }// END: getUniqueTreeStates public void launch(String treeFilename, String stateAttName, File workingDirectory) { try { this.workingDirectory = workingDirectory; if(treeFilename == null) { Utils.handleError(""Must open a file first.""); return; } RootedTree tree = (RootedTree) new NexusImporter(new FileReader( treeFilename)).importNextTree(); Object[] uniqueTreeStates = getUniqueTreeStates(tree, stateAttName); for (int i = 0; i < uniqueTreeStates.length; i++) { tableModel.insertRow(i, new TableRecord(String .valueOf(uniqueTreeStates[i]), """", """")); }// END: row loop // Display Frame window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); window.setSize(new Dimension(350, 300)); window.setMinimumSize(new Dimension(100, 100)); window.setResizable(true); window.setVisible(true); } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: launch public InteractiveTableModel getTable() { return tableModel; } public void launch(File workingDirectory) { if (!tableModel.hasEmptyRow()) { tableModel.addEmptyRow(); } this.workingDirectory = workingDirectory; // Display Frame window.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); window.setSize(new Dimension(300, 300)); window.setMinimumSize(new Dimension(100, 100)); window.setResizable(true); window.setVisible(true); }// END: launch public String[] getColumnNames() { return COLUMN_NAMES; }// END: getColumnNames }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/gui/RateIndicatorBFTab.java",".java","23958","817","package gui; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.ScrollPane; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.BoxLayout; import javax.swing.ComboBoxModel; import javax.swing.DefaultComboBoxModel; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSlider; import javax.swing.JSplitPane; import javax.swing.JTextField; import javax.swing.SwingWorker; import javax.swing.border.TitledBorder; import readers.LogFileReader; import templates.MapBackground; import templates.RateIndicatorBFToKML; import templates.RateIndicatorBFToProcessing; import utils.Utils; import app.SpreadApp; import colorpicker.swing.ColorPicker; @SuppressWarnings(""serial"") public class RateIndicatorBFTab extends JPanel { // Shared Frame private SpreadApp frame; // Sizing constants private final int leftPanelWidth = 260; private final int leftPanelHeight = 1000; private final int spinningPanelHeight = 20; private final int mapImageWidth = MapBackground.MAP_IMAGE_WIDTH; private final int mapImageHeight = MapBackground.MAP_IMAGE_HEIGHT; private final Dimension minimumDimension = new Dimension(0, 0); // Colors private Color backgroundColor; private Color branchesMaxColor; private Color branchesMinColor; // Locations & coordinates table private InteractiveTableModel table = null; // Strings for paths private String logFilename = null; private File workingDirectory = null; // Text fields private JTextField numberOfIntervalsParser; private JTextField maxAltMappingParser; private JTextField bfCutoffParser; private JTextField kmlPathParser; // Buttons private JButton openLog; private JButton openLocations; private JButton generateKml; private JButton generateProcessing; private JButton saveProcessingPlot; private JButton branchesMaxColorChooser; private JButton branchesMinColorChooser; // Sliders private JSlider burnInParser; private JSlider branchesWidthParser; // Combo boxes private JComboBox meanPoissonPriorParser; private JComboBox poissonPriorOffsetParser; private JComboBox indicatorNameBox; // Left tools pane private JPanel leftPanel; private JPanel tmpPanel; private SpinningPanel sp; private JPanel tmpPanelsHolder; // Processing pane private RateIndicatorBFToProcessing rateIndicatorBFToProcessing; // Progress bar private JProgressBar progressBar; public RateIndicatorBFTab(SpreadApp spreadApp) { this.frame = spreadApp; // Setup miscallenous setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS)); backgroundColor = new Color(231, 237, 246); branchesMaxColor = new Color(255, 5, 50, 255); branchesMinColor = new Color(0, 0, 0, 255); GridBagConstraints c = new GridBagConstraints(); // Setup text fields numberOfIntervalsParser = new JTextField(""100"", 10); maxAltMappingParser = new JTextField(""500000"", 10); bfCutoffParser = new JTextField(""3.0"", 5); kmlPathParser = new JTextField(""output.kml"", 10); // Setup buttons openLog = new JButton(""Open"", SpreadApp.logIcon); openLocations = new JButton(""Open"", SpreadApp.locationsIcon); generateKml = new JButton(""Generate"", SpreadApp.nuclearIcon); generateProcessing = new JButton(""Plot"", SpreadApp.processingIcon); saveProcessingPlot = new JButton(""Save"", SpreadApp.saveIcon); branchesMaxColorChooser = new JButton(""Setup max""); branchesMinColorChooser = new JButton(""Setup min""); // Setup sliders burnInParser = new JSlider(JSlider.HORIZONTAL, 0, 100, 10); burnInParser.setMajorTickSpacing(20); burnInParser.setMinorTickSpacing(10); burnInParser.setPaintTicks(true); burnInParser.setPaintLabels(true); branchesWidthParser = new JSlider(JSlider.HORIZONTAL, 2, 10, 4); branchesWidthParser.setMajorTickSpacing(2); branchesWidthParser.setMinorTickSpacing(1); branchesWidthParser.setPaintTicks(true); branchesWidthParser.setPaintLabels(true); // Setup Combo boxes indicatorNameBox = new JComboBox(new String[] {""indicator""}); // Setup progress bar progressBar = new JProgressBar(); /** * left tools pane * */ leftPanel = new JPanel(); leftPanel.setBackground(backgroundColor); leftPanel.setLayout(new BoxLayout(leftPanel, BoxLayout.PAGE_AXIS)); // leftPanel.setSize(new Dimension(leftPanelWidth, leftPanelHeight)); // Listeners openLog.addActionListener(new ListenOpenLog()); generateKml.addActionListener(new ListenGenerateKml()); openLocations .addActionListener(new ListenOpenLocationCoordinatesEditor()); generateProcessing.addActionListener(new ListenGenerateProcessing()); saveProcessingPlot.addActionListener(new ListenSaveProcessingPlot()); branchesMaxColorChooser .addActionListener(new ListenBranchesMaxColorChooser()); branchesMinColorChooser .addActionListener(new ListenBranchesMinColorChooser()); // ///////////// // ---INPUT---// // ///////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Load log file:"")); tmpPanel.add(openLog); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Setup location coordinates:"")); tmpPanel.add(openLocations); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Indicator attribute name:"")); tmpPanel.add(indicatorNameBox); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Input"", new Dimension( leftPanelWidth, spinningPanelHeight)); sp.showBottom(true); leftPanel.add(sp); // //////////////////// // ---COMPUTATIONS---// // //////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Specify burn-in %:"")); tmpPanel.add(burnInParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Poisson prior mean / offset:"")); String[] meanPoissonPrior = { ""log(2)"", "" "" }; meanPoissonPriorParser = new JComboBox(meanPoissonPrior); meanPoissonPriorParser.setEditable(true); meanPoissonPriorParser.setPreferredSize(new Dimension(70, 25)); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(meanPoissonPriorParser, c); String[] poissonPriorOffset = { ""n-1"", "" "" }; poissonPriorOffsetParser = new JComboBox(poissonPriorOffset); poissonPriorOffsetParser.setEditable(true); poissonPriorOffsetParser.setPreferredSize(new Dimension(70, 25)); c.gridx = 2; c.gridy = 0; tmpPanel.add(poissonPriorOffsetParser, c); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Bayes Factor cut-off:"")); tmpPanel.add(bfCutoffParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Computations"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////////// // ---BRANCHES MAPPING---// // //////////////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); // Rates color mapping: tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Rates color mapping:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(branchesMinColorChooser, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(branchesMaxColorChooser, c); tmpPanelsHolder.add(tmpPanel); // Branches width: tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Rates width:"")); tmpPanel.add(branchesWidthParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Number of intervals:"")); tmpPanel.add(numberOfIntervalsParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Maximal altitude:"")); tmpPanel.add(maxAltMappingParser); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Branches mapping"", new Dimension(leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // ////////////// // ---OUTPUT---// // ////////////// tmpPanelsHolder = new JPanel(); tmpPanelsHolder.setLayout(new BoxLayout(tmpPanelsHolder, BoxLayout.Y_AXIS)); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""KML name:"")); tmpPanel.add(kmlPathParser); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setLayout(new GridBagLayout()); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Generate KML / Plot map:"")); c.fill = GridBagConstraints.HORIZONTAL; c.gridx = 0; c.gridy = 0; tmpPanel.add(generateKml, c); c.gridx = 2; c.gridy = 0; tmpPanel.add(generateProcessing, c); c.ipady = 7; c.gridwidth = 3; c.gridx = 0; c.gridy = 1; tmpPanel.add(progressBar, c); tmpPanelsHolder.add(tmpPanel); tmpPanel = new JPanel(); tmpPanel.setMaximumSize(new Dimension(leftPanelWidth, 100)); tmpPanel.setBackground(backgroundColor); tmpPanel.setBorder(new TitledBorder(""Save plot:"")); tmpPanel.add(saveProcessingPlot); tmpPanelsHolder.add(tmpPanel); sp = new SpinningPanel(tmpPanelsHolder, "" Output"", new Dimension( leftPanelWidth, spinningPanelHeight)); sp.showBottom(false); leftPanel.add(sp); // //////////////////////// // ---LEFT SCROLL PANE---// // //////////////////////// JScrollPane leftScrollPane = new JScrollPane(leftPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); leftScrollPane.setMinimumSize(minimumDimension); leftScrollPane.setMaximumSize(new Dimension(leftPanelWidth, leftPanelHeight)); /** * Processing pane * */ rateIndicatorBFToProcessing = new RateIndicatorBFToProcessing(); rateIndicatorBFToProcessing.setPreferredSize(new Dimension( mapImageWidth, mapImageHeight)); // if (System.getProperty(""java.runtime.name"").toLowerCase().startsWith( // ""openjdk"")) { // // JScrollPane rightScrollPane = new JScrollPane( // rateIndicatorBFToProcessing, // JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, // JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); // rightScrollPane.setMinimumSize(minimumDimension); // // SplitPane splitPane = new SplitPane(JSplitPane.HORIZONTAL_SPLIT, // leftScrollPane, rightScrollPane); // splitPane.setDividerLocation(leftPanelWidth); // // this.add(splitPane); // // } else { ScrollPane rightScrollPane = new ScrollPane( ScrollPane.SCROLLBARS_ALWAYS); rightScrollPane.add(rateIndicatorBFToProcessing); rightScrollPane.setMinimumSize(minimumDimension); SplitPane splitPane = new SplitPane(JSplitPane.HORIZONTAL_SPLIT, leftScrollPane, rightScrollPane); splitPane.setDividerLocation(leftPanelWidth); this.add(splitPane); // } }// END: Constructor private void populateInidcatorCombobox() { LogFileReader parser = new LogFileReader(); String [] colNames = parser.getColNames(logFilename); // remove numbers from end of column name, and count their occurrances Map map = new HashMap(); for (String colName : colNames) { colName = colName.replaceAll(""[0-9]*$"", """"); if (map.containsKey(colName)) { map.put(colName, map.get(colName) + 1); } else { map.put(colName, 1); } } // make those that occur more than once a candidate List indicatorNames = new ArrayList(); for (String colName : map.keySet()) { if (map.get(colName) > 1) { indicatorNames.add(colName); } } // re-initialise combobox ComboBoxModel model = new DefaultComboBoxModel(indicatorNames.toArray(new String[0])); indicatorNameBox.setModel(model); } private class ListenOpenLog implements ActionListener { public void actionPerformed(ActionEvent ev) { try { String[] logFiles = new String[] { ""log"" }; final JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Loading tree file...""); chooser.setMultiSelectionEnabled(false); chooser.addChoosableFileFilter(new SimpleFileFilter(logFiles, ""Log files (*.log)"")); chooser.setCurrentDirectory(workingDirectory); int returnVal = chooser.showOpenDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); logFilename = file.getAbsolutePath(); System.out.println(""Opened "" + logFilename + ""\n""); File tmpDir = chooser.getCurrentDirectory(); if (tmpDir != null) { workingDirectory = tmpDir; } populateInidcatorCombobox(); } else { System.out.println(""Could not Open! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenOpenLog private class ListenOpenLocationCoordinatesEditor implements ActionListener { public void actionPerformed(ActionEvent ev) { try { LocationCoordinatesEditor locationCoordinatesEditor = new LocationCoordinatesEditor(frame); locationCoordinatesEditor.launch(workingDirectory); table = locationCoordinatesEditor.getTable(); } catch (Exception e) { Utils.handleException(e, e.getMessage()); } } }// END: ListenOpenLocations private class ListenBranchesMinColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose minimum branches color..."", branchesMinColor, true); if (c != null) branchesMinColor = c; } } private class ListenBranchesMaxColorChooser implements ActionListener { public void actionPerformed(ActionEvent ev) { Color c = ColorPicker.showDialog(Utils.getActiveFrame(), ""Choose maximum branches color..."", branchesMaxColor, true); if (c != null) branchesMaxColor = c; } } private class ListenGenerateKml implements ActionListener { public void actionPerformed(ActionEvent ev) { if (logFilename == null) { new ListenOpenLog().actionPerformed(ev); } else if (table == null) { new ListenOpenLocationCoordinatesEditor().actionPerformed(ev); } else { generateKml.setEnabled(false); progressBar.setIndeterminate(true); SwingWorker worker = new SwingWorker() { // Executed in background thread public Void doInBackground() { try { RateIndicatorBFToKML rateIndicatorBFToKML = new RateIndicatorBFToKML(); rateIndicatorBFToKML.setTable(table); rateIndicatorBFToKML.setLogFileParser(logFilename, burnInParser.getValue() / 100.0, indicatorNameBox.getSelectedItem().toString()); rateIndicatorBFToKML.setBfCutoff(Double .valueOf(bfCutoffParser.getText())); rateIndicatorBFToKML.setMaxAltitudeMapping(Double .valueOf(maxAltMappingParser.getText())); rateIndicatorBFToKML .setNumberOfIntervals(Integer .valueOf(numberOfIntervalsParser .getText())); rateIndicatorBFToKML .setKmlWriterPath(workingDirectory .toString().concat(""/"").concat( kmlPathParser.getText())); rateIndicatorBFToKML .setMinBranchRedMapping(branchesMinColor .getRed()); rateIndicatorBFToKML .setMinBranchGreenMapping(branchesMinColor .getGreen()); rateIndicatorBFToKML .setMinBranchBlueMapping(branchesMinColor .getBlue()); rateIndicatorBFToKML .setMinBranchOpacityMapping(branchesMinColor .getAlpha()); rateIndicatorBFToKML .setMaxBranchRedMapping(branchesMaxColor .getRed()); rateIndicatorBFToKML .setMaxBranchGreenMapping(branchesMaxColor .getGreen()); rateIndicatorBFToKML .setMaxBranchBlueMapping(branchesMaxColor .getBlue()); rateIndicatorBFToKML .setMaxBranchOpacityMapping(branchesMaxColor .getAlpha()); rateIndicatorBFToKML .setBranchWidth(branchesWidthParser .getValue()); if (meanPoissonPriorParser.getSelectedIndex() == 0) { rateIndicatorBFToKML .setDefaultMeanPoissonPrior(); } else { rateIndicatorBFToKML .setUserMeanPoissonPrior(Double .valueOf(meanPoissonPriorParser .getSelectedItem() .toString())); } if (poissonPriorOffsetParser.getSelectedIndex() == 0) { rateIndicatorBFToKML .setDefaultPoissonPriorOffset(); } else { rateIndicatorBFToKML .setUserPoissonPriorOffset(Double .valueOf(poissonPriorOffsetParser .getSelectedItem() .toString())); } rateIndicatorBFToKML.GenerateKML(); System.out.println(""Finished in: "" + RateIndicatorBFToKML.time + "" msec \n""); } catch (final OutOfMemoryError e) { Utils.handleException(e, ""Increase Java Heap Space""); // SwingUtilities.invokeLater(new Runnable() { // // public void run() { // // e.printStackTrace(); // // String msg = String.format( // ""Unexpected problem: %s"", e // .toString()); // // JOptionPane.showMessageDialog(Utils // .getActiveFrame(), msg // + ""\nIncrease Java Heap Space"", // ""Error"", JOptionPane.ERROR_MESSAGE, // SpreadApp.errorIcon); // // } // }); } catch (Exception e) { Utils.handleException(e, null); } return null; }// END: doInBackground() // Executed in event dispatch thread public void done() { generateKml.setEnabled(true); progressBar.setIndeterminate(false); System.out.println(""Generated "" + workingDirectory.toString().concat(""/"") .concat(kmlPathParser.getText())); } }; worker.execute(); }// END: if not loaded }// END: actionPerformed }// END: ListenGenerateKml private class ListenGenerateProcessing implements ActionListener { public void actionPerformed(ActionEvent ev) { if (logFilename == null) { new ListenOpenLog().actionPerformed(ev); } else if (table == null) { new ListenOpenLocationCoordinatesEditor().actionPerformed(ev); } else { generateProcessing.setEnabled(false); progressBar.setIndeterminate(true); SwingWorker worker = new SwingWorker() { // Executed in background thread public Void doInBackground() { try { rateIndicatorBFToProcessing.setTable(table); rateIndicatorBFToProcessing.setLogFilePath( logFilename, burnInParser.getValue() / 100.0, indicatorNameBox.getSelectedItem().toString()); rateIndicatorBFToProcessing.setBfCutoff(Double .valueOf(bfCutoffParser.getText())); // rateIndicatorBFToProcessing // .setNumberOfIntervals(Integer // .valueOf(numberOfIntervalsParser // .getText())); rateIndicatorBFToProcessing .setMinBranchRedMapping(branchesMinColor .getRed()); rateIndicatorBFToProcessing .setMinBranchGreenMapping(branchesMinColor .getGreen()); rateIndicatorBFToProcessing .setMinBranchBlueMapping(branchesMinColor .getBlue()); rateIndicatorBFToProcessing .setMinBranchOpacityMapping(branchesMinColor .getAlpha()); rateIndicatorBFToProcessing .setMaxBranchRedMapping(branchesMaxColor .getRed()); rateIndicatorBFToProcessing .setMaxBranchGreenMapping(branchesMaxColor .getGreen()); rateIndicatorBFToProcessing .setMaxBranchBlueMapping(branchesMaxColor .getBlue()); rateIndicatorBFToProcessing .setMaxBranchOpacityMapping(branchesMaxColor .getAlpha()); rateIndicatorBFToProcessing .setBranchWidth(branchesWidthParser .getValue() / 2); if (meanPoissonPriorParser.getSelectedIndex() == 0) { rateIndicatorBFToProcessing .setDefaultMeanPoissonPrior(); } else { rateIndicatorBFToProcessing .setUserMeanPoissonPrior(Double .valueOf(meanPoissonPriorParser .getSelectedItem() .toString())); } if (poissonPriorOffsetParser.getSelectedIndex() == 0) { rateIndicatorBFToProcessing .setDefaultPoissonPriorOffset(); } else { rateIndicatorBFToProcessing .setUserPoissonPriorOffset(Double .valueOf(poissonPriorOffsetParser .getSelectedItem() .toString())); } rateIndicatorBFToProcessing.init(); } catch (final Exception e) { Utils.handleException(e, null); } return null; }// END: doInBackground() // Executed in event dispatch thread public void done() { generateProcessing.setEnabled(true); progressBar.setIndeterminate(false); frame.setStatus(""Finished. \n""); } }; worker.execute(); }// END: if not loaded }// END: actionPerformed }// END: ListenGenerateProcessing private class ListenSaveProcessingPlot implements ActionListener { public void actionPerformed(ActionEvent ev) { try { JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(""Saving as png file...""); int returnVal = chooser.showSaveDialog(Utils.getActiveFrame()); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = chooser.getSelectedFile(); String filename = file.getAbsolutePath(); rateIndicatorBFToProcessing.save(filename); frame.setStatus(""Saved "" + filename + ""\n""); } else { frame.setStatus(""Could not Save! \n""); } } catch (Exception e) { Utils.handleException(e, e.getMessage()); }// END: try-catch block }// END: actionPerformed }// END: ListenSaveProcessingPlot }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/readers/LocationsReader.java",".java","2181","96","package readers; import java.text.ParseException; import processing.core.PApplet; @SuppressWarnings(""serial"") public class LocationsReader extends PApplet { private String[] lines; public String[] locations; public float[][] coordinates; public int nrow; public LocationsReader(String filename) throws ParseException { lines = loadStrings(filename); nrow = lines.length; locations = new String[nrow]; coordinates = new float[nrow][]; for (int i = 0; i < nrow; i++) { String[] line = lines[i].split(""\t""); locations[i] = line[0]; coordinates[i] = parseFloat(subset(line, 1)); } coordinates = (float[][]) coordinates; }// END: ReadLocation public String[] getLocations() { return locations; }// END: getLocations public float getLongMin() { /* this should maybe specify which column is lat/long */ float m = Float.MAX_VALUE; for (int row = 0; row < nrow; row++) { if (coordinates[row][0] < m) { m = coordinates[row][0]; } } return m; }// END: getLongMin public float getLongMax() { /* this should maybe specify which column is lat/long */ float m = -Float.MAX_VALUE; for (int row = 0; row < nrow; row++) { if (coordinates[row][0] > m) { m = coordinates[row][0]; } } return m; }// END: getLongMax public float getLatMin() { /* this should maybe specify which column is lat/long */ float m = Float.MAX_VALUE; for (int row = 0; row < nrow; row++) { if (coordinates[row][1] < m) { m = coordinates[row][1]; } } return m; }// END: getLatMin public float getLatMax() { /* this should maybe specify which column is lat/long */ float m = -Float.MAX_VALUE; for (int row = 0; row < nrow; row++) { if (coordinates[row][1] > m) { m = coordinates[row][1]; } } return m; }// END: getLatMax int getNrow() { return nrow; }// END: getNrow public float getFloat(int row, int col) { return coordinates[row][col]; }// END: getFloat public double[] getCoordsColumn(int columnIndex) { double[] x = new double[nrow]; for (int row = 0; row < nrow; row++) { x[row] = coordinates[row][columnIndex]; } return x; }// END: getCoordsColumn }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/readers/LogFileReader.java",".java","3042","130","package readers; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import processing.core.PApplet; import utils.Utils; @SuppressWarnings(""serial"") public class LogFileReader extends PApplet { private static final int HEADER_ROW = 0; public double[][] indicators; public int nrow; public int ncol; public LogFileReader() { } public LogFileReader(String filename, double burnIn, String indicatorName) { String[] lines = LoadStrings(filename); nrow = lines.length - 1; String[] colNames = lines[HEADER_ROW].split(""\t""); List list = new ArrayList(); // Create a pattern to match Pattern pattern = Pattern.compile(indicatorName); for (int row = 0; row < colNames.length; row++) { // Look for matches in column names Matcher matcher = pattern.matcher(colNames[row]); if (matcher.find()) { list.add(row); } } ncol = list.size(); // skip first line with col names and the burn in lines int delete = (int) (nrow * burnIn) + 1; indicators = new double[nrow - delete][ncol]; int i = 0; for (int row = delete; row < nrow; row++) { String[] line = lines[row].split(""\t""); indicators[i] = Utils.parseDouble(Utils.subset(line, list.get(0), ncol)); i++; } indicators = (double[][]) indicators; nrow = indicators.length; }// END: ReadLog public String [] getColNames(String filename) { // a bit ineffecient to read the complete log file // TODO: only read to column names line String[] lines = LoadStrings(filename); String[] colNames = lines[HEADER_ROW].split(""\t""); return colNames; } private String[] LoadStrings(String filename) { InputStream is = createInput(filename); if (is != null) return LoadStrings(is); System.err.println(""The file \"""" + filename + ""\"" "" + ""is missing or inaccessible, make sure "" + ""the URL is valid or that the file is readable.""); return null; } private String[] LoadStrings(InputStream input) { try { BufferedReader reader = new BufferedReader(new InputStreamReader( input, ""UTF-8"")); String lines[] = new String[100]; int lineCount = 0; String line = null; while (((line = reader.readLine()) != null)) { if (lineCount == lines.length) { String temp[] = new String[lineCount << 1]; System.arraycopy(lines, 0, temp, 0, lineCount); lines = temp; } // suppress commented lines if (!line.startsWith(""#"")) { lines[lineCount++] = line; } } reader.close(); if (lineCount == lines.length) { return lines; } // resize array to appropriate amount for these lines String output[] = new String[lineCount]; System.arraycopy(lines, 0, output, 0, lineCount); return output; } catch (IOException e) { Utils.handleException(e, ""Error when loading strings!""); } return null; } }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/readers/SliceHeightsReader.java",".java","544","28","package readers; import processing.core.PApplet; @SuppressWarnings(""serial"") public class SliceHeightsReader extends PApplet { private double[] sliceHeights; private int nrow; public SliceHeightsReader(String filename) { String[] lines = loadStrings(filename); nrow = lines.length; sliceHeights = new double[nrow]; for (int i = 0; i < nrow; i++) { sliceHeights[i] = Double.parseDouble(lines[i]); } }// END: constructor public double[] getSliceHeights() { return sliceHeights; }// END: getTimeSlices }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/app/SpreadApp.java",".java","10762","370","package app; import gui.ContinuousModelTab; import gui.DiscreteModelTab; import gui.RateIndicatorBFTab; import gui.TerminalTab; import gui.TimeSlicerTab; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.net.URL; import javax.swing.BoxLayout; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.border.BevelBorder; import utils.ExceptionHandler; public class SpreadApp { /** * Version string: assumed to be in format x.x.x */ private static final String VERSION = ""1.0.7""; private static final String DATE_STRING = ""2015""; // Dimension private Dimension dimension; // Icons public static ImageIcon quitIcon; public static ImageIcon helpIcon; public static ImageIcon clearIcon; public static ImageIcon nuclearIcon; public static ImageIcon treeIcon; public static ImageIcon processingIcon; public static ImageIcon saveIcon; public static ImageIcon errorIcon; public static ImageIcon locationsIcon; public static ImageIcon loadIcon; public static ImageIcon doneIcon; public static ImageIcon logIcon; public static ImageIcon timeSlicesIcon; public static ImageIcon treesIcon; // Frame private JFrame frame; private JTabbedPane tabbedPane; // Menubar private JToolBar mainMenu; // Buttons with options private JButton help; private JButton quit; private JButton clear; // Tabs private ContinuousModelTab continuousModelTab; private DiscreteModelTab discreteModelTab; private RateIndicatorBFTab rateIndicatorBFTab; private TimeSlicerTab timeSlicerTab; private TerminalTab terminalTab; // Status bar private JLabel statusbar; public SpreadApp() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException { boolean lafLoaded = false; // Setup Look & Feel if (System.getProperty(""os.name"").toLowerCase().startsWith(""mac os x"")) { // Mac stuff System.setProperty(""apple.awt.showGrowBox"", ""true""); System.setProperty(""apple.awt.brushMetalLook"", ""true""); System.setProperty(""apple.laf.useScreenMenuBar"", ""true""); System.setProperty(""apple.awt.graphics.UseQuartz"", ""true""); System.setProperty(""apple.awt.antialiasing"", ""true""); System.setProperty(""apple.awt.rendering"", ""VALUE_RENDER_QUALITY""); System.setProperty(""apple.laf.useScreenMenuBar"", ""true""); System.setProperty(""apple.awt.draggableWindowBackground"", ""true""); System.setProperty(""apple.awt.showGrowBox"", ""true""); UIManager.put(""SystemFont"", new Font(""Lucida Grande"", Font.PLAIN, 13)); UIManager.put(""SmallSystemFont"", new Font(""Lucida Grande"", Font.PLAIN, 11)); try { // UIManager.setLookAndFeel(UIManager // .getSystemLookAndFeelClassName()); UIManager .setLookAndFeel(""ch.randelshofer.quaqua.QuaquaLookAndFeel""); lafLoaded = true; } catch (Exception e) { // } } else { try { UIManager .setLookAndFeel(""com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel""); lafLoaded = true; } catch (Exception e) { // } } if (!lafLoaded) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); System.out.println(""Specified l&f not found. Loading system default l&f""); } catch (Exception e) { e.printStackTrace(); } } dimension = Toolkit.getDefaultToolkit().getScreenSize(); Toolkit.getDefaultToolkit().setDynamicLayout(true); // Setup icons quitIcon = CreateImageIcon(""/icons/close.png""); helpIcon = CreateImageIcon(""/icons/help.png""); clearIcon = CreateImageIcon(""/icons/clear.png""); nuclearIcon = CreateImageIcon(""/icons/nuclear.png""); treeIcon = CreateImageIcon(""/icons/tree.png""); processingIcon = CreateImageIcon(""/icons/processing.png""); saveIcon = CreateImageIcon(""/icons/save.png""); errorIcon = CreateImageIcon(""/icons/error.png""); locationsIcon = CreateImageIcon(""/icons/locations.png""); loadIcon = CreateImageIcon(""/icons/locations.png""); doneIcon = CreateImageIcon(""/icons/check.png""); logIcon = CreateImageIcon(""/icons/log.png""); timeSlicesIcon = CreateImageIcon(""/icons/timeSlices.png""); treesIcon = CreateImageIcon(""/icons/trees.png""); // Setup Main Frame frame = new JFrame(""SPREAD""); frame.getContentPane().setLayout(new BorderLayout()); frame.addWindowListener(new ListenCloseWdw()); frame.setIconImage(CreateImage(""/icons/spread.png"")); // Setup Main Menu buttons help = new JButton(""Help"", helpIcon); quit = new JButton(""Quit"", quitIcon); clear = new JButton(""Clear Terminal"", clearIcon); // Add Main Menu buttons listeners quit.addActionListener(new ListenMenuQuit()); help.addActionListener(new ListenMenuHelp()); clear.addActionListener(new ListenMenuClearTerminal()); // Setup Main Menu mainMenu = new JToolBar(); mainMenu.setFloatable(false); mainMenu.setLayout(new BorderLayout()); JPanel buttonsHolder = new JPanel(); buttonsHolder.setOpaque(false); buttonsHolder.add(clear); buttonsHolder.add(help); buttonsHolder.add(quit); mainMenu.add(buttonsHolder, BorderLayout.EAST); // Setup Tabbed Pane tabbedPane = new JTabbedPane(); // add Discrete Model Tab discreteModelTab = new DiscreteModelTab(this); tabbedPane.add(""Discrete Tree"", discreteModelTab); // add rateIndicatorBF Tab rateIndicatorBFTab = new RateIndicatorBFTab(this); tabbedPane.add(""Discrete Bayes Factors"", rateIndicatorBFTab); // add Continuous Model Tab continuousModelTab = new ContinuousModelTab(this); tabbedPane.add(""Continuous Tree"", continuousModelTab); // add Time Slicer tab timeSlicerTab = new TimeSlicerTab(this); tabbedPane.add(""Time Slicer"", timeSlicerTab); // add Terminal Tab terminalTab = new TerminalTab(); tabbedPane.add(""Terminal"", terminalTab); // Setup status bar JPanel statusPanel = new JPanel(); statusPanel.setBorder(new BevelBorder(BevelBorder.LOWERED)); statusPanel.setPreferredSize(new Dimension(frame.getWidth(), 16)); statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS)); statusbar = new JLabel(""Welcome to Spread!""); statusbar.setHorizontalAlignment(SwingConstants.LEFT); statusPanel.add(statusbar); frame.getContentPane().add(mainMenu, BorderLayout.NORTH); frame.getContentPane().add(tabbedPane, BorderLayout.CENTER); frame.getContentPane().add(statusPanel, BorderLayout.SOUTH); // frame.getContentPane().add(Box.createVerticalStrut(15), // BorderLayout.SOUTH); frame.pack(); }// END: Constructor private class ListenMenuHelp implements ActionListener { public void actionPerformed(ActionEvent ev) { String helpText = ""\n"" + ""\t SPREAD \n"" + ""Spatial Phylogenetic Reconstruction of Evolutionary Dynamics \n"" + "" \t Version "" + VERSION + "", "" + DATE_STRING + ""\n"" + ""Filip Bielejec, Andrew Rambaut, Marc A. Suchard & Philippe Lemey \n"" + ""\n"" + ""SPREAD: www.phylogeography.org/SPREAD \n"" + ""BEAST software: http://beast.bio.ed.ac.uk/Main_Page \n"" + ""PROCESSING libraries: http://processing.org/ \n"" + ""\n"" + ""Citing SPREAD: \n"" + ""Bielejec F., Rambaut A., Suchard M.A & Lemey P. SPREAD: Spatial Phylogenetic Reconstruction of Evolutionary Dynamics. Bioinformatics, 2011. doi:10.1093 \n"" // + ""\n"" + ""BibTeX entry: \n"" + ""@article{Bielejec11092011, \n"" + ""\t author = {Bielejec, Filip and Rambaut, Andrew and Suchard, Marc A. and Lemey, Philippe}, \n"" + ""\t title = {SPREAD: Spatial phylogenetic reconstruction of evolutionary dynamics}, \n"" + ""\t year = {2011}, \n"" + ""\t volume = {27}, \n"" + ""\t pages = {2910-2912}, \n"" + ""\t doi = {10.1093/bioinformatics/btr481}, \n"" + ""\t URL = {http://bioinformatics.oxfordjournals.org/content/27/20/2910.abstract}, \n"" + ""\t eprint = {http://bioinformatics.oxfordjournals.org/content/27/20/2910.full.pdf+html}, \n"" + ""\t journal = {Bioinformatics} \n"" + ""} \n""; terminalTab.setText(helpText); tabbedPane.setSelectedIndex(4); } } private class ListenMenuClearTerminal implements ActionListener { public void actionPerformed(ActionEvent ev) { terminalTab.clearTerminal(); } } public class ListenMenuQuit implements ActionListener { public void actionPerformed(ActionEvent ev) { System.exit(0); } } public class ListenCloseWdw extends WindowAdapter { public void windowClosing(WindowEvent ev) { System.exit(0); } } public JFrame launchFrame() { // Display Frame frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(new Dimension(dimension.width - 100, dimension.height - 100)); frame.setMinimumSize(new Dimension(260, 100)); frame.setResizable(true); frame.setVisible(true); return frame; } public static SpreadApp gui; public static void main(String args[]) { Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler()); // Start application's GUI from Event Dispatching Thread SwingUtilities.invokeLater(new Runnable() { public void run() { try { gui = new SpreadApp(); gui.launchFrame(); } catch (UnsupportedClassVersionError e) { System.err.println(""Your Java Runtime Environment is too old. Please update!""); e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (UnsupportedLookAndFeelException e) { e.printStackTrace(); } } }); }// END: main private ImageIcon CreateImageIcon(String path) { URL imgURL = this.getClass().getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println(""Couldn't find file: "" + path + ""\n""); return null; } }// END: CreateImageIcon private Image CreateImage(String path) { URL imgURL = this.getClass().getResource(path); Toolkit kit = Toolkit.getDefaultToolkit(); Image img = kit.createImage(imgURL); if (img != null) { return img; } else { System.err.println(""Couldn't find file: "" + path + ""\n""); return null; } }// END: CreateImage public void setStatus(String status) { statusbar.setText(status); }// END: setStatus }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/generator/KMLGenerator.java",".java","8611","303","package generator; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Locale; import kmlframework.kml.AltitudeModeEnum; import kmlframework.kml.Document; import kmlframework.kml.Feature; import kmlframework.kml.Folder; import kmlframework.kml.Kml; import kmlframework.kml.KmlException; import kmlframework.kml.LineString; import kmlframework.kml.LineStyle; import kmlframework.kml.LinearRing; import kmlframework.kml.Placemark; import kmlframework.kml.Point; import kmlframework.kml.PolyStyle; import kmlframework.kml.StyleSelector; import kmlframework.kml.TimePrimitive; import kmlframework.kml.TimeSpan; import structure.Container; import structure.Coordinates; import structure.Item; import structure.Layer; import structure.Line; import structure.Place; import structure.Polygon; import structure.Style; import structure.TimeLine; import utils.GeoIntermediate; import utils.Utils; public class KMLGenerator implements Generator { private List styles = new ArrayList(); private TimeLine timeLine; private SimpleDateFormat formatter = new SimpleDateFormat(""yyyy-MM-dd"", Locale.US); private Document document = new Document(); private GeoIntermediate rhumbIntermediate; // 01-01-01 in millis before 1970-01-01 private static final double YearZeroInMillis = -62135773200000.0; public KMLGenerator() { } public void generate(PrintWriter writer, final TimeLine timeLine, final Collection layers) throws IOException { this.timeLine = timeLine; // We create a new KML Document Kml kml = new Kml(); kml.setXmlIndent(true); kml.setGenerateObjectIds(false); // We add a document to the kml kml.setFeature(document); for (Layer layer : layers) { document.addFeature(generateLayer(layer)); } // We generate the kml file try { kml.createKml(writer); } catch (KmlException e) { e.printStackTrace(); } } private Feature generateLayer(final Layer layer) { Folder folder = new Folder(); folder.setName(layer.getName()); folder.setDescription(layer.getDescription()); generateContent(folder, layer); return folder; } private Feature generateContent(final Folder folder, final Container container) { for (Item item : container.getItems()) { folder.addFeature(generateItem(item)); } return null; } private Feature generateItem(final Item item) { if (item instanceof Line) { return generateLine((Line) item); } else if (item instanceof Polygon) { return generatePolygon((Polygon) item); } else if (item instanceof Place) { return generatePlacemark((Place) item); } throw new IllegalArgumentException(""unknown item type""); } private Feature generatePolygon(final Polygon polygon) { Placemark placemark = new Placemark(polygon.getName()); double startTime = polygon.getStartTime(); double duration = polygon.getDuration(); // Style Style style = polygon.getPolyStyle(); PolyStyle polyStyle = new PolyStyle(); polyStyle.setOutline(false); polyStyle.setColor(Utils.getKMLColor(style.getStrokeColor())); style.setPolyStyle(polyStyle); styles.add(style); placemark.setStyleUrl(style.getId()); document.setStyleSelectors(styles); // Time // Parse minus if date is BC placemark.setTimePrimitive(new TimeSpan( startTime < YearZeroInMillis ? ""-"" + formatter.format(startTime) : formatter .format(startTime), duration > 0.0 ? (startTime + duration < YearZeroInMillis ? ""-"" + formatter.format(startTime + duration) : formatter .format(startTime + duration)) : """")); // Polygon OuterBoundaryIs LinearRing LinearRing linearRing = new LinearRing(); // linearRing.setCoordinates(); linearRing.setCoordinates(Utils.convertToPoint(polygon .getPolyCoordinates())); kmlframework.kml.Polygon localPolygon = new kmlframework.kml.Polygon(); localPolygon.setTessellate(true); localPolygon.setOuterBoundary(linearRing); placemark.setGeometry(localPolygon); return placemark; } private Feature generateLine(final Line line) { Feature feature; if (line.getEndStyle() == null || line.getStartStyle().equals(line.getEndStyle())) { double startTime = line.getStartTime(); double endTime = line.getEndTime(); double duration = line.getDuration(); double maxAltitude = line.getMaxAltitude(); double timeRange = endTime - startTime; if (timeLine.isInstantaneous() || timeRange == 0.0) { feature = generateLineSegment(line.getStartLocation(), line .getEndLocation(), startTime, duration, line .getStartStyle()); } else { Folder folder = new Folder(); // Parse start and end point coordinates double startLon = line.getStartLocation().getLongitude(); double startLat = line.getStartLocation().getLatitude(); double endLon = line.getEndLocation().getLongitude(); double endLat = line.getEndLocation().getLatitude(); int sliceCount = timeLine.getSliceCount(); rhumbIntermediate = new GeoIntermediate(startLon, startLat, endLon, endLat, sliceCount); double coords[][] = rhumbIntermediate.getCoords(); // Utils.print2DArray(coords); double a = -2 * maxAltitude / (Math.pow(sliceCount, 2) - sliceCount); double b = 2 * maxAltitude / (sliceCount - 1); for (int i = 0; i < sliceCount; i++) { double startAltitude = a * Math.pow((double) i, 2) + b * (double) i; double endAltitude = a * Math.pow((double) (i + 1), 2) + b * (double) (i + 1); double segmentStartTime = endTime - (i + 1) * ((endTime - startTime) / sliceCount); //TODO // System.out.println(startTime < YearZeroInMillis ? ""-"" // + formatter.format(startTime) : formatter // .format(startTime)); Placemark lineSegment = generateLineSegment( new Coordinates(coords[i][0], coords[i][1], startAltitude),// startCoordinates new Coordinates(coords[i + 1][0], coords[i + 1][1], endAltitude),// endCoordinates segmentStartTime,// startTime duration,// duration line.getStartStyle()// Style ); folder.addFeature(lineSegment); } feature = folder; } } else { Folder folder = new Folder(); // for (int i = 0; i < divisionCount; i++) { // Placemark lineSegment = generateLineSegment(loc1, loc2, time, // duration, style); // folder.addFeature(lineSegment); // } feature = folder; } feature.setName(line.getName()); return feature; } private Placemark generateLineSegment(Coordinates startCoordinates, Coordinates endCoordinates, double startTime, double duration, Style style) { LineStyle lineStyle = new LineStyle(); lineStyle.setColor(Utils.getKMLColor(style.getStrokeColor())); lineStyle.setWidth(style.getStrokeWidth()); style.setLineStyle(lineStyle); styles.add(style); document.setStyleSelectors(styles); LineString lineString = new LineString(); lineString.setTessellate(true); lineString.setAltitudeMode(AltitudeModeEnum.relativeToGround); List points = new ArrayList(); points.add(generatePoint(startCoordinates)); points.add(generatePoint(endCoordinates)); lineString.setCoordinates(points); Placemark placemark = new Placemark(); if (!Double.isNaN(duration)) { // Parse minus if date is BC TimePrimitive timePrimitive = new TimeSpan( startTime < YearZeroInMillis ? ""-"" + formatter.format(startTime) : formatter .format(startTime), duration > 0.0 ? (startTime + duration < YearZeroInMillis ? ""-"" + formatter.format(startTime + duration) : formatter.format(startTime + duration)) : """"); // System.out.println(formatter.format(startTime + duration)); placemark.setTimePrimitive(timePrimitive); } placemark.setStyleUrl(style.getId()); placemark.setGeometry(lineString); return placemark; } private Placemark generatePlacemark(final Place place) { Placemark placemark = new Placemark(); placemark.setGeometry(generatePoint(place.getCoordinates())); placemark.setName(place.getName()); return placemark; } private Point generatePoint(final Coordinates coordinates) { Point point = new Point(); point.setAltitudeMode(AltitudeModeEnum.relativeToGround); point.setAltitude(coordinates.getAltitude()); point.setLongitude(coordinates.getLongitude()); point.setLatitude(coordinates.getLatitude()); return point; } @Override public String toString() { return ""KML""; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/generator/Generator.java",".java","362","18","package generator; import java.io.IOException; import java.io.PrintWriter; import java.util.Collection; import structure.Layer; import structure.TimeLine; /** * @author Andrew Rambaut * @version $Id$ */ public interface Generator { public void generate(PrintWriter writer, final TimeLine timeLine, final Collection layers) throws IOException; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/util/JVM.java",".java","4247","114","/* * @(#)JVM.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.util; import java.security.AccessControlException; /** Static methods relating to the JVM environment. *

Instead of burying a constant like ""isQuartz"" in its most * relevant class (such as OptimizedGraphics2D), it should be * stored here so if other classes need to access it they don't * necessary have to */ public class JVM { /** Prints basic information about this session's JVM: * the OS name & version, the Java version, and (on Mac) whether Quartz is being used. */ public static void printProfile() { System.out.println(getProfile()); } /** Gets basic information about this session's JVM: * the OS name & version, the Java version, and (on Mac) whether Quartz is being used. */ public static String getProfile() { StringBuffer sb = new StringBuffer(); sb.append(""OS = ""+System.getProperty(""os.name"")+"" (""+System.getProperty(""os.version"")+""), ""+System.getProperty(""os.arch"")+""\n""); sb.append(""Java Version = ""+System.getProperty(""java.version"")+""\n""); if(JVM.isMac) { sb.append(""apple.awt.graphics.UseQuartz = ""+usingQuartz); } return sb.toString(); } /** The major Java version being used (1.4, 1.5, 1.6, etc.), or * -1 if this value couldn't be correctly determined. */ public static final float javaVersion = JVM.getMajorJavaVersion(true); /** Whether this session is on a Mac. */ public static final boolean isMac = (System.getProperty(""os.name"").toLowerCase().indexOf(""mac"")!=-1); /** Whether this session is on Windows. */ public static final boolean isWindows = (System.getProperty(""os.name"").toLowerCase().indexOf(""windows"")!=-1); /** Whether this session is on Vista. */ public static final boolean isVista = (System.getProperty(""os.name"").toLowerCase().indexOf(""vista"")!=-1); /** If on a Mac: whether Quartz is the rendering pipeline. */ public static final boolean usingQuartz = isMac && ((javaVersion>0 && javaVersion<1.4f) || (System.getProperty(""apple.awt.graphics.UseQuartz"")!=null && System.getProperty(""apple.awt.graphics.UseQuartz"").toString().equals(""true""))); /** This converts the system property ""java.version"" to a float value. * This drops rightmost digits until a legitimate float can be parsed. *
For example, this converts ""1.6.0_05"" to ""1.6"". *
This value is cached as the system property ""java.major.version"". Although * technically this value is a String, it will always be parseable as a float. * @throws AccessControlException this may be thrown in unsigned applets! Beware! */ public static float getMajorJavaVersion() throws AccessControlException { String majorVersion = System.getProperty(""java.major.version""); if(majorVersion==null) { String s = System.getProperty(""java.version""); float f = -1; int i = s.length(); while(f<0 && i>0) { try { f = Float.parseFloat(s.substring(0,i)); } catch(Exception e) {} i--; } majorVersion = Float.toString(f); System.setProperty(""java.major.version"",majorVersion); } return Float.parseFloat(majorVersion); } /** * * @param catchSecurityException if true and an exception occurs, * then -1 is returned. * @return the major java version, or -1 if this can't be determined/ */ public static float getMajorJavaVersion(boolean catchSecurityException) { try { return getMajorJavaVersion(); } catch(RuntimeException t) { if(catchSecurityException) { System.err.println(""this exception was ignored without incident, but it means we can't determine the major java version:""); t.printStackTrace(); return -1; } throw t; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/swing/ColorPicker.java",".java","34939","1011","/* * @(#)ColorPicker.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.swing; import java.awt.Color; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ResourceBundle; import javax.swing.ButtonGroup; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SwingUtilities; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import colorpicker.plaf.ColorPickerSliderUI; /** This is a panel that offers a robust set of controls to pick a color. *

This was originally intended to replace the JColorChooser. * To use this class to create a color choosing dialog, simply call: *
ColorPicker.showDialog(frame, originalColor); *

However this panel is also resizable, and it can exist in other contexts. * For example, you might try the following panel: *
ColorPicker picker = new ColorPicker(false, false); *
picker.setPreferredSize(new Dimension(200,160)); *
picker.setMode(ColorPicker.HUE); *

This will create a miniature color picker that still lets the user choose * from every available color, but it does not include all the buttons and * numeric controls on the right side of the panel. This might be ideal if you * are working with limited space, or non-power-users who don't need the * RGB values of a color. The main() method of this class demonstrates * possible ways you can customize a ColorPicker component. *

To listen to color changes to this panel, you can add a PropertyChangeListener * listening for changes to the SELECTED_COLOR_PROPERTY. This will be triggered only * when the RGB value of the selected color changes. *

To listen to opacity changes to this panel, use a PropertyChangeListener listening * for changes to the OPACITY_PROPERTY. * */ public class ColorPicker extends JPanel { private static final long serialVersionUID = 3L; /** The localized strings used in this (and related) panel(s). */ protected static ResourceBundle strings = ResourceBundle.getBundle(""colorpicker.swing.resources.ColorPicker""); /** This creates a modal dialog prompting the user to select a color. *

This uses a generic dialog title: ""Choose a Color"", and does not include opacity. * * @param owner the dialog this new dialog belongs to. This must be a Frame or a Dialog. * Java 1.6 supports Windows here, but this package is designed/compiled to work in Java 1.4, * so an IllegalArgumentException will be thrown if this component is a Window. * @param originalColor the color the ColorPicker initially points to. * @return the Color the user chooses, or null if the user cancels the dialog. */ public static Color showDialog(Window owner,Color originalColor) { return showDialog(owner, null, originalColor, false ); } /** This creates a modal dialog prompting the user to select a color. *

This uses a generic dialog title: ""Choose a Color"". * * @param owner the dialog this new dialog belongs to. This must be a Frame or a Dialog. * Java 1.6 supports Windows here, but this package is designed/compiled to work in Java 1.4, * so an IllegalArgumentException will be thrown if this component is a Window. * @param originalColor the color the ColorPicker initially points to. * @param includeOpacity whether to add a control for the opacity of the color. * @return the Color the user chooses, or null if the user cancels the dialog. */ public static Color showDialog(Window owner,Color originalColor,boolean includeOpacity) { return showDialog(owner, null, originalColor, includeOpacity ); } /** This creates a modal dialog prompting the user to select a color. * * @param owner the dialog this new dialog belongs to. This must be a Frame or a Dialog. * Java 1.6 supports Windows here, but this package is designed/compiled to work in Java 1.4, * so an IllegalArgumentException will be thrown if this component is a Window. * @param title the title for the dialog. * @param originalColor the color the ColorPicker initially points to. * @param includeOpacity whether to add a control for the opacity of the color. * @return the Color the user chooses, or null if the user cancels the dialog. */ public static Color showDialog(Window owner, String title,Color originalColor,boolean includeOpacity) { ColorPickerDialog d; if(owner instanceof Frame || owner==null) { d = new ColorPickerDialog( (Frame)owner, originalColor, includeOpacity); } else if(owner instanceof Dialog){ d = new ColorPickerDialog( (Dialog)owner, originalColor, includeOpacity); } else { throw new IllegalArgumentException(""the owner (""+owner.getClass().getName()+"") must be a java.awt.Frame or a java.awt.Dialog""); } d.setTitle(title == null ? strings.getObject(""ColorPickerDialogTitle"").toString() : title); d.pack(); d.setVisible(true); return d.getColor(); } /** PropertyChangeEvents will be triggered for this property when the selected color * changes. *

(Events are only created when then RGB values of the color change. This means, for example, * that the change from HSB(0,0,0) to HSB(.4,0,0) will not generate events, because when the * brightness stays zero the RGB color remains (0,0,0). So although the hue moved around, the color * is still black, so no events are created.) * */ public static final String SELECTED_COLOR_PROPERTY = ""selected color""; /** PropertyChangeEvents will be triggered for this property when setModeControlsVisible() * is called. */ public static final String MODE_CONTROLS_VISIBLE_PROPERTY = ""mode controls visible""; /** PropertyChangeEvents will be triggered when the opacity value is * adjusted. */ public static final String OPACITY_PROPERTY = ""opacity""; /** PropertyChangeEvents will be triggered when the mode changes. * (That is, when the wheel switches from HUE, SAT, BRI, RED, GREEN, or BLUE modes.) */ public static final String MODE_PROPERTY = ""mode""; /** Used to indicate when we're in ""hue mode"". */ public static final int HUE = 0; /** Used to indicate when we're in ""brightness mode"". */ public static final int BRI = 1; /** Used to indicate when we're in ""saturation mode"". */ public static final int SAT = 2; /** Used to indicate when we're in ""red mode"". */ public static final int RED = 3; /** Used to indicate when we're in ""green mode"". */ public static final int GREEN = 4; /** Used to indicate when we're in ""blue mode"". */ public static final int BLUE = 5; /** The vertical slider */ private JSlider slider = new JSlider(JSlider.VERTICAL,0,100,0); private int currentRed = 0; private int currentGreen = 0; private int currentBlue = 0; ChangeListener changeListener = new ChangeListener() { public void stateChanged(ChangeEvent e) { Object src = e.getSource(); if(hue.contains(src) || sat.contains(src) || bri.contains(src)) { if(adjustingSpinners>0) return; setHSB( hue.getFloatValue()/360f, sat.getFloatValue()/100f, bri.getFloatValue()/100f ); } else if(red.contains(src) || green.contains(src) || blue.contains(src)) { if(adjustingSpinners>0) return; setRGB( red.getIntValue(), green.getIntValue(), blue.getIntValue() ); } else if(src==colorPanel) { if(adjustingColorPanel>0) return; int mode = getMode(); if(mode==HUE || mode==BRI || mode==SAT) { float[] hsb = colorPanel.getHSB(); setHSB(hsb[0],hsb[1],hsb[2]); } else { int[] rgb = colorPanel.getRGB(); setRGB(rgb[0],rgb[1],rgb[2]); } } else if(src==slider) { if(adjustingSlider>0) return; int v = slider.getValue(); Option option = getSelectedOption(); option.setValue(v); } else if(alpha.contains(src)) { if(adjustingOpacity>0) return; int v = alpha.getIntValue(); setOpacity( v ); } else if(src==opacitySlider) { if(adjustingOpacity>0) return; setOpacity( opacitySlider.getValue() ); } } }; ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src==hue.radioButton) { setMode(HUE); } else if(src==bri.radioButton) { setMode(BRI); } else if(src==sat.radioButton) { setMode(SAT); } else if(src==red.radioButton) { setMode(RED); } else if(src==green.radioButton) { setMode(GREEN); } else if(src==blue.radioButton) { setMode(BLUE); } } }; /** @return the currently selected Option */ private Option getSelectedOption() { int mode = getMode(); if(mode==HUE) { return hue; } else if(mode==SAT) { return sat; } else if(mode==BRI) { return bri; } else if(mode==RED) { return red; } else if(mode==GREEN) { return green; } else { return blue; } } /** This thread will wait a second or two before committing the text in * the hex TextField. This gives the user a chance to finish typing... * but if the user is just waiting for something to happen, this makes sure * after a second or two something happens. */ class HexUpdateThread extends Thread { long myStamp; String text; public HexUpdateThread(long stamp,String s) { myStamp = stamp; text = s; } public void run() { if(SwingUtilities.isEventDispatchThread()==false) { long WAIT = 1500; while(System.currentTimeMillis()-myStamp6) text = text.substring(0,6); while(text.length()<6) { text = text+""0""; } if(hexField.getText().equals(text)) return; int pos = hexField.getCaretPosition(); hexField.setText(text); hexField.setCaretPosition(pos); } } HexDocumentListener hexDocListener = new HexDocumentListener(); class HexDocumentListener implements DocumentListener { long lastTimeStamp; public void changedUpdate(DocumentEvent e) { lastTimeStamp = System.currentTimeMillis(); if(adjustingHexField>0) return; String s = hexField.getText(); s = stripToHex(s); if(s.length()==6) { //the user typed 6 digits: we can work with this: try { int i = Integer.parseInt(s,16); setRGB( ((i >> 16) & 0xff), ((i >> 8) & 0xff), ((i) & 0xff) ); return; } catch(NumberFormatException e2) { //this shouldn't happen, since we already stripped out non-hex characters. e2.printStackTrace(); } } Thread thread = new HexUpdateThread(lastTimeStamp,s); thread.start(); while(System.currentTimeMillis()-lastTimeStamp==0) { Thread.yield(); } } /** Strips a string down to only uppercase hex-supported characters. */ private String stripToHex(String s) { s = s.toUpperCase(); String s2 = """"; for(int a = 0; aColorPicker with all controls visible except opacity. */ public ColorPicker() { this(true,false); } /** Create a new ColorPicker. * * @param showExpertControls the labels/spinners/buttons on the right side of a * ColorPicker are optional. This boolean will control whether they * are shown or not. *

It may be that your users will never need or want numeric control when * they choose their colors, so hiding this may simplify your interface. * @param includeOpacity whether the opacity controls will be shown */ public ColorPicker(boolean showExpertControls,boolean includeOpacity) { super(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); Insets normalInsets = new Insets(3,3,3,3); JPanel options = new JPanel(new GridBagLayout()); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.insets = normalInsets; ButtonGroup bg = new ButtonGroup(); //put them in order Option[] optionsArray = new Option[] { hue, sat, bri, red, green, blue }; for(int a = 0; aNote this lives inside the ""expert controls"", so if setExpertControlsVisible(false) * has been called, then calling this method makes no difference: the hex controls will be hidden. */ public void setHexControlsVisible(boolean b) { hexLabel.setVisible(b); hexField.setVisible(b); } /** This controls whether the preview swatch visible or not. *

Note this lives inside the ""expert controls"", so if setExpertControlsVisible(false) * has been called, then calling this method makes no difference: the swatch will be hidden. */ public void setPreviewSwatchVisible(boolean b) { preview.setVisible(b); } /** The labels/spinners/buttons on the right side of a ColorPicker * are optional. This method will control whether they are shown or not. *

It may be that your users will never need or want numeric control when * they choose their colors, so hiding this may simplify your interface. * * @param b whether to show or hide the expert controls. */ public void setExpertControlsVisible(boolean b) { expertControls.setVisible(b); } /** @return the current HSB coordinates of this ColorPicker. * Each value is between [0,1]. * */ public float[] getHSB() { return new float[] { hue.getFloatValue()/360f, sat.getFloatValue()/100f, bri.getFloatValue()/100f }; } /** @return the current RGB coordinates of this ColorPicker. * Each value is between [0,255]. * */ public int[] getRGB() { return new int[] { currentRed, currentGreen, currentBlue }; } /** Returns the currently selected opacity (a float between 0 and 1). * * @return the currently selected opacity (a float between 0 and 1). */ public float getOpacity() { return ((float)opacitySlider.getValue())/255f; } private int lastOpacity = 255; /** Sets the currently selected opacity. * * @param v an int between 0 and 255. */ public void setOpacity(int v) { if(v<0 || v>255) throw new IllegalArgumentException(""The opacity (""+v+"") must be between 0 and 255.""); adjustingOpacity++; try { opacitySlider.setValue( v ); alpha.spinner.setValue( new Integer(v) ); if(lastOpacity!=v) { firePropertyChange(OPACITY_PROPERTY,new Integer(lastOpacity),new Integer(v)); Color c = preview.getForeground(); preview.setForeground(new Color(c.getRed(), c.getGreen(), c.getBlue(), v)); } lastOpacity = v; } finally { adjustingOpacity--; } } /** Sets the mode of this ColorPicker. * This is especially useful if this picker is in non-expert mode, so * the radio buttons are not visible for the user to directly select. * * @param mode must be HUE, SAT, BRI, RED, GREEN or BLUE. */ public void setMode(int mode) { if(!(mode==HUE || mode==SAT || mode==BRI || mode==RED || mode==GREEN || mode==BLUE)) throw new IllegalArgumentException(""mode must be HUE, SAT, BRI, REd, GREEN, or BLUE""); putClientProperty(MODE_PROPERTY,new Integer(mode)); hue.radioButton.setSelected(mode==HUE); sat.radioButton.setSelected(mode==SAT); bri.radioButton.setSelected(mode==BRI); red.radioButton.setSelected(mode==RED); green.radioButton.setSelected(mode==GREEN); blue.radioButton.setSelected(mode==BLUE); colorPanel.setMode(mode); adjustingSlider++; try { slider.setValue(0); Option option = getSelectedOption(); slider.setInverted(mode==HUE); int max = option.getMaximum(); slider.setMaximum(max); slider.setValue( option.getIntValue() ); slider.repaint(); if(mode==HUE || mode==SAT || mode==BRI) { setHSB( hue.getFloatValue()/360f, sat.getFloatValue()/100f, bri.getFloatValue()/100f ); } else { setRGB( red.getIntValue(), green.getIntValue(), blue.getIntValue() ); } } finally { adjustingSlider--; } } /** This controls whether the radio buttons that adjust the mode are visible. *

(These buttons appear next to the spinners in the expert controls.) *

Note these live inside the ""expert controls"", so if setExpertControlsVisible(false) * has been called, then these will never be visible. * * @param b */ public void setModeControlsVisible(boolean b) { hue.radioButton.setVisible(b && hue.isVisible()); sat.radioButton.setVisible(b && sat.isVisible()); bri.radioButton.setVisible(b && bri.isVisible()); red.radioButton.setVisible(b && red.isVisible()); green.radioButton.setVisible(b && green.isVisible()); blue.radioButton.setVisible(b && blue.isVisible()); putClientProperty(MODE_CONTROLS_VISIBLE_PROPERTY,new Boolean(b)); } /** @return the current mode of this ColorPicker. *
This will return HUE, SAT, BRI, * RED, GREEN, or BLUE. *

The default mode is BRI, because that provides the most * aesthetic/recognizable color wheel. */ public int getMode() { Integer i = (Integer)getClientProperty(MODE_PROPERTY); if(i==null) return -1; return i.intValue(); } /** Sets the current color of this ColorPicker. * This method simply calls setRGB() and setOpacity(). * @param c the new color to use. */ public void setColor(Color c) { setRGB(c.getRed(),c.getGreen(),c.getBlue()); setOpacity(c.getAlpha()); } /** Sets the current color of this ColorPicker * * @param r the red value. Must be between [0,255]. * @param g the green value. Must be between [0,255]. * @param b the blue value. Must be between [0,255]. */ public void setRGB(int r,int g,int b) { if(r<0 || r>255) throw new IllegalArgumentException(""The red value (""+r+"") must be between [0,255].""); if(g<0 || g>255) throw new IllegalArgumentException(""The green value (""+g+"") must be between [0,255].""); if(b<0 || b>255) throw new IllegalArgumentException(""The blue value (""+b+"") must be between [0,255].""); Color lastColor = getColor(); boolean updateRGBSpinners = adjustingSpinners==0; adjustingSpinners++; adjustingColorPanel++; int alpha = this.alpha.getIntValue(); try { if(updateRGBSpinners) { red.setValue(r); green.setValue(g); blue.setValue(b); } preview.setForeground(new Color(r,g,b, alpha)); float[] hsb = new float[3]; Color.RGBtoHSB(r, g, b, hsb); hue.setValue( (int)(hsb[0]*360f+.49f)); sat.setValue( (int)(hsb[1]*100f+.49f)); bri.setValue( (int)(hsb[2]*100f+.49f)); colorPanel.setRGB(r, g, b); updateHexField(); updateSlider(); } finally { adjustingSpinners--; adjustingColorPanel--; } currentRed = r; currentGreen = g; currentBlue = b; Color newColor = getColor(); if(lastColor.equals(newColor)==false) firePropertyChange(SELECTED_COLOR_PROPERTY,lastColor,newColor); } /** @return the current Color this ColorPicker has selected. *

This is equivalent to: *
int[] i = getRGB(); *
return new Color(i[0], i[1], i[2], opacitySlider.getValue()); */ public Color getColor() { int[] i = getRGB(); return new Color(i[0], i[1], i[2], opacitySlider.getValue()); } private void updateSlider() { adjustingSlider++; try { int mode = getMode(); if(mode==HUE) { slider.setValue( hue.getIntValue() ); } else if(mode==SAT) { slider.setValue( sat.getIntValue() ); } else if(mode==BRI) { slider.setValue( bri.getIntValue() ); } else if(mode==RED) { slider.setValue( red.getIntValue() ); } else if(mode==GREEN) { slider.setValue( green.getIntValue() ); } else if(mode==BLUE) { slider.setValue( blue.getIntValue() ); } } finally { adjustingSlider--; } slider.repaint(); } /** This returns the panel with several rows of spinner controls. *

Note you can also call methods such as setRGBControlsVisible() to adjust * which controls are showing. *

(This returns the panel this ColorPicker uses, so if you put it in * another container, it will be removed from this ColorPicker.) * @return the panel with several rows of spinner controls. */ public JPanel getExpertControls() { return expertControls; } /** This shows or hides the RGB spinner controls. *

Note these live inside the ""expert controls"", so if setExpertControlsVisible(false) * has been called, then calling this method makes no difference: the RGB controls will be hidden. * * @param b whether the controls should be visible or not. */ public void setRGBControlsVisible(boolean b) { red.setVisible(b); green.setVisible(b); blue.setVisible(b); } /** This shows or hides the HSB spinner controls. *

Note these live inside the ""expert controls"", so if setExpertControlsVisible(false) * has been called, then calling this method makes no difference: the HSB controls will be hidden. * * @param b whether the controls should be visible or not. */ public void setHSBControlsVisible(boolean b) { hue.setVisible(b); sat.setVisible(b); bri.setVisible(b); } /** This shows or hides the alpha controls. *

Note the alpha spinner live inside the ""expert controls"", so if setExpertControlsVisible(false) * has been called, then this method does not affect that spinner. * However, the opacity slider is not affected by the visibility of the export controls. * @param b */ public void setOpacityVisible(boolean b) { opacityLabel.setVisible(b); opacitySlider.setVisible(b); alpha.label.setVisible(b); alpha.spinner.setVisible(b); } /** @return the ColorPickerPanel this ColorPicker displays. */ public ColorPickerPanel getColorPanel() { return colorPanel; } /** Sets the current color of this ColorPicker * * @param h the hue value. * @param s the saturation value. Must be between [0,1]. * @param b the blue value. Must be between [0,1]. */ public void setHSB(float h, float s, float b) { if(Float.isInfinite(h) || Float.isNaN(h)) throw new IllegalArgumentException(""The hue value (""+h+"") is not a valid number.""); //hue is cyclic, so it can be any value: while(h<0) h++; while(h>1) h--; if(s<0 || s>1) throw new IllegalArgumentException(""The saturation value (""+s+"") must be between [0,1]""); if(b<0 || b>1) throw new IllegalArgumentException(""The brightness value (""+b+"") must be between [0,1]""); Color lastColor = getColor(); boolean updateHSBSpinners = adjustingSpinners==0; adjustingSpinners++; adjustingColorPanel++; try { if(updateHSBSpinners) { hue.setValue( (int)(h*360f+.49f)); sat.setValue( (int)(s*100f+.49f)); bri.setValue( (int)(b*100f+.49f)); } Color c = new Color(Color.HSBtoRGB(h, s, b)); int alpha = this.alpha.getIntValue(); c = new Color(c.getRed(), c.getGreen(), c.getBlue(), alpha); preview.setForeground(c); currentRed = c.getRed(); currentGreen = c.getGreen(); currentBlue = c.getBlue(); red.setValue(currentRed); green.setValue(currentGreen); blue.setValue(currentBlue); colorPanel.setHSB(h, s, b); updateHexField(); updateSlider(); slider.repaint(); } finally { adjustingSpinners--; adjustingColorPanel--; } Color newColor = getColor(); if(lastColor.equals(newColor)==false) firePropertyChange(SELECTED_COLOR_PROPERTY,lastColor,newColor); } private void updateHexField() { adjustingHexField++; try { int r = red.getIntValue(); int g = green.getIntValue(); int b = blue.getIntValue(); int i = (r << 16) + (g << 8) +b; String s = Integer.toHexString(i).toUpperCase(); while(s.length()<6) s = ""0""+s; if(hexField.getText().equalsIgnoreCase(s)==false) hexField.setText(s); } finally { adjustingHexField--; } } class Option { JRadioButton radioButton = new JRadioButton(); JSpinner spinner; JSlider slider; JLabel label; public Option(String text,int max) { spinner = new JSpinner(new SpinnerNumberModel(0,0,max,5)); spinner.addChangeListener(changeListener); /*this tries out Tim Boudreaux's new slider UI. * It's a good UI, but I think for the ColorPicker * the numeric controls are more useful. * That is: users who want click-and-drag control to choose * their colors don't need any of these Option objects * at all; only power users who may have specific RGB * values in mind will use these controls: and when they do * limiting them to a slider is unnecessary. * That's my current position... of course it may * not be true in the real world... :) */ //slider = new JSlider(0,max); //slider.addChangeListener(changeListener); //slider.setUI(new org.netbeans.paint.api.components.PopupSliderUI()); label = new JLabel(text); radioButton.addActionListener(actionListener); } public void setValue(int i) { if(slider!=null) { slider.setValue(i); } if(spinner!=null) { spinner.setValue(new Integer(i)); } } public int getMaximum() { if(slider!=null) return slider.getMaximum(); return ((Number) ((SpinnerNumberModel)spinner.getModel()).getMaximum() ).intValue(); } public boolean contains(Object src) { return (src==slider || src==spinner || src==radioButton || src==label); } public float getFloatValue() { return getIntValue(); } public int getIntValue() { if(slider!=null) return slider.getValue(); return ((Number)spinner.getValue()).intValue(); } public boolean isVisible() { return label.isVisible(); } public void setVisible(boolean b) { boolean radioButtonsAllowed = true; Boolean z = (Boolean)getClientProperty(MODE_CONTROLS_VISIBLE_PROPERTY); if(z!=null) radioButtonsAllowed = z.booleanValue(); radioButton.setVisible(b && radioButtonsAllowed); if(slider!=null) slider.setVisible(b); if(spinner!=null) spinner.setVisible(b); label.setVisible(b); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/swing/ColorPickerPanel.java",".java","19150","617","/* * @(#)ColorPickerPanel.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.swing; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Insets; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import java.awt.image.BufferedImage; import java.util.Vector; import javax.swing.JPanel; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MouseInputAdapter; import javax.swing.event.MouseInputListener; import colorpicker.plaf.PlafPaintUtils; /** This is the large graphic element in the ColorPicker * that depicts a wide range of colors. *

This panel can operate in 6 different modes. In each mode a different * property is held constant: hue, saturation, brightness, red, green, or blue. * (Each property is identified with a constant in the ColorPicker class, * such as: ColorPicker.HUE or ColorPicker.GREEN.) *

In saturation and brightness mode, a wheel is used. Although it doesn't * use as many pixels as a square does: it is a very aesthetic model since the hue can * wrap around in a complete circle. (Also, on top of looks, this is how most * people learn to think the color spectrum, so it has that advantage, too). * In all other modes a square is used. *

The user can click in this panel to select a new color. The selected color is * highlighted with a circle drawn around it. Also once this * component has the keyboard focus, the user can use the arrow keys to * traverse the available colors. *

Note this component is public and exists independently of the * ColorPicker class. The only way this class is dependent * on the ColorPicker class is when the constants for the modes * are used. *

The graphic in this panel will be based on either the width or * the height of this component: depending on which is smaller. * */ public class ColorPickerPanel extends JPanel { private static final long serialVersionUID = 1L; /** The maximum size the graphic will be. No matter * how big the panel becomes, the graphic will not exceed * this length. *

(This is enforced because only 1 BufferedImage is used * to render the graphic. This image is created once at a fixed * size and is never replaced.) */ public static final int MAX_SIZE = 325; /** This controls how the colors are displayed. */ private int mode = ColorPicker.BRI; /** The point used to indicate the selected color. */ private Point point = new Point(0,0); private Vector changeListeners = new Vector(); /* Floats from [0,1]. They must be kept distinct, because * when you convert them to RGB coordinates HSB(0,0,0) and HSB (.5,0,0) * and then convert them back to HSB coordinates, the hue always shifts back to zero. */ float hue = -1, sat = -1, bri = -1; int red = -1, green = -1, blue = -1; MouseInputListener mouseListener = new MouseInputAdapter() { public void mousePressed(MouseEvent e) { requestFocus(); Point p = e.getPoint(); if(mode==ColorPicker.BRI || mode==ColorPicker.SAT || mode==ColorPicker.HUE) { float[] hsb = getHSB(p); setHSB(hsb[0], hsb[1], hsb[2]); } else { int[] rgb = getRGB(p); setRGB(rgb[0], rgb[1], rgb[2]); } } public void mouseDragged(MouseEvent e) { mousePressed(e); } }; KeyListener keyListener = new KeyAdapter() { public void keyPressed(KeyEvent e) { int dx = 0; int dy = 0; if(e.getKeyCode()==KeyEvent.VK_LEFT) { dx = -1; } else if(e.getKeyCode()==KeyEvent.VK_RIGHT) { dx = 1; } else if(e.getKeyCode()==KeyEvent.VK_UP) { dy = -1; } else if(e.getKeyCode()==KeyEvent.VK_DOWN) { dy = 1; } int multiplier = 1; if(e.isShiftDown() && e.isAltDown()) { multiplier = 10; } else if(e.isShiftDown() || e.isAltDown()) { multiplier = 5; } if(dx!=0 || dy!=0) { int size = Math.min(MAX_SIZE, Math.min(getWidth()-imagePadding.left-imagePadding.right,getHeight()-imagePadding.top-imagePadding.bottom)); int offsetX = getWidth()/2-size/2; int offsetY = getHeight()/2-size/2; mouseListener.mousePressed(new MouseEvent(ColorPickerPanel.this, MouseEvent.MOUSE_PRESSED, System.currentTimeMillis(), 0, point.x+multiplier*dx+offsetX, point.y+multiplier*dy+offsetY, 1, false )); } } }; FocusListener focusListener = new FocusListener() { public void focusGained(FocusEvent e) { repaint(); } public void focusLost(FocusEvent e) { repaint(); } }; ComponentListener componentListener = new ComponentAdapter() { public void componentResized(ComponentEvent e) { regeneratePoint(); regenerateImage(); } }; BufferedImage image = new BufferedImage(MAX_SIZE, MAX_SIZE, BufferedImage.TYPE_INT_ARGB); /** Creates a new ColorPickerPanel */ public ColorPickerPanel() { setMaximumSize(new Dimension(MAX_SIZE+imagePadding.left+imagePadding.right, MAX_SIZE+imagePadding.top+imagePadding.bottom)); setPreferredSize(new Dimension( (int)(MAX_SIZE*.75), (int)(MAX_SIZE*.75))); setRGB(0,0,0); addMouseListener(mouseListener); addMouseMotionListener(mouseListener); setFocusable(true); addKeyListener(keyListener); addFocusListener(focusListener); setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); addComponentListener(componentListener); } /** This listener will be notified when the current HSB or RGB values * change. */ public void addChangeListener(ChangeListener l) { if(changeListeners.contains(l)) return; changeListeners.add(l); } /** Remove a ChangeListener so it is no longer * notified when the selected color changes. */ public void removeChangeListener(ChangeListener l) { changeListeners.remove(l); } protected void fireChangeListeners() { if(changeListeners==null) return; for(int a = 0; aColorPicker class: * HUE, SAT, BRI, RED, GREEN, or BLUE */ public void setMode(int mode) { if(!(mode==ColorPicker.HUE || mode==ColorPicker.SAT || mode==ColorPicker.BRI || mode==ColorPicker.RED || mode==ColorPicker.GREEN || mode==ColorPicker.BLUE)) throw new IllegalArgumentException(""The mode must be HUE, SAT, BRI, RED, GREEN, or BLUE.""); if(this.mode==mode) return; this.mode = mode; regenerateImage(); regeneratePoint(); } /** Sets the selected color of this panel. *

If this panel is in HUE, SAT, or BRI mode, then * this method converts these values to HSB coordinates * and calls setHSB. *

This method may regenerate the graphic if necessary. * * @param r the red value of the selected color. * @param g the green value of the selected color. * @param b the blue value of the selected color. */ public void setRGB(int r,int g,int b) { if(r<0 || r>255) throw new IllegalArgumentException(""The red value (""+r+"") must be between [0,255].""); if(g<0 || g>255) throw new IllegalArgumentException(""The green value (""+g+"") must be between [0,255].""); if(b<0 || b>255) throw new IllegalArgumentException(""The blue value (""+b+"") must be between [0,255].""); if(red!=r || green!=g || blue!=b) { if(mode==ColorPicker.RED || mode==ColorPicker.GREEN || mode==ColorPicker.BLUE) { int lastR = red; int lastG = green; int lastB = blue; red = r; green = g; blue = b; if(mode==ColorPicker.RED) { if(lastR!=r) { regenerateImage(); } } else if(mode==ColorPicker.GREEN) { if(lastG!=g) { regenerateImage(); } } else if(mode==ColorPicker.BLUE) { if(lastB!=b) { regenerateImage(); } } } else { float[] hsb = new float[3]; Color.RGBtoHSB(r, g, b, hsb); setHSB(hsb[0],hsb[1],hsb[2]); return; } regeneratePoint(); repaint(); fireChangeListeners(); } } /** @return the HSB values of the selected color. * Each value is between [0,1]. */ public float[] getHSB() { return new float[] {hue, sat, bri}; } /** @return the RGB values of the selected color. * Each value is between [0,255]. */ public int[] getRGB() { return new int[] {red, green, blue}; } /** Returns the color at the indicated point in HSB values. * * @param p a point relative to this panel. * @return the HSB values at the point provided. */ public float[] getHSB(Point p) { if(mode==ColorPicker.RED || mode==ColorPicker.GREEN || mode==ColorPicker.BLUE) { int[] rgb = getRGB(p); float[] hsb = Color.RGBtoHSB(rgb[0], rgb[1], rgb[2], null); return hsb; } int size = Math.min(MAX_SIZE, Math.min(getWidth()-imagePadding.left-imagePadding.right,getHeight()-imagePadding.top-imagePadding.bottom)); p.translate(-(getWidth()/2-size/2), -(getHeight()/2-size/2)); if(mode==ColorPicker.BRI || mode==ColorPicker.SAT) { //the two circular views: double radius = ((double)size)/2.0; double x = p.getX()-size/2.0; double y = p.getY()-size/2.0; double r = Math.sqrt(x*x+y*y)/radius; double theta = Math.atan2(y,x)/(Math.PI*2.0); if(r>1) r = 1; if(mode==ColorPicker.BRI) { return new float[] { (float)(theta+.25f), (float)(r), bri}; } else { return new float[] { (float)(theta+.25f), sat, (float)(r) }; } } else { float s = ((float)p.x)/((float)size); float b = ((float)p.y)/((float)size); if(s<0) s = 0; if(s>1) s = 1; if(b<0) b = 0; if(b>1) b = 1; return new float[] {hue, s, b}; } } /** Returns the color at the indicated point in RGB values. * * @param p a point relative to this panel. * @return the RGB values at the point provided. */ public int[] getRGB(Point p) { if(mode==ColorPicker.BRI || mode==ColorPicker.SAT || mode==ColorPicker.HUE) { float[] hsb = getHSB(p); int rgb = Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]); int r = (rgb & 0xff0000) >> 16; int g = (rgb & 0xff00) >> 8; int b = (rgb & 0xff); return new int[] {r, g, b}; } int size = Math.min(MAX_SIZE, Math.min(getWidth()-imagePadding.left-imagePadding.right,getHeight()-imagePadding.top-imagePadding.bottom)); p.translate(-(getWidth()/2-size/2), -(getHeight()/2-size/2)); int x2 = p.x*255/size; int y2 = p.y*255/size; if(x2<0) x2 = 0; if(x2>255) x2 = 255; if(y2<0) y2 = 0; if(y2>255) y2 = 255; if(mode==ColorPicker.RED) { return new int[] {red, x2, y2}; } else if(mode==ColorPicker.GREEN) { return new int[] {x2, green, y2}; } else { return new int[] {x2, y2, blue}; } } /** Sets the selected color of this panel. *

If this panel is in RED, GREEN, or BLUE mode, then * this method converts these values to RGB coordinates * and calls setRGB. *

This method may regenerate the graphic if necessary. * * @param h the hue value of the selected color. * @param s the saturation value of the selected color. * @param b the brightness value of the selected color. */ public void setHSB(float h,float s,float b) { //hue is cyclic: it can be any value h = (float)(h-Math.floor(h)); if(s<0 || s>1) throw new IllegalArgumentException(""The saturation value (""+s+"") must be between [0,1]""); if(b<0 || b>1) throw new IllegalArgumentException(""The brightness value (""+b+"") must be between [0,1]""); if(hue!=h || sat!=s || bri!=b) { if(mode==ColorPicker.HUE || mode==ColorPicker.BRI || mode==ColorPicker.SAT) { float lastHue = hue; float lastBri = bri; float lastSat = sat; hue = h; sat = s; bri = b; if(mode==ColorPicker.HUE) { if(lastHue!=hue) { regenerateImage(); } } else if(mode==ColorPicker.SAT) { if(lastSat!=sat) { regenerateImage(); } } else if(mode==ColorPicker.BRI) { if(lastBri!=bri) { regenerateImage(); } } } else { Color c = new Color(Color.HSBtoRGB(h, s, b)); setRGB(c.getRed(), c.getGreen(), c.getBlue()); return; } Color c = new Color(Color.HSBtoRGB(hue, sat, bri)); red = c.getRed(); green = c.getGreen(); blue = c.getBlue(); regeneratePoint(); repaint(); fireChangeListeners(); } } /** Recalculates the (x,y) point used to indicate the selected color. */ private void regeneratePoint() { int size = Math.min(MAX_SIZE, Math.min(getWidth()-imagePadding.left-imagePadding.right,getHeight()-imagePadding.top-imagePadding.bottom)); if(mode==ColorPicker.HUE || mode==ColorPicker.SAT || mode==ColorPicker.BRI) { if(mode==ColorPicker.HUE) { point = new Point((int)(sat*size+.5),(int)(bri*size+.5)); } else if(mode==ColorPicker.SAT) { double theta = hue*2*Math.PI-Math.PI/2; if(theta<0) theta+=2*Math.PI; double r = bri*size/2; point = new Point((int)(r*Math.cos(theta)+.5+size/2.0),(int)(r*Math.sin(theta)+.5+size/2.0)); } else if(mode==ColorPicker.BRI) { double theta = hue*2*Math.PI-Math.PI/2; if(theta<0) theta+=2*Math.PI; double r = sat*size/2; point = new Point((int)(r*Math.cos(theta)+.5+size/2.0),(int)(r*Math.sin(theta)+.5+size/2.0)); } } else if(mode==ColorPicker.RED) { point = new Point((int)(green*size/255f+.49f), (int)(blue*size/255f+.49f) ); } else if(mode==ColorPicker.GREEN) { point = new Point((int)(red*size/255f+.49f), (int)(blue*size/255f+.49f) ); } else if(mode==ColorPicker.BLUE) { point = new Point((int)(red*size/255f+.49f), (int)(green*size/255f+.49f) ); } } /** A row of pixel data we recycle every time we regenerate this image. */ private int[] row = new int[MAX_SIZE]; /** Regenerates the image. */ private synchronized void regenerateImage() { int size = Math.min(MAX_SIZE, Math.min(getWidth()-imagePadding.left-imagePadding.right,getHeight()-imagePadding.top-imagePadding.bottom)); if(mode==ColorPicker.BRI || mode==ColorPicker.SAT) { float bri2 = this.bri; float sat2 = this.sat; float radius = ((float)size)/2f; float hue2; float k = 1.2f; //the number of pixels to antialias for(int y = 0; yradius-k) { int alpha = (int)(255-255*(r-radius+k)/k); if(alpha<0) alpha = 0; if(alpha>255) alpha = 255; row[x] = row[x] & 0xffffff+(alpha << 24); } } else { row[x] = 0x00000000; } } image.getRaster().setDataElements(0, y, size, 1, row); } } else if(mode==ColorPicker.HUE) { float hue2 = this.hue; for(int y = 0; yThe color is assigned with the setForeground() method. *

Also the user can right-click this panel and select 'Copy' to send * a 100x100 image of this color to the clipboard. (This feature was * added at the request of a friend who paints; she wanted to select a * color and then quickly print it off, and then mix her paints to match * that shade.) * */ public class ColorSwatch extends JPanel { private static final long serialVersionUID = 1L; JPopupMenu menu; JMenuItem copyItem; MouseListener mouseListener = new MouseAdapter() { public void mousePressed(MouseEvent e) { if(e.isPopupTrigger()) { if(menu==null) { menu = new JPopupMenu(); copyItem = new JMenuItem(ColorPicker.strings.getObject(""Copy"").toString()); menu.add(copyItem); copyItem.addActionListener(actionListener); } menu.show(ColorSwatch.this,e.getX(),e.getY()); } } }; ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if(src==copyItem) { BufferedImage image = new BufferedImage(100,100,BufferedImage.TYPE_INT_RGB); Graphics2D g = image.createGraphics(); g.setColor(getBackground()); g.fillRect(0, 0, image.getWidth(), image.getHeight()); g.dispose(); Transferable contents = new ImageTransferable(image); Toolkit.getDefaultToolkit().getSystemClipboard().setContents(contents, null); } } }; int w; public ColorSwatch(int width) { w = width; setPreferredSize(new Dimension(width,width)); setMinimumSize(new Dimension(width,width)); addMouseListener(mouseListener); } public ColorSwatch(Color color,int width) { this(width); setForeground(color); } private static TexturePaint checkerPaint = null; private static TexturePaint getCheckerPaint() { if(checkerPaint==null) { int t = 8; BufferedImage bi = new BufferedImage(t*2,t*2,BufferedImage.TYPE_INT_RGB); Graphics g = bi.createGraphics(); g.setColor(Color.white); g.fillRect(0,0,2*t,2*t); g.setColor(Color.lightGray); g.fillRect(0,0,t,t); g.fillRect(t,t,t,t); checkerPaint = new TexturePaint(bi,new Rectangle(0,0,bi.getWidth(),bi.getHeight())); } return checkerPaint; } public void paint(Graphics g0) { super.paint(g0); //may be necessary for some look-and-feels? Graphics2D g = (Graphics2D)g0; Color c = getForeground(); int w2 = Math.min(getWidth(), w); int h2 = Math.min(getHeight(), w); Rectangle r = new Rectangle(getWidth()/2-w2/2,getHeight()/2-h2/2, w2, h2); if(c.getAlpha()<255) { TexturePaint checkers = getCheckerPaint(); g.setPaint(checkers); g.fillRect(r.x, r.y, r.width, r.height); } g.setColor(c); g.fillRect(r.x, r.y, r.width, r.height); PlafPaintUtils.drawBevel(g, r); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/swing/ColorPickerDialog.java",".java","3044","107","/* * @(#)ColorPickerDialog.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.swing; import java.awt.Color; import java.awt.Component; import java.awt.Dialog; import java.awt.Frame; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComponent; import javax.swing.JDialog; /** * This wraps a ColorPicker in a simple dialog with ""OK"" and * ""Cancel"" options. *

* (This object is used by the static calls in ColorPicker to show * a dialog.) * */ class ColorPickerDialog extends JDialog { private static final long serialVersionUID = 2L; ColorPicker cp; int alpha; Color returnValue = null; ActionListener okListener = new ActionListener() { public void actionPerformed(ActionEvent e) { returnValue = cp.getColor(); } }; DialogFooter footer; public ColorPickerDialog(Frame owner, Color color, boolean includeOpacity) { super(owner); initialize(owner, color, includeOpacity); } public ColorPickerDialog(Dialog owner, Color color, boolean includeOpacity) { super(owner); initialize(owner, color, includeOpacity); } private void initialize(Component owner, Color color, boolean includeOpacity) { cp = new ColorPicker(true, includeOpacity); setModal(true); setResizable(false); getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 1; c.fill = GridBagConstraints.BOTH; c.gridwidth = GridBagConstraints.REMAINDER; c.insets = new Insets(10, 10, 10, 10); getContentPane().add(cp, c); c.gridy++; footer = DialogFooter.createDialogFooter(new JComponent[] {}, DialogFooter.OK_CANCEL_OPTION, DialogFooter.OK_OPTION, DialogFooter.ESCAPE_KEY_TRIGGERS_CANCEL); c.gridy++; c.weighty = 0; getContentPane().add(footer, c); cp.setRGB(color.getRed(), color.getGreen(), color.getBlue()); cp.setOpacity(color.getAlpha()); alpha = color.getAlpha(); pack(); setLocationRelativeTo(owner); footer.getButton(DialogFooter.OK_OPTION).addActionListener(okListener); } /** * @return the color committed when the user clicked 'OK'. Note this returns * null if the user canceled this dialog, or exited via * the close decoration. */ public Color getColor() { return returnValue; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/swing/ImageTransferable.java",".java","1412","51","/* * @(#)ImageTransferable.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.swing; import java.awt.Image; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; class ImageTransferable implements Transferable { Image img; public ImageTransferable(Image i) { img = i; } public Object getTransferData(DataFlavor f) throws UnsupportedFlavorException, IOException { if(f.equals(DataFlavor.imageFlavor)==false) throw new UnsupportedFlavorException(f); return img; } public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] {DataFlavor.imageFlavor}; } public boolean isDataFlavorSupported(DataFlavor flavor) { return(flavor.equals(DataFlavor.imageFlavor)); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/swing/DelegateFocusTraversalPolicy.java",".java","1726","59","/* * @(#)DelegateFocusTraversalPolicy.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.swing; import java.awt.Component; import java.awt.Container; import java.awt.FocusTraversalPolicy; /** A simple FocusTraversalPolicy object that delegates to * another object. * */ public class DelegateFocusTraversalPolicy extends FocusTraversalPolicy { FocusTraversalPolicy ftp; public DelegateFocusTraversalPolicy(FocusTraversalPolicy policy) { ftp = policy; } public Component getComponentAfter(Container focusCycleRoot, Component component) { return ftp.getComponentAfter(focusCycleRoot, component); } public Component getComponentBefore(Container focusCycleRoot, Component component) { return ftp.getComponentBefore(focusCycleRoot, component); } public Component getDefaultComponent(Container focusCycleRoot) { return ftp.getDefaultComponent(focusCycleRoot); } public Component getFirstComponent(Container focusCycleRoot) { return ftp.getFirstComponent(focusCycleRoot); } public Component getLastComponent(Container focusCycleRoot) { return ftp.getLastComponent(focusCycleRoot); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/swing/DialogFooter.java",".java","38992","937","/* * @(#)DialogFooter.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.swing; import java.awt.Component; import java.awt.Container; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Toolkit; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.HierarchyEvent; import java.awt.event.HierarchyListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.lang.reflect.Method; import java.util.ResourceBundle; import java.util.Vector; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JRootPane; import javax.swing.KeyStroke; import javax.swing.RootPaneContainer; import javax.swing.SwingUtilities; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import colorpicker.plaf.FocusArrowListener; import colorpicker.util.JVM; /** This is a row of buttons, intended to be displayed at the * bottom of a dialog. This class is strongly related to the * {@link com.bric.swing.QDialog} project, although the * DialogFooter can exist by itself. *

On the left of a footer are controls that should apply to the dialog itself, * such as ""Help"" button, or a ""Reset Preferences"" button. * On the far right are buttons that should dismiss this dialog. They * may be presented in different orders on different platforms based * on the reverseButtonOrder boolean. *

Buttons are also generally normalized, so the widths of buttons * are equal. *

This object will ""latch onto"" the RootPane that contains it. It is assumed * two DialogFooters will not be contained in the same RootPane. It is also * assumed the same DialogFooter will not be passed around to several * different RootPanes. *

Preset Options

* This class has several OPTION constants to create specific buttons. *

In each constant the first option is the default button unless * you specify otherwise. The Apple Interface Guidelines advises: * ""The default button should be the button that represents the * action that the user is most likely to perform if that action isn�t * potentially dangerous."" *

The YES_NO options should be approached with special reluctance. * Microsoft cautions, * ""Use Yes and No buttons only to respond to yes or no questions."" This seems * obvious enough, but Apple adds, ""Button names should correspond to the action * the user performs when pressing the button�for example, Erase, Save, or Delete."" * So instead of presenting a YES_NO dialog with the question ""Do you want to continue?"" * a better dialog might provide the options ""Cancel"" and ""Continue"". In short: we * as developers might tend to lazily use this option and phrase dialogs in such * a way that yes/no options make sense, but in fact the commit buttons should be * more descriptive. *

Partly because of the need to avoid yes/no questions, DialogFooter introduces the * dialog type: SAVE_DONT_SAVE_CANCEL_OPTION. This is mostly straightforward, but * there is one catch: on Mac the buttons * are reordered: ""Save"", ""Cancel"" and ""Don't Save"". This is to conform with standard * Mac behavior. (Or, more specifically: because the Apple guidelines * state that a button that can cause permanent data loss be as physically far * from a ""safe"" button as possible.) On all other platforms the buttons are * listed in the order ""Save"", ""Don't Save"" and ""Cancel"". *

Also note the field {@link #reverseButtonOrder} * controls the order each option is presented in the dialog from left-to-right. *

Platform Differences

* These are based mostly on studying Apple and Vista interface guidelines. *
  • On Mac, command-period acts like the escape key in dialogs. *
  • On Mac the Help component is the standard Mac help icon. On other platforms * the help component is a {@link com.bric.swing.JLink}. *
  • By default button order is reversed on Macs compared to other platforms. See * the DialogFooter.reverseButtonOrder field for details. *
  • There is a static boolean to control whether button mnemonics should be * universally activated. This was added because * when studying Windows XP there seemed to be no fixed rules for whether to * use mnemonics or not. (Some dialogs show them, some dialogs don't.) So I * leave it to your discretion to activate them. I think this boolean should never be * activated on Vista or Mac, but on XP and Linux flavors: that's up to you. (Remember * using the alt key usually activates the mnemonics in most Java look-and-feels, so just * because they aren't universally active doesn't mean you're hurting accessibility needs.)
  • */ public class DialogFooter extends JPanel { private static final long serialVersionUID = 1L; /** This (the default behavior) does nothing when the escape key is pressed. */ public static final int ESCAPE_KEY_DOES_NOTHING = 0; /** This triggers the cancel button when the escape key is pressed. If no * cancel button is present: this does nothing. * (Also on Macs command+period acts the same as the escape key.) *

    This should only be used if the cancel button does not lead to data * loss, because users may quickly press the escape key before reading * the text in a dialog. */ public static final int ESCAPE_KEY_TRIGGERS_CANCEL = 1; /** This triggers the default button when the escape key is pressed. If no * default button is defined: this does nothing. * (Also on Macs command+period acts the same as the escape key.) *

    This should only be used if the default button does not lead to data * loss, because users may quickly press the escape key before reading * the text in a dialog. */ public static final int ESCAPE_KEY_TRIGGERS_DEFAULT = 2; /** This triggers the non-default button when the escape key is pressed. If no * non-default button is defined: this does nothing. * (Also on Macs command+period acts the same as the escape key.) *

    This should only be used if the non-default button does not lead to data * loss, because users may quickly press the escape key before reading * the text in a dialog. */ public static final int ESCAPE_KEY_TRIGGERS_NONDEFAULT = 3; private static KeyStroke escapeKey = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); private static KeyStroke commandPeriodKey = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); /** The localized strings used in dialogs. */ public static ResourceBundle strings = ResourceBundle.getBundle(""colorpicker.swing.resources.DialogFooter""); /** This is the client property of buttons created in static methods by this class. */ public static String PROPERTY_OPTION = ""DialogFooter.propertyOption""; private static int uniqueCtr = 0; /** Used to indicate the user selected ""Cancel"" in a dialog. *
    Also this can be used as a dialog type, to indicate that ""Cancel"" should * be the only option presented to the user. *

    Note the usage is similar to JOptionPane's, but the numerical value is * different, so you cannot substitute JOptionPane.CANCEL_OPTION for DialogFooter.CANCEL_OPTION. */ public static final int CANCEL_OPTION = uniqueCtr++; /** Used to indicate the user selected ""OK"" in a dialog. *
    Also this can be used as a dialog type, to indicate that ""OK"" should * be the only option presented to the user. *

    Note the usage is similar to JOptionPane's, but the numerical value is * different, so you cannot substitute JOptionPane.OK_OPTION for DialogFooter.OK_OPTION. */ public static final int OK_OPTION = uniqueCtr++; /** Used to indicate the user selected ""No"" in a dialog. *
    Also this can be used as a dialog type, to indicate that ""No"" should * be the only option presented to the user. *

    Note the usage is similar to JOptionPane's, but the numerical value is * different, so you cannot substitute JOptionPane.NO_OPTION for DialogFooter.NO_OPTION. */ public static final int NO_OPTION = uniqueCtr++; /** Used to indicate the user selected ""Yes"" in a dialog. *
    Also this can be used as a dialog type, to indicate that ""Yes"" should * be the only option presented to the user. *

    Note the usage is similar to JOptionPane's, but the numerical value is * different, so you cannot substitute JOptionPane.YES_OPTION for DialogFooter.YES_OPTION. */ public static final int YES_OPTION = uniqueCtr++; /** Used to indicate a dialog should present a ""Yes"" and ""No"" option. *

    Note the usage is similar to JOptionPane's, but the numerical value is * different, so you cannot substitute JOptionPane.YES_NO_OPTION for DialogFooter.YES_NO_OPTION. */ public static final int YES_NO_OPTION = uniqueCtr++; /** Used to indicate a dialog should present a ""Yes"", ""No"", and ""Cancel"" option. *

    Note the usage is similar to JOptionPane's, but the numerical value is * different, so you cannot substitute JOptionPane.YES_NO_CANCEL_OPTION for DialogFooter.YES_NO_CANCEL_OPTION. */ public static final int YES_NO_CANCEL_OPTION = uniqueCtr++; /** Used to indicate a dialog should present a ""OK"" and ""Cancel"" option. *

    Note the usage is similar to JOptionPane's, but the numerical value is * different, so you cannot substitute JOptionPane.OK_CANCEL_OPTION for DialogFooter.OK_CANCEL_OPTION. */ public static final int OK_CANCEL_OPTION = uniqueCtr++; /** Used to indicate a dialog should present a ""Save"", ""Don't Save"", and ""Cancel"" option. */ public static final int SAVE_DONT_SAVE_CANCEL_OPTION = uniqueCtr++; /** Used to indicate the user selected ""Save"" in a dialog. *
    Also this can be used as a dialog type, to indicate that ""Save"" * should be the only option presented to the user. */ public static final int SAVE_OPTION = uniqueCtr++; /** Used to indicate the user selected ""Don't Save"" in a dialog. *
    Also this can be used as a dialog type, to indicate that ""Don't Save"" * should be the only option presented to the user. */ public static final int DONT_SAVE_OPTION = uniqueCtr++; private static AncestorListener escapeTriggerListener = new AncestorListener() { public void ancestorAdded(AncestorEvent event) { JButton button = (JButton)event.getComponent(); Window w = SwingUtilities.getWindowAncestor(button); if(w instanceof RootPaneContainer) { setRootPaneContainer(button, (RootPaneContainer)w); } else { setRootPaneContainer(button, null); } } private void setRootPaneContainer(JButton button,RootPaneContainer c) { RootPaneContainer lastContainer = (RootPaneContainer)button.getClientProperty(""bric.footer.rpc""); if(lastContainer==c) return; if(lastContainer!=null) { lastContainer.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).remove(escapeKey); lastContainer.getRootPane().getActionMap().remove(escapeKey); if(JVM.isMac) lastContainer.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).remove(commandPeriodKey); } if(c!=null) { c.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(escapeKey, escapeKey); c.getRootPane().getActionMap().put(escapeKey, new ClickAction(button)); if(JVM.isMac) c.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(commandPeriodKey, escapeKey); } button.putClientProperty(""bric.footer.rpc"", c); } public void ancestorMoved(AncestorEvent event) { ancestorAdded(event); } public void ancestorRemoved(AncestorEvent event) { ancestorAdded(event); } }; /** Creates a new ""Cancel"" button. * * @param escapeKeyIsTrigger if true then pressing the escape * key will trigger this button. (Also on Macs command-period will act * like the escape key.) This should be false if this button * can lead to permanent data loss. */ public static JButton createCancelButton(boolean escapeKeyIsTrigger) { JButton button = new JButton(strings.getString(""dialogCancelButton"")); button.setMnemonic( strings.getString(""dialogCancelMnemonic"").charAt(0) ); button.putClientProperty(PROPERTY_OPTION, new Integer(CANCEL_OPTION)); if(escapeKeyIsTrigger) makeEscapeKeyActivate(button); return button; } /** This guarantees that when the escape key is pressed * (if its parent window has the keyboard focus) this button * is clicked. *

    It is assumed that no two buttons will try to consume * escape keys in the same window. * * @param button the button to trigger when the escape key is pressed. */ public static void makeEscapeKeyActivate(AbstractButton button) { button.addAncestorListener(escapeTriggerListener); } /** Creates a new ""OK"" button that is not triggered by the escape key. */ public static JButton createOKButton() { return createOKButton(false); } /** Creates a new ""OK"" button. * * @param escapeKeyIsTrigger if true then pressing the escape * key will trigger this button. (Also on Macs command-period will act * like the escape key.) This should be false if this button * can lead to permanent data loss. */ public static JButton createOKButton(boolean escapeKeyIsTrigger) { JButton button = new JButton(strings.getString(""dialogOKButton"")); button.setMnemonic( strings.getString(""dialogOKMnemonic"").charAt(0) ); button.putClientProperty(PROPERTY_OPTION, new Integer(OK_OPTION)); if(escapeKeyIsTrigger) makeEscapeKeyActivate(button); return button; } /** Creates a new ""Yes"" button that is not triggered by the escape key. */ public static JButton createYesButton() { return createYesButton(false); } /** Creates a new ""Yes"" button. * * @param escapeKeyIsTrigger if true then pressing the escape * key will trigger this button. (Also on Macs command-period will act * like the escape key.) This should be false if this button * can lead to permanent data loss. */ public static JButton createYesButton(boolean escapeKeyIsTrigger) { JButton button = new JButton(strings.getString(""dialogYesButton"")); button.setMnemonic( strings.getString(""dialogYesMnemonic"").charAt(0) ); button.putClientProperty(PROPERTY_OPTION, new Integer(YES_OPTION)); if(escapeKeyIsTrigger) makeEscapeKeyActivate(button); return button; } /** Creates a new ""No"" button that is not triggered by the escape key. * */ public static JButton createNoButton() { return createNoButton(false); } /** Creates a new ""No"" button. * * @param escapeKeyIsTrigger if true then pressing the escape * key will trigger this button. (Also on Macs command-period will act * like the escape key.) This should be false if this button * can lead to permanent data loss. */ public static JButton createNoButton(boolean escapeKeyIsTrigger) { JButton button = new JButton(strings.getString(""dialogNoButton"")); button.setMnemonic( strings.getString(""dialogNoMnemonic"").charAt(0) ); button.putClientProperty(PROPERTY_OPTION, new Integer(NO_OPTION)); if(escapeKeyIsTrigger) makeEscapeKeyActivate(button); return button; } /** Creates a new ""Save"" button that is not triggered by the escape key. */ public static JButton createSaveButton() { return createSaveButton(false); } /** Creates a new ""Save"" button. * * @param escapeKeyIsTrigger if true then pressing the escape * key will trigger this button. (Also on Macs command-period will act * like the escape key.) This should be false if this button * can lead to permanent data loss. */ public static JButton createSaveButton(boolean escapeKeyIsTrigger) { JButton button = new JButton(strings.getString(""dialogSaveButton"")); button.setMnemonic( strings.getString(""dialogSaveMnemonic"").charAt(0) ); button.putClientProperty(PROPERTY_OPTION, new Integer(SAVE_OPTION)); if(escapeKeyIsTrigger) makeEscapeKeyActivate(button); return button; } /** Creates a new ""Don't Save"" button that is not triggered by the escape key. */ public static JButton createDontSaveButton() { return createDontSaveButton(false); } /** Creates a new ""Don't Save"" button. * * @param escapeKeyIsTrigger if true then pressing the escape * key will trigger this button. (Also on Macs command-period will act * like the escape key.) This should be false if this button * can lead to permanent data loss. */ public static JButton createDontSaveButton(boolean escapeKeyIsTrigger) { String text = strings.getString(""dialogDontSaveButton""); JButton button = new JButton(text); button.setMnemonic( strings.getString(""dialogDontSaveMnemonic"").charAt(0) ); button.putClientProperty(PROPERTY_OPTION, new Integer(DONT_SAVE_OPTION)); //Don't know if this documented by Apple, but command-D usually triggers ""Don't Save"" buttons: button.putClientProperty(DialogFooter.PROPERTY_META_SHORTCUT,new Character(text.charAt(0))); if(escapeKeyIsTrigger) makeEscapeKeyActivate(button); return button; } /** Creates a DialogFooter and assigns a default button. * The default button is the first button listed in the button type. For example, * a YES_NO_CANCEL_OPTION dialog will make the YES_OPTION the default button. *

    To use a different default button, use the other createDialogFooter() method. * * @param leftComponents the components to put on the left side of the footer. *

    The Apple guidelines state that this area is reserved for * ""button[s] that affect the contents of the dialog itself, such as Reset [or Help]"". * @param options one of the OPTIONS fields in this class, such as YES_NO_OPTION or CANCEL_OPTION. * @param escapeKeyBehavior one of the ESCAPE_KEY constants in this class. * @return a DialogFooter */ public static DialogFooter createDialogFooter(JComponent[] leftComponents,int options,int escapeKeyBehavior) { if(options==CANCEL_OPTION) { return createDialogFooter(leftComponents,options,CANCEL_OPTION,escapeKeyBehavior); } else if(options==DONT_SAVE_OPTION) { return createDialogFooter(leftComponents,options,DONT_SAVE_OPTION,escapeKeyBehavior); } else if(options==NO_OPTION) { return createDialogFooter(leftComponents,options,NO_OPTION,escapeKeyBehavior); } else if(options==OK_CANCEL_OPTION) { return createDialogFooter(leftComponents,options,OK_OPTION,escapeKeyBehavior); } else if(options==OK_OPTION) { return createDialogFooter(leftComponents,options,OK_OPTION,escapeKeyBehavior); } else if(options==SAVE_DONT_SAVE_CANCEL_OPTION) { return createDialogFooter(leftComponents,options,SAVE_OPTION,escapeKeyBehavior); } else if(options==SAVE_OPTION) { return createDialogFooter(leftComponents,options,SAVE_OPTION,escapeKeyBehavior); } else if(options==YES_NO_CANCEL_OPTION) { return createDialogFooter(leftComponents,options,YES_OPTION,escapeKeyBehavior); } else if(options==YES_NO_OPTION) { return createDialogFooter(leftComponents,options,YES_OPTION,escapeKeyBehavior); } else if(options==YES_OPTION) { return createDialogFooter(leftComponents,options,YES_OPTION,escapeKeyBehavior); } throw new IllegalArgumentException(""unrecognized option type (""+options+"")""); } /** Creates a DialogFooter. * @param leftComponents the components to put on the left side of the footer. *

    The Apple guidelines state that this area is reserved for * ""button[s] that affect the contents of the dialog itself, such as Reset [or Help]"". * @param options one of the OPTIONS fields in this class, such as YES_NO_OPTION or CANCEL_OPTION. * @param defaultButton the OPTION field corresponding to the button that * should be the default button, or -1 if there should be no default button. * @param escapeKeyBehavior one of the ESCAPE_KEY constants in this class. * @return a DialogFooter */ public static DialogFooter createDialogFooter(JComponent[] leftComponents,int options,int defaultButton,int escapeKeyBehavior) { JButton[] dismissControls; JButton cancelButton = null; JButton dontSaveButton = null; JButton noButton = null; JButton okButton = null; JButton saveButton = null; JButton yesButton = null; if(escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_NONDEFAULT) { int buttonCount = 1; if(options==OK_CANCEL_OPTION || options==YES_NO_OPTION) { buttonCount = 2; } else if(options==SAVE_DONT_SAVE_CANCEL_OPTION || options==YES_NO_CANCEL_OPTION) { buttonCount = 3; } if(defaultButton!=-1) { buttonCount--; } if(buttonCount>1) { throw new IllegalArgumentException(""request for escape key to map to ""+buttonCount+"" buttons.""); } } if(options==CANCEL_OPTION || options==OK_CANCEL_OPTION || options==SAVE_DONT_SAVE_CANCEL_OPTION || options==YES_NO_CANCEL_OPTION) { cancelButton = createCancelButton( escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_CANCEL || (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_NONDEFAULT && defaultButton!=CANCEL_OPTION) || (defaultButton==CANCEL_OPTION && escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_DEFAULT) ); } if(options==DONT_SAVE_OPTION || options==SAVE_DONT_SAVE_CANCEL_OPTION) { dontSaveButton = createDontSaveButton( (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_NONDEFAULT && defaultButton!=DONT_SAVE_OPTION) || (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_DEFAULT && defaultButton==DONT_SAVE_OPTION )); } if(options==NO_OPTION || options==YES_NO_OPTION || options==YES_NO_CANCEL_OPTION) { noButton = createNoButton( (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_NONDEFAULT && defaultButton!=NO_OPTION) || (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_DEFAULT && defaultButton==NO_OPTION )); } if(options==OK_OPTION || options==OK_CANCEL_OPTION) { okButton = createOKButton( (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_NONDEFAULT && defaultButton!=OK_OPTION) || (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_DEFAULT && defaultButton==OK_OPTION )); } if(options==SAVE_OPTION || options==SAVE_DONT_SAVE_CANCEL_OPTION) { saveButton = createSaveButton( (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_NONDEFAULT && defaultButton!=SAVE_OPTION) || (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_DEFAULT && defaultButton==SAVE_OPTION )); } if(options==YES_OPTION || options==YES_NO_OPTION || options==YES_NO_CANCEL_OPTION) { yesButton = createYesButton( (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_NONDEFAULT && defaultButton!=YES_OPTION) || (escapeKeyBehavior==ESCAPE_KEY_TRIGGERS_DEFAULT && defaultButton==YES_OPTION )); } if(options==CANCEL_OPTION) { dismissControls = new JButton[] { cancelButton }; } else if(options==DONT_SAVE_OPTION) { dismissControls = new JButton[] { dontSaveButton }; } else if(options==NO_OPTION) { dismissControls = new JButton[] { noButton }; } else if(options==OK_CANCEL_OPTION) { dismissControls = new JButton[] { okButton, cancelButton }; } else if(options==OK_OPTION) { dismissControls = new JButton[] { okButton }; } else if(options==SAVE_DONT_SAVE_CANCEL_OPTION) { dontSaveButton.putClientProperty(DialogFooter.PROPERTY_UNSAFE, Boolean.TRUE); if(JVM.isMac) { dismissControls = new JButton[] { saveButton, cancelButton, dontSaveButton }; } else { dismissControls = new JButton[] { saveButton, dontSaveButton, cancelButton }; } } else if(options==SAVE_OPTION) { dismissControls = new JButton[] { saveButton }; } else if(options==YES_NO_CANCEL_OPTION) { dismissControls = new JButton[] { yesButton, noButton, cancelButton }; } else if(options==YES_NO_OPTION) { dismissControls = new JButton[] { yesButton, noButton }; } else if(options==YES_OPTION) { dismissControls = new JButton[] { yesButton }; } else { throw new IllegalArgumentException(""Unrecognized dialog type.""); } JButton theDefaultButton = null; for(int a = 0; abutton.doClick(). */ public static class ClickAction extends AbstractAction { private static final long serialVersionUID = 1L; JButton button; public ClickAction(JButton button) { this.button = button; } public void actionPerformed(ActionEvent e) { button.doClick(); } } public static final boolean isMac = System.getProperty(""os.name"").toLowerCase().indexOf(""mac"")!=-1; public static final boolean isVista = System.getProperty(""os.name"").toLowerCase().indexOf(""vista"")!=-1; /** This client property is used to impose a meta-shortcut to click a button. * This should map to a Character. */ public static final String PROPERTY_META_SHORTCUT = ""Dialog.meta.shortcut""; /** This client property is used to indicate a button is ""unsafe"". Apple * guidelines state that ""unsafe"" buttons (such as ""discard changes"") should * be several pixels away from ""safe"" buttons. */ public static final String PROPERTY_UNSAFE = ""Dialog.Unsafe.Action""; /** This indicates whether the dismiss controls should be displayed in reverse * order. When you construct a DialogFooter, the dismiss controls should be listed * in order of priority (with the most preferred listed first, the least preferred last). * If this boolean is false, then those components will be listed in that order. If this is * true, then those components will be listed in the reverse order. *

    By default on Mac this is true, because Macs put the default button on the right * side of dialogs. On all other platforms this is false by default. *

    Window's guidelines * advise to, ""Position the most important button -- typically the default command -- * as the first button in the set."" */ public static boolean reverseButtonOrder = isMac; protected JComponent[] leftControls; protected JComponent[] dismissControls; protected JComponent lastSelectedComponent; protected boolean autoClose = false; protected JButton defaultButton = null; private final ActionListener innerActionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { lastSelectedComponent = (JComponent)e.getSource(); fireActionListeners(e); if(autoClose) closeDialogAndDisposeAction.actionPerformed(e); } }; /** Clones an array of JComponents */ private static JComponent[] copy(JComponent[] c) { JComponent[] newArray = new JComponent[c.length]; for(int a = 0; aDialogFooter. * * @param leftControls the controls on the left side of this dialog, such as a help component, or a ""Reset"" button. * @param dismissControls the controls on the right side of this dialog that should dismiss this dialog. Also * called ""action"" buttons. * @param autoClose whether the dismiss buttons should automatically close the containing window. * If this is false, then it is assumed someone else is taking care of closing/disposing the * containing dialog * @param defaultButton the optional button in dismissControls to make the default button in this dialog. * (May be null.) */ public DialogFooter(JComponent[] leftControls,JComponent[] dismissControls,boolean autoClose,JButton defaultButton) { super(new GridBagLayout()); this.autoClose = autoClose; //this may be common: if(leftControls==null) leftControls = new JComponent[] {}; //erg, this shouldn't be, but let's not throw an error because of it? if(dismissControls==null) dismissControls = new JComponent[] {}; this.leftControls = copy(leftControls); this.dismissControls = copy(dismissControls); this.defaultButton = defaultButton; // if(leftControls==null) leftControls = new JComponent[] {}; // if(dismissControls==null) dismissControls = new JComponent[] {}; GridBagConstraints c = new GridBagConstraints(); int buttonPadding; if(isMac) { buttonPadding = 12; } else if(isVista) { buttonPadding = 8; } else { buttonPadding = 6; } c.gridx = 0; c.gridy = 0; c.weightx = 0; c.weighty = 1; c.fill = GridBagConstraints.NONE; c.insets = new Insets(0,0,0,0); c.anchor = GridBagConstraints.CENTER; for(int a = 0; a cl = dismissControls[a].getClass(); Method m = cl.getMethod(""addActionListener"", new Class[] {ActionListener.class}); m.invoke(dismissControls[a], new Object[] {innerActionListener}); } catch(Throwable t) { //do nothing } } } addHierarchyListener(hierarchyListener); for(int a = 0; a(More specifically, this sets the preferredSize * of each button to the largest preferred size in the list of buttons. * * @param buttons an array of buttons. */ public static void normalizeButtons(JButton[] buttons) { int maxWidth = 0; int maxHeight = 0; for(int a = 0; a listeners; /** Adds an ActionListener. * * @param l this listener will be notified when a dismissControl is activated. */ public void addActionListener(ActionListener l) { if(listeners==null) listeners = new Vector(); if(listeners.contains(l)) return; listeners.add(l); } /** Removes an ActionListener. */ public void removeActionListener(ActionListener l) { if(listeners==null) return; listeners.remove(l); } private void fireActionListeners(ActionEvent e) { if(listeners==null) return; for(int a = 0; aNote the components on the left side of this footer * (such as a ""Help"" button or a ""Reset Preferences"" button) * do NOT dismiss the dialog, and so this method has nothing * to do with those components. This only related to the components on the * right side of dialog. * @return the component last used to dismiss the dialog. */ public JComponent getLastSelectedComponent() { return lastSelectedComponent; } /** Finds a certain type of button, if it is available. * * @param buttonType of the options in this class (such as YES_OPTION or CANCEL_OPTION) * @return the button that maps to that option, or null if no such button was found. */ public JButton getButton(int buttonType) { for(int a = 0; alastSelectedComponent to null. *

    If this footer is recycled in different dialogs, then you may * need to nullify this value for getLastSelectedComponent() * to remain relevant. */ public void reset() { lastSelectedComponent = null; } /** Returns a copy of the dismissControls array used to construct this footer. */ public JComponent[] getDismissControls() { return copy(dismissControls); } public void setAutoClose(boolean b) { autoClose = b; } /** Returns a copy of the leftControls array used to construct this footer. */ public JComponent[] getLeftControls() { return copy(leftControls); } /** This action takes the Window associated with the source of this event, * hides it, and then calls dispose() on it. *

    (This will not throw an exception if there is no parent window, * but it does nothing in that case...) */ public static Action closeDialogAndDisposeAction = new AbstractAction() { private static final long serialVersionUID = 1L; public void actionPerformed(ActionEvent e) { Component src = (Component)e.getSource(); Window w = SwingUtilities.getWindowAncestor(src); if(w==null) return; w.setVisible(false); w.dispose(); } }; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/swing/ColorPickerDemo.java",".java","9170","299","/* * @(#)ColorPickerDemo.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.swing; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.image.BufferedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Random; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JInternalFrame; import javax.swing.JWindow; import javax.swing.SwingUtilities; import javax.swing.UIManager; /** * A simple demo for the ColorPicker class. * * @name ColorPicker * @title Colors: a Color Dialog * @release April 2007 * @blurb This is a Photoshop-style color choosing dialog. *

    * You can pull some parts of it apart for customization, but * out-of-the-box it offers a great interface if you're dealing with a * power user. *

    * Of course: all dialogs are at least slightly evil, and they should be * used with care... * @see Colors: a Color Dialog */ public class ColorPickerDemo extends JApplet implements PropertyChangeListener { private static final long serialVersionUID = 1L; public static BufferedImage createBlurbGraphic(Dimension preferredSize) throws Exception { ColorPicker picker = new ColorPicker(); picker.setColor(new Color(0x4F63C3)); JFrame frame = new JFrame(); final JInternalFrame window = new JInternalFrame(); window.getContentPane().add(picker); window.pack(); frame.getContentPane().add(window); frame.pack(); final BufferedImage image = new BufferedImage(window.getWidth(), window .getHeight(), BufferedImage.TYPE_INT_ARGB); SwingUtilities.invokeAndWait(new Runnable() { public void run() { Graphics2D g = image.createGraphics(); window.paint(g); g.dispose(); } }); return image; } /** * This demonstrates how to customize a small ColorPicker * component. */ public static void main(String[] args) { final JFrame demo = new JFrame(""Demo""); final JWindow palette = new JWindow(demo); final ColorPicker picker = new ColorPicker(true, false); final JComboBox comboBox = new JComboBox(); final JCheckBox alphaCheckbox = new JCheckBox(""Include Alpha""); final JCheckBox hsbCheckbox = new JCheckBox(""Include HSB Values""); final JCheckBox rgbCheckbox = new JCheckBox(""Include RGB Values""); final JCheckBox modeCheckbox = new JCheckBox(""Include Mode Controls"", true); final JButton button = new JButton(""Show Dialog""); demo.getContentPane().setLayout(new GridBagLayout()); palette.getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.gridx = 0; c.gridy = 0; c.weightx = 1; c.weighty = 0; c.insets = new Insets(5, 5, 5, 5); c.anchor = GridBagConstraints.WEST; palette.getContentPane().add(comboBox, c); c.gridy++; palette.getContentPane().add(alphaCheckbox, c); c.gridy++; palette.getContentPane().add(hsbCheckbox, c); c.gridy++; palette.getContentPane().add(rgbCheckbox, c); c.gridy++; palette.getContentPane().add(modeCheckbox, c); c.gridy = 0; c.weighty = 1; c.fill = GridBagConstraints.BOTH; picker.setPreferredSize(new Dimension(220, 200)); demo.getContentPane().add(picker, c); c.gridy++; c.weighty = 0; demo.getContentPane().add(picker.getExpertControls(), c); c.gridy++; c.fill = GridBagConstraints.NONE; demo.getContentPane().add(button, c); comboBox.addItem(""Hue""); comboBox.addItem(""Saturation""); comboBox.addItem(""Brightness""); comboBox.addItem(""Red""); comboBox.addItem(""Green""); comboBox.addItem(""Blue""); ActionListener checkboxListener = new ActionListener() { public void actionPerformed(ActionEvent e) { Object src = e.getSource(); if (src == alphaCheckbox) { picker.setOpacityVisible(alphaCheckbox.isSelected()); } else if (src == hsbCheckbox) { picker.setHSBControlsVisible(hsbCheckbox.isSelected()); } else if (src == rgbCheckbox) { picker.setRGBControlsVisible(rgbCheckbox.isSelected()); } else if (src == modeCheckbox) { picker.setModeControlsVisible(modeCheckbox.isSelected()); } demo.pack(); } }; picker.setOpacityVisible(false); picker.setHSBControlsVisible(false); picker.setRGBControlsVisible(false); picker.setHexControlsVisible(false); picker.setPreviewSwatchVisible(false); picker.addPropertyChangeListener(ColorPicker.MODE_PROPERTY, new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent evt) { int m = picker.getMode(); if (m == ColorPicker.HUE) { comboBox.setSelectedIndex(0); } else if (m == ColorPicker.SAT) { comboBox.setSelectedIndex(1); } else if (m == ColorPicker.BRI) { comboBox.setSelectedIndex(2); } else if (m == ColorPicker.RED) { comboBox.setSelectedIndex(3); } else if (m == ColorPicker.GREEN) { comboBox.setSelectedIndex(4); } else if (m == ColorPicker.BLUE) { comboBox.setSelectedIndex(5); } } }); alphaCheckbox.addActionListener(checkboxListener); hsbCheckbox.addActionListener(checkboxListener); rgbCheckbox.addActionListener(checkboxListener); modeCheckbox.addActionListener(checkboxListener); button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Color color = picker.getColor(); color = ColorPicker.showDialog(demo, color, true); if (color != null) picker.setColor(color); } }); comboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = ((JComboBox) e.getSource()).getSelectedIndex(); if (i == 0) { picker.setMode(ColorPicker.HUE); } else if (i == 1) { picker.setMode(ColorPicker.SAT); } else if (i == 2) { picker.setMode(ColorPicker.BRI); } else if (i == 3) { picker.setMode(ColorPicker.RED); } else if (i == 4) { picker.setMode(ColorPicker.GREEN); } else if (i == 5) { picker.setMode(ColorPicker.BLUE); } } }); comboBox.setSelectedIndex(2); palette.pack(); palette.setLocationRelativeTo(null); demo.addComponentListener(new ComponentAdapter() { public void componentMoved(ComponentEvent e) { Point p = demo.getLocation(); palette.setLocation(new Point(p.x - palette.getWidth() - 10, p.y)); } }); demo.pack(); demo.setLocationRelativeTo(null); demo.setVisible(true); palette.setVisible(true); demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public ColorPickerDemo() { try { String lf = UIManager.getSystemLookAndFeelClassName(); UIManager.setLookAndFeel(lf); } catch (Throwable e) { e.printStackTrace(); } ColorPicker picker = new ColorPicker(); picker.setOpacityVisible(true); Random r = new Random(System.currentTimeMillis()); picker.setColor(new Color(r.nextInt(255), r.nextInt(255), r .nextInt(255))); getContentPane().add(picker); picker.addPropertyChangeListener(this); /* * If you really want to know what RGB values the mouse is over: * ColorPickerPanel pickerPanel = picker.getColorPanel(); * pickerPanel.addMouseMotionListener(new MouseMotionAdapter() { public * void mouseMoved(MouseEvent e) { ColorPickerPanel cpp = * (ColorPickerPanel)e.getSource(); int[] rgb = * cpp.getRGB(e.getPoint()); * System.out.println(""indicated point: ""+rgb[0 * ]+"", ""+rgb[1]+"", ""+rgb[2]); } }); */ picker.setBackground(Color.white); picker.setOpaque(true); } public void propertyChange(PropertyChangeEvent evt) { System.out.println(""\"""" + evt.getPropertyName() + ""\"" "" + toString(evt.getOldValue()) + ""->"" + toString(evt.getNewValue())); } /** * Because Color.toString() omits alpha information... * * @param obj * @return */ private static String toString(Object obj) { if (obj == null) return null; if (obj instanceof Color) { Color c = (Color) obj; return ""Color[ r="" + c.getRed() + "", g="" + c.getGreen() + "", b="" + c.getBlue() + "", a="" + c.getAlpha() + ""]""; } return obj.toString(); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/plaf/ColorPickerSliderUI.java",".java","6268","205","/* * @(#)ColorPickerSliderUI.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.plaf; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.TexturePaint; import java.awt.Toolkit; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import javax.swing.JSlider; import javax.swing.event.MouseInputAdapter; import javax.swing.plaf.basic.BasicSliderUI; import colorpicker.swing.ColorPicker; import colorpicker.swing.ColorPickerPanel; /** This is a SliderUI designed specifically for the * ColorPicker. * */ public class ColorPickerSliderUI extends BasicSliderUI { ColorPicker colorPicker; /** Half of the height of the arrow */ int ARROW_HALF = 8; int[] intArray = new int[ Toolkit.getDefaultToolkit().getScreenSize().height ]; BufferedImage bi = new BufferedImage(1,intArray.length,BufferedImage.TYPE_INT_RGB); int lastMode = -1; public ColorPickerSliderUI(JSlider b,ColorPicker cp) { super(b); colorPicker = cp; cp.getColorPanel().addComponentListener(new ComponentAdapter() { public void componentResized(ComponentEvent e) { ColorPickerSliderUI.this.calculateGeometry(); slider.repaint(); } }); } public void paintThumb(Graphics g) { int y = thumbRect.y+thumbRect.height/2; Polygon polygon = new Polygon(); polygon.addPoint(0,y-ARROW_HALF); polygon.addPoint(ARROW_HALF,y); polygon.addPoint(0,y+ARROW_HALF); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setColor(Color.black); g2.fill(polygon); g2.setColor(Color.white); g2.setStroke(new BasicStroke(1)); g2.draw(polygon); } protected void calculateThumbSize() { super.calculateThumbSize(); thumbRect.height+=4; thumbRect.y-=2; } protected void calculateTrackRect() { super.calculateTrackRect(); ColorPickerPanel cp = colorPicker.getColorPanel(); int size = Math.min(ColorPickerPanel.MAX_SIZE, Math.min(cp.getWidth(), cp.getHeight())); int max = slider.getHeight()-ARROW_HALF*2-2; if(size>max) { size = max; } trackRect.y = slider.getHeight()/2-size/2; trackRect.height = size; } public synchronized void paintTrack(Graphics g) { int mode = colorPicker.getMode(); if(mode==ColorPicker.HUE || mode==ColorPicker.BRI || mode==ColorPicker.SAT) { float[] hsb = colorPicker.getHSB(); if(mode==ColorPicker.HUE) { for(int y = 0; yUIManager.put(""focusRing"",customColor); */ public static Color getFocusRingColor() { Object obj = UIManager.getColor(""Focus.color""); if(obj instanceof Color) return (Color)obj; obj = UIManager.getColor(""focusRing""); if(obj instanceof Color) return (Color)obj; return new Color(64,113,167); } /** Paints 3 different strokes around a shape to indicate focus. * The widest stroke is the most transparent, so this achieves a nice * ""glow"" effect. *

    The catch is that you have to render this underneath the shape, * and the shape should be filled completely. * * @param g the graphics to paint to * @param shape the shape to outline * @param pixelSize the number of pixels the outline should cover. */ public static void paintFocus(Graphics2D g,Shape shape,int pixelSize) { Color focusColor = getFocusRingColor(); Color[] focusArray = new Color[] { new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(),235), new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(),130), new Color(focusColor.getRed(), focusColor.getGreen(), focusColor.getBlue(),80) }; if(JVM.usingQuartz) { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); } else { g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE); } g.setStroke(new BasicStroke(2*pixelSize+1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g.setColor(focusArray[2]); g.draw(shape); if(2*pixelSize+1>0) { g.setStroke(new BasicStroke(2*pixelSize-2+1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g.setColor(focusArray[1]); g.draw(shape); } if(2*pixelSize-4+1>0) { g.setStroke(new BasicStroke(2*pixelSize-4+1, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); g.setColor(focusArray[0]); g.draw(shape); } } /** Uses translucent shades of white and black to draw highlights * and shadows around a rectangle, and then frames the rectangle * with a shade of gray (120). *

    This should be called to add a finishing touch on top of * existing graphics. * @param g the graphics to paint to. * @param r the rectangle to paint. */ public static void drawBevel(Graphics2D g,Rectangle r) { g.setStroke(new BasicStroke(1)); drawColors(blacks,g, r.x, r.y+r.height, r.x+r.width, r.y+r.height, SwingConstants.SOUTH); drawColors(blacks,g, r.x+r.width, r.y, r.x+r.width, r.y+r.height, SwingConstants.EAST); drawColors(whites,g, r.x, r.y, r.x+r.width, r.y, SwingConstants.NORTH); drawColors(whites,g, r.x, r.y, r.x, r.y+r.height, SwingConstants.WEST); g.setColor(new Color(120, 120, 120)); g.drawRect(r.x, r.y, r.width, r.height); } private static void drawColors(Color[] colors,Graphics g,int x1,int y1,int x2,int y2,int direction) { for(int a = 0; a verticalGradients; /** Create a vertical gradient. This gradient is stored in a * table and reused throughout the rest of this session. * * @param name an identifying key for this gradient (used to cache it). * @param height the height of the gradient * @param y the y offset of the gradient * @param positions the fractional positions of each color (between [0,1]). * @param colors one color for each position. * @return the vertical gradient. */ synchronized static Paint getVerticalGradient(String name, int height,int y, float[] positions, Color[] colors) { if(verticalGradients==null) { verticalGradients = new Hashtable(); } String key = name+"" ""+height+"" ""+y; Paint paint = (Paint)verticalGradients.get(key); if(paint==null) { height = Math.max(height, 1); //before a component is laid out, it may be 0x0 BufferedImage bi = new BufferedImage(1,height,BufferedImage.TYPE_INT_ARGB); int[] array = new int[height]; for(int a = 0; a=positions[b-1] && f checkers; public static TexturePaint getCheckerBoard(int checkerSize) { if(checkers==null) checkers = new Hashtable(); Integer key = new Integer(checkerSize); TexturePaint paint = (TexturePaint)checkers.get(key); if(paint==null) { BufferedImage bi = new BufferedImage(2*checkerSize, 2*checkerSize, BufferedImage.TYPE_INT_RGB); Graphics2D g = bi.createGraphics(); g.setColor(Color.white); g.fillRect(0,0,2*checkerSize,2*checkerSize); g.setColor(Color.lightGray); g.fillRect(0,0,checkerSize,checkerSize); g.fillRect(checkerSize,checkerSize,checkerSize,checkerSize); g.dispose(); paint = new TexturePaint(bi,new Rectangle(0,0,bi.getWidth(),bi.getHeight())); checkers.put(key, paint); } return paint; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/colorpicker/plaf/FocusArrowListener.java",".java","5784","162","/* * @(#)FocusArrowListener.java * * $Date: 2011-02-24 00:42:26 -0600 (Thu, 24 Feb 2011) $ * * Copyright (c) 2011 by Jeremy Wood. * All rights reserved. * * The copyright of this software is owned by Jeremy Wood. * You may not use, copy or modify this software, except in * accordance with the license agreement you entered into with * Jeremy Wood. For details see accompanying license terms. * * This software is probably, but not necessarily, discussed here: * http://javagraphics.java.net/ * * That site should also contain the most recent official version * of this software. (See the SVN repository for more details.) */ package colorpicker.plaf; import java.awt.Component; import java.awt.Container; import java.awt.FocusTraversalPolicy; import java.awt.Point; import java.awt.Window; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.util.HashSet; import java.util.Set; import javax.swing.JPanel; import javax.swing.SwingUtilities; /** This listens for arrow keys and shifts * the keyboard focus accordingly. * So if you press the left arrow key, the component * to the left of the source component requests the focus. *

    This scans for the first available component whose * isFocusable() method returns true. * If no such component is found: nothing happens. */ public class FocusArrowListener extends KeyAdapter { public void keyPressed(KeyEvent e) { int code = e.getKeyCode(); int dx = 0; int dy = 0; if(code==KeyEvent.VK_LEFT) { dx = -1; } else if(code==KeyEvent.VK_UP) { dy = -1; } else if(code==KeyEvent.VK_RIGHT) { dx = 1; } else if(code==KeyEvent.VK_DOWN) { dy = 1; } if( (dx==0 && dy==0)==false && shiftFocus(dx,dy,(Component)e.getSource())) e.consume(); } /** Shifts the focus in a certain direction. * * @param dx the amount to increment x. * @param dy the amount to increment y. * @param src the source to traverse from. * @return true if another component requested the focus * as a result of this method. This may return false if * no suitable component was found to shift focus to. * (If you press the right arrow key on the right-most * component, for example.) */ public static boolean shiftFocus(int dx,int dy,Component src) { if(dx==0 && dy==0) //this would result in an infinite loop throw new IllegalArgumentException(""dx (""+dx+"") and (""+dy+"") cannot both be zero""); Set focusableComponents = getFocusableComponents(src); int x = src.getWidth()/2; int y = src.getHeight()/2; Window window = SwingUtilities.getWindowAncestor(src); if(window==null) return false; Point p = SwingUtilities.convertPoint(src, x, y, window); Component comp = null; int windowWidth = window.getWidth(); int windowHeight = window.getHeight(); while(p.x>0 && p.x0 && p.yMy first implementation involved of this concept * simply involved asking JCompnonents if they were * focusable, but in the FilledButtonTest this * resulted in shifting focus to the ContentPane. Although * it is technically focusable: if I used the tab key * I did not get this result. So I studied * the inner workings for Component.transferFocus() * and ended up with a method that involved * calls to getFocusCycleRootAncestor(), * and getFocusTraversalPolicy(). *

    (Also credit goes to Werner for originally tipping me off * towards looking at FocusTraversalPolicies.) * @param currentFocusOwner the current focus owner. * @return all the JComponents that can receive the focus. */ public static Set getFocusableComponents(Component currentFocusOwner) { HashSet set = new HashSet(); set.add(currentFocusOwner); Container rootAncestor = currentFocusOwner.getFocusCycleRootAncestor(); Component comp = currentFocusOwner; while (rootAncestor != null && !(rootAncestor.isShowing() && rootAncestor.isFocusable() && rootAncestor.isEnabled())) { comp = rootAncestor; rootAncestor = comp.getFocusCycleRootAncestor(); } if (rootAncestor != null) { FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy(); Component toFocus = policy.getComponentAfter(rootAncestor, comp); // final Component startingPoint = currentFocusOwner; while(toFocus!=null && set.contains(toFocus)==false) { set.add(toFocus); toFocus = policy.getComponentAfter(rootAncestor, toFocus); } toFocus = policy.getComponentBefore(rootAncestor, comp); while(toFocus!=null && set.contains(toFocus)==false) { set.add(toFocus); toFocus = policy.getComponentBefore(rootAncestor, toFocus); } } return set; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/app/SPREADBase.java",".java","2866","100","package test.app; import static org.fest.assertions.Assertions.assertThat; import static org.fest.swing.edt.GuiActionRunner.execute; import static org.fest.swing.finder.JFileChooserFinder.findFileChooser; import java.awt.Dimension; import java.awt.FileDialog; import java.io.File; import javax.swing.JFrame; import org.fest.swing.annotation.RunsInEDT; import org.fest.swing.edt.GuiQuery; import org.fest.swing.edt.GuiTask; import org.fest.swing.fixture.FrameFixture; import org.fest.swing.fixture.JFileChooserFixture; import org.fest.swing.junit.testcase.FestSwingJUnitTestCase; import app.SpreadApp; /** * Basic gui test methods for SPREAD * */ public class SPREADBase extends FestSwingJUnitTestCase { protected FrameFixture spreadFrame; protected SpreadApp spreadApp; protected void onSetUp() { spreadFrame = new FrameFixture(robot(), createNewEditor()); spreadFrame.show(); spreadFrame.resizeTo(new Dimension(1224, 786)); spreadApp = SpreadApp.gui; } @RunsInEDT private static JFrame createNewEditor() { return execute(new GuiQuery() { protected JFrame executeInEDT() throws Throwable { SpreadApp gui = new SpreadApp(); JFrame frame = gui.launchFrame(); return frame; } }); } void warning(String str) { System.err.println(""\n\n=====================================================\n""); System.err.println(str); System.err.println(""\n=====================================================\n\n""); } // for handling file open events on Mac FileDialog fileDlg = null; String _dir; File _file; boolean isMac() { return System.getProperty(""os.name"").toLowerCase().startsWith(""mac os x""); } void importAlignment(String dir, File ... files) { if (!isMac()) { spreadFrame.menuItemWithPath(""File"", ""Import Alignment"").click(); JFileChooserFixture fileChooser = findFileChooser().using(robot()); fileChooser.setCurrentDirectory(new File(dir)); fileChooser.selectFiles(files).approve(); } else { this._dir = dir; for (File file : files) { _file = new File(dir + ""/"" + file.getName()); execute(new GuiTask() { protected void executeInEDT() { try { // spreadApp.doc.importNexus(_file); } catch (Exception e) { e.printStackTrace(); } } }); } } } void assertArrayEquals(Object [] o, String array) { String str = array.substring(1, array.length() - 1); String [] strs = str.split("", ""); for (int i = 0; i < o.length && i < strs.length; i++) { assertThat(strs[i]).as(""expected array value "" + strs[i] + "" instead of "" + o[i].toString()).isEqualTo(o[i].toString()); } assertThat(o.length).as(""arrays do not match: different lengths"").isEqualTo(strs.length); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/app/DiscreteTutorialTest.java",".java","3563","111","package test.app; import static org.fest.assertions.Assertions.assertThat; import static org.fest.swing.finder.JFileChooserFinder.findFileChooser; import java.io.File; import javax.swing.JButton; import org.fest.swing.core.GenericTypeMatcher; import org.fest.swing.fixture.JFileChooserFixture; import org.fest.swing.fixture.JOptionPaneFixture; import org.fest.swing.fixture.JTabbedPaneFixture; import org.fest.swing.image.ScreenshotTaker; import org.junit.Test; public class DiscreteTutorialTest extends SPREADBase { @Test public void testDiscreteTutorial() throws Exception { ScreenshotTaker screenshotTaker = new ScreenshotTaker(); JTabbedPaneFixture f = spreadFrame.tabbedPane(); f.requireVisible(); String[] titles = f.tabTitles(); assertArrayEquals(titles,""[Discrete Tree, Discrete Bayes Factors, Continuous Tree, Time Slicer, Terminal]""); f = f.selectTab(""Discrete Tree""); assertThat(f).isNotNull(); spreadFrame.button(new GenericTypeMatcher(JButton.class, true) { @Override protected boolean isMatching(JButton button) { // return button.getLabel().equals(""Open""); return button.getText().equals(""Open""); } }).click(); JFileChooserFixture fileChooser = findFileChooser().using(robot()); fileChooser.setCurrentDirectory(new File(""src/data/tutorial/phylogeography_discrete"")); fileChooser.selectFile(new File(""H5N1.tree"")).approve(); spreadFrame.comboBox(""state"").selectItem(""location""); spreadFrame.button(new GenericTypeMatcher(JButton.class, true) { @Override protected boolean isMatching(JButton button) { // return button.getLabel().equals(""Setup""); return button.getText().equals(""Setup""); } }).click(); spreadFrame.button(new GenericTypeMatcher(JButton.class, true) { @Override protected boolean isMatching(JButton button) { // return button.getLabel().equals(""Load""); return button.getText().equals(""Load""); } }).click(); fileChooser = findFileChooser().using(robot()); fileChooser.setCurrentDirectory(new File(""src/data/tutorial/phylogeography_discrete"")); fileChooser.selectFile(new File(""H5N1locations.dat"")).approve(); spreadFrame.button(new GenericTypeMatcher(JButton.class, true) { @Override protected boolean isMatching(JButton button) { // return button.getLabel().equals(""Done""); return button.getText().equals(""Done""); } }).click(); spreadFrame.panel(""Output.spinWidget"").click(); spreadFrame.button(new GenericTypeMatcher(JButton.class, true) { @Override protected boolean isMatching(JButton button) { // return button.getLabel().equals(""Plot""); return button.getText().equals(""Plot""); } }).click(); try { JOptionPaneFixture optionPane = new JOptionPaneFixture(robot()); optionPane.okButton().click(); } catch (Exception e) { // ignore } new File(""src/data/tutorial/phylogeography_discrete/output.kml"").delete(); spreadFrame.button(new GenericTypeMatcher(JButton.class, true) { @Override protected boolean isMatching(JButton button) { // return button.getLabel().equals(""Generate""); return button.getText().equals(""Generate""); } }).click(); Thread.sleep(300); if (!(new File(""src/data/tutorial/phylogeography_discrete/output.kml"").exists())) { throw new Exception(""Expected file output.kml to be generated""); } new File(""SPREADdiscrete.png"").delete(); screenshotTaker.saveComponentAsPng(spreadFrame.target, ""SPREADdiscrete.png""); } // testDiscreteTutorial } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/app/ContinuousTutorialTest.java",".java","1957","58","package test.app; import static org.fest.assertions.Assertions.assertThat; import static org.fest.swing.finder.JFileChooserFinder.findFileChooser; import java.io.File; import javax.swing.JButton; import org.fest.swing.core.GenericTypeMatcher; import org.fest.swing.fixture.JFileChooserFixture; import org.fest.swing.fixture.JTabbedPaneFixture; import org.fest.swing.image.ScreenshotTaker; import org.junit.Test; public class ContinuousTutorialTest extends SPREADBase { @Test public void testContinuousTutorial() throws Exception { ScreenshotTaker screenshotTaker = new ScreenshotTaker(); JTabbedPaneFixture f = spreadFrame.tabbedPane(); f.requireVisible(); String[] titles = f.tabTitles(); assertArrayEquals(titles,""[Discrete Tree, Discrete Bayes Factors, Continuous Tree, Time Slicer, Terminal]""); f = f.selectTab(""Continuous Tree""); assertThat(f).isNotNull(); spreadFrame.button(new GenericTypeMatcher(JButton.class, true) { @Override protected boolean isMatching(JButton button) { // return button.getLabel().equals(""Open""); return button.getText().equals(""Open""); } }).click(); JFileChooserFixture fileChooser = findFileChooser().using(robot()); fileChooser.setCurrentDirectory(new File(""src/data/tutorial/phylogeography_continuous"")); fileChooser.selectFile(new File(""RacRABV.tree"")).approve(); spreadFrame.comboBox(""latitudeComboBox"").selectItem(""location.location1""); spreadFrame.comboBox(""longitudeComboBox"").selectItem(""location.location2""); spreadFrame.panel(""Output.spinWidget"").click(); spreadFrame.button(new GenericTypeMatcher(JButton.class, true) { @Override protected boolean isMatching(JButton button) { // return button.getLabel().equals(""Plot""); return button.getText().equals(""Plot""); } }).click(); new File(""SPREADcontinuous.png"").delete(); screenshotTaker.saveComponentAsPng(spreadFrame.target, ""SPREADcontinuous.png""); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/app/TinyTest.java",".java","141","13","package test.app; import org.junit.Test; public class TinyTest extends SPREADBase { @Test public void testThatAppLaunches() { } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/templates/RateIndicatorBFToKMLTest.java",".java","2404","91","package test.templates; import org.junit.Test; import junit.framework.TestCase; import gui.InteractiveTableModel; import gui.LocationCoordinatesEditor; import gui.TableRecord; import readers.LocationsReader; import templates.RateIndicatorBFToKML; public class RateIndicatorBFToKMLTest extends TestCase { @Test public void testRateIndicatorBFToKML() throws Exception { RateIndicatorBFToKML rateIndicatorBFToKML = new RateIndicatorBFToKML(); InteractiveTableModel table; LocationsReader data; System.out .println(""Command line mode is experimental. Expect the unexpected.""); table = new InteractiveTableModel(new LocationCoordinatesEditor(null) .getColumnNames()); data = new LocationsReader( TestUtils.getResourcePath(""/data/locationCoordinates_H5N1"")); String indicatorAttributeName = ""indicator""; for (int i = 0; i < data.nrow; i++) { String name = String.valueOf(data.locations[i]); String longitude = String.valueOf(data.coordinates[i][0]); String latitude = String.valueOf(data.coordinates[i][1]); table.insertRow(i, new TableRecord(name, longitude, latitude)); }// END: row loop rateIndicatorBFToKML.setTable(table); rateIndicatorBFToKML .setLogFileParser( TestUtils.getResourcePath(""/data/H5N1_HA_discrete_rateMatrix.log""), 0.1, indicatorAttributeName); rateIndicatorBFToKML.setBfCutoff(3.0); rateIndicatorBFToKML.setMaxAltitudeMapping(50000); rateIndicatorBFToKML.setNumberOfIntervals(100); rateIndicatorBFToKML.setDefaultMeanPoissonPrior(); rateIndicatorBFToKML.setDefaultPoissonPriorOffset(); rateIndicatorBFToKML .setKmlWriterPath(""output.kml""); rateIndicatorBFToKML.setMinBranchRedMapping(255); rateIndicatorBFToKML.setMinBranchGreenMapping(100); rateIndicatorBFToKML.setMinBranchBlueMapping(255); rateIndicatorBFToKML.setMinBranchOpacityMapping(255); rateIndicatorBFToKML.setMaxBranchRedMapping(25); rateIndicatorBFToKML.setMaxBranchGreenMapping(25); rateIndicatorBFToKML.setMaxBranchBlueMapping(25); rateIndicatorBFToKML.setMaxBranchOpacityMapping(255); rateIndicatorBFToKML.setBranchWidth(4); rateIndicatorBFToKML.GenerateKML(); System.out.println(""Finished in: "" + RateIndicatorBFToKML.time + "" msec \n""); // force quit //System.exit(0); }// END: RateIndicatorBFToKMLTest }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/templates/ContinuousTreeToKMLTest.java",".java","1986","76","package test.templates; import org.junit.Test; import templates.ContinuousTreeToKML; public class ContinuousTreeToKMLTest extends TestUtils { @Test public void testContinuousTreeToKML() throws Exception { ContinuousTreeToKML continuousTreeToKML = new ContinuousTreeToKML(); continuousTreeToKML.setMrsdString(""2011-07-28 AD""); continuousTreeToKML .setTreePath(TestUtils.getResourcePath(""/data/WNV_relaxed_geo_gamma_MCC.tre"")); continuousTreeToKML.setHPDString(""80%HPD""); continuousTreeToKML.setLatitudeName(""location1""); continuousTreeToKML.setLongitudeName(""location2""); continuousTreeToKML.setMaxAltitudeMapping(50000); continuousTreeToKML.setMinPolygonRedMapping(100); continuousTreeToKML.setMinPolygonGreenMapping(255); continuousTreeToKML.setMinPolygonBlueMapping(255); continuousTreeToKML.setMinPolygonOpacityMapping(255); continuousTreeToKML.setMaxPolygonRedMapping(255); continuousTreeToKML.setMaxPolygonGreenMapping(255); continuousTreeToKML.setMaxPolygonBlueMapping(25); continuousTreeToKML.setMaxPolygonOpacityMapping(255); continuousTreeToKML.setMinBranchRedMapping(255); continuousTreeToKML.setMinBranchGreenMapping(100); continuousTreeToKML.setMinBranchBlueMapping(255); continuousTreeToKML.setMinBranchOpacityMapping(255); continuousTreeToKML.setMaxBranchRedMapping(25); continuousTreeToKML.setMaxBranchGreenMapping(25); continuousTreeToKML.setMaxBranchBlueMapping(25); continuousTreeToKML.setMaxBranchOpacityMapping(255); continuousTreeToKML.setBranchWidth(4); continuousTreeToKML.setTimescaler(1); continuousTreeToKML.setNumberOfIntervals(100); // continuousTreeToKML.setKmlWriterPath(""/home/filip/output.kml""); continuousTreeToKML.setKmlWriterPath(""output.kml""); continuousTreeToKML.GenerateKML(); System.out.println(""Finished in: "" + continuousTreeToKML.time + "" msec \n""); }// END: ContinuousTreeToKMLTest }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/templates/SpatialStatsToTerminalTest.java",".java","1437","51","package test.templates; import org.junit.Test; import junit.framework.TestCase; import templates.SpatialStatsToTerminal; public class SpatialStatsToTerminalTest extends TestCase { @Test public static void testSpatialStatsToTerminal() throws Exception { boolean FIRST_ANALYSIS = false; SpatialStatsToTerminal spatialStatsToTerminal = new SpatialStatsToTerminal(); if(FIRST_ANALYSIS) { spatialStatsToTerminal.setAnalysisType(SpatialStatsToTerminal.FIRST_ANALYSIS); spatialStatsToTerminal.setTreePath(TestUtils.getResourcePath(""/data/Cent_ITS_broad.tree"")); spatialStatsToTerminal.setNumberOfIntervals(10); } else { spatialStatsToTerminal.setAnalysisType(SpatialStatsToTerminal.SECOND_ANALYSIS); spatialStatsToTerminal.setCustomSliceHeightsPath(TestUtils.getResourcePath(""src/data/treeslice_small.txt"")); // spatialStatsToTerminal.setCustomSliceHeightsPath(""/home/filip/Dropbox/SPREAD_dev/CustomTimeSlicing/zeroSlice.txt""); } spatialStatsToTerminal.setTreesPath(TestUtils.getResourcePath(""src/data/Cent_ITS_small.trees"")); spatialStatsToTerminal.setBurnIn(0); spatialStatsToTerminal.setLocationAttributeName(""coords""); spatialStatsToTerminal.setRateAttributeName(""rate""); spatialStatsToTerminal.setPrecisionAttName(""precision""); spatialStatsToTerminal.setUseTrueNoise(false); spatialStatsToTerminal.calculate(); }//END: main }//END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/templates/TestUtils.java",".java","594","28","package test.templates; import java.net.URL; import junit.framework.TestCase; import app.SpreadApp; public class TestUtils extends TestCase { public static String getResourcePath(String resource) throws Exception { URL url = SpreadApp.class.getResource(resource); if (url == null) { url = SpreadApp.class.getResource(""/src/"" + resource); } if (url == null) { throw new Exception (""Resource "" + resource + "" not found""); } String path = url.getPath(); return path; } public static void main(String args[]) { org.junit.runner.JUnitCore.main(args[0]); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/templates/TimeSlicerToKMLTest.java",".java","2417","102","package test.templates; import org.junit.Test; import junit.framework.TestCase; import templates.TimeSlicerToKML; public class TimeSlicerToKMLTest extends TestCase { @Test public void testTimeSlicerToKML() throws Exception { TimeSlicerToKML timeSlicerToKML = new TimeSlicerToKML(); boolean FIRST_ANALYSIS = true; if(FIRST_ANALYSIS) { timeSlicerToKML.setAnalysisType(TimeSlicerToKML.FIRST_ANALYSIS); timeSlicerToKML.setTreePath(TestUtils.getResourcePath(""/data/WNV_relaxed_geo_gamma_MCC.tre"")); timeSlicerToKML.setNumberOfIntervals(10); } else { timeSlicerToKML.setAnalysisType(TimeSlicerToKML.SECOND_ANALYSIS); timeSlicerToKML.setCustomSliceHeightsPath(TestUtils.getResourcePath(""/data/treeslice_WNV.txt"")); } timeSlicerToKML.setTreesPath(TestUtils.getResourcePath(""/data/WNV_relaxed_geo_gamma.trees"")); timeSlicerToKML.setBurnIn(0); timeSlicerToKML.setLocationAttributeName(""location""); timeSlicerToKML.setMrsdString(""2012-10-24 AD""); timeSlicerToKML.setHPD(0.80); timeSlicerToKML.setGridSize(100); timeSlicerToKML.setRateAttributeName(""rate""); timeSlicerToKML.setPrecisionAttName(""precision""); timeSlicerToKML.setUseTrueNoise(true); timeSlicerToKML.setTimescaler(1); timeSlicerToKML.setKmlWriterPath(""output_custom.kml""); timeSlicerToKML.setMinPolygonRedMapping(0); timeSlicerToKML.setMinPolygonGreenMapping(0); timeSlicerToKML.setMinPolygonBlueMapping(0); timeSlicerToKML.setMinPolygonOpacityMapping(100); timeSlicerToKML.setMaxPolygonRedMapping(50); timeSlicerToKML.setMaxPolygonGreenMapping(255); timeSlicerToKML.setMaxPolygonBlueMapping(255); timeSlicerToKML.setMaxPolygonOpacityMapping(255); timeSlicerToKML.setMinBranchRedMapping(0); timeSlicerToKML.setMinBranchGreenMapping(0); timeSlicerToKML.setMinBranchBlueMapping(0); timeSlicerToKML.setMinBranchOpacityMapping(255); timeSlicerToKML.setMaxBranchRedMapping(255); timeSlicerToKML.setMaxBranchGreenMapping(5); timeSlicerToKML.setMaxBranchBlueMapping(50); timeSlicerToKML.setMaxBranchOpacityMapping(255); timeSlicerToKML.setMaxAltitudeMapping(500000); timeSlicerToKML.setBranchWidth(4); timeSlicerToKML.GenerateKML(); System.out.println(""Finished in: "" + timeSlicerToKML.time + "" msec \n""); }// END: main }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/test/templates/DiscreteTreeToKMLTest.java",".java","2677","104","package test.templates; import org.junit.Test; import junit.framework.TestCase; import gui.InteractiveTableModel; import gui.LocationCoordinatesEditor; import gui.TableRecord; import readers.LocationsReader; import templates.DiscreteTreeToKML; public class DiscreteTreeToKMLTest extends TestCase { @Test public void testDiscreteTreeToKML() throws Exception { DiscreteTreeToKML discreteTreeToKML = new DiscreteTreeToKML(); InteractiveTableModel table; LocationsReader data; System.out .println(""Command line mode is experimental. Expect the unexpected.""); table = new InteractiveTableModel(new LocationCoordinatesEditor(null) .getColumnNames()); data = new LocationsReader( TestUtils.getResourcePath(""/data/locationCoordinates_H5N1"")); for (int i = 0; i < data.nrow; i++) { String name = String.valueOf(data.locations[i]); String longitude = String.valueOf(data.coordinates[i][0]); String latitude = String.valueOf(data.coordinates[i][1]); table.insertRow(i, new TableRecord(name, longitude, latitude)); }// END: row loop discreteTreeToKML .setTreePath(TestUtils.getResourcePath(""/data/H5N1_HA_discrete_MCC.tre"")); discreteTreeToKML.setTimescaler(1); discreteTreeToKML.setMrsdString(""2011-07-28 AD""); discreteTreeToKML.setTable(table); discreteTreeToKML.setStateAttName(""states""); discreteTreeToKML.setMaxAltitudeMapping(5000000); discreteTreeToKML.setNumberOfIntervals(100); discreteTreeToKML.setPolygonsRadiusMultiplier(1); discreteTreeToKML.setMinPolygonRedMapping(0); discreteTreeToKML.setMinPolygonGreenMapping(0); discreteTreeToKML.setMinPolygonBlueMapping(0); discreteTreeToKML.setMinPolygonOpacityMapping(100); discreteTreeToKML.setMaxPolygonRedMapping(50); discreteTreeToKML.setMaxPolygonGreenMapping(255); discreteTreeToKML.setMaxPolygonBlueMapping(255); discreteTreeToKML.setMaxPolygonOpacityMapping(255); discreteTreeToKML.setMinBranchRedMapping(0); discreteTreeToKML.setMinBranchGreenMapping(0); discreteTreeToKML.setMinBranchBlueMapping(0); discreteTreeToKML.setMinBranchOpacityMapping(255); discreteTreeToKML.setMaxBranchRedMapping(255); discreteTreeToKML.setMaxBranchGreenMapping(5); discreteTreeToKML.setMaxBranchBlueMapping(50); discreteTreeToKML.setMaxBranchOpacityMapping(255); discreteTreeToKML.setBranchWidth(4); discreteTreeToKML.setKmlWriterPath(""output.kml""); discreteTreeToKML.GenerateKML(); System.out.println(""Finished in: "" + discreteTreeToKML.time + "" msec \n""); // force quit //System.exit(0); }// END: DiscreteTreeToKMLTest }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/TimeSlicerToKML.java",".java","15495","585","package templates; import generator.KMLGenerator; import java.awt.Color; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.io.TreeImporter; import jebl.evolution.trees.RootedTree; import readers.SliceHeightsReader; import structure.Coordinates; import structure.Layer; import structure.Line; import structure.Polygon; import structure.Style; import structure.TimeLine; import utils.ThreadLocalSpreadDate; import utils.Utils; import contouring.ContourMaker; import contouring.ContourPath; import contouring.ContourWithSynder; public class TimeSlicerToKML { private int analysisType; public final static int FIRST_ANALYSIS = 1; public final static int SECOND_ANALYSIS = 2; public long time; // // how many days one year holds // private static final int DaysInYear = 365; // Concurrency stuff private ConcurrentMap> slicesMap; private RootedTree currentTree; private TreeImporter treeImporter; private RootedTree tree; private int numberOfIntervals; private double[] sliceHeights; private double maxAltMapping; private double minPolygonRedMapping; private double minPolygonGreenMapping; private double minPolygonBlueMapping; private double minPolygonOpacityMapping; private double maxPolygonRedMapping; private double maxPolygonGreenMapping; private double maxPolygonBlueMapping; private double maxPolygonOpacityMapping; private double minBranchRedMapping; private double minBranchGreenMapping; private double minBranchBlueMapping; private double minBranchOpacityMapping; private double maxBranchRedMapping; private double maxBranchGreenMapping; private double maxBranchBlueMapping; private double maxBranchOpacityMapping; private ThreadLocalSpreadDate mrsd; private double timescaler; private double treeRootHeight; private double branchWidth; private TreeImporter treesImporter; private String mrsdString; private int burnIn; private boolean useTrueNoise; private String coordinatesName; private String longitudeName; private String latitudeName; private String rateString; private String precisionString; private List layers; private SimpleDateFormat formatter; private String kmlPath; private TimeLine timeLine; private double startTime; private double endTime; private double hpd; private int gridSize; public TimeSlicerToKML() { } public void setAnalysisType(int analysisType) { this.analysisType = analysisType; } public void setCustomSliceHeightsPath(String path) { sliceHeights = new SliceHeightsReader(path).getSliceHeights(); } public void setTimescaler(double timescaler) { this.timescaler = timescaler; } public void setHPD(double hpd) { this.hpd = hpd; } public void setGridSize(int gridSize) { this.gridSize = gridSize; } public void setTreePath(String path) throws FileNotFoundException { treeImporter = new NexusImporter(new FileReader(path)); } public void setTreesPath(String path) throws FileNotFoundException { treesImporter = new NexusImporter(new FileReader(path)); } public void setMrsdString(String mrsd) { mrsdString = mrsd; } public void setNumberOfIntervals(int numberOfIntervals) { this.numberOfIntervals = numberOfIntervals; } public void setBurnIn(int burnIn) { this.burnIn = burnIn; } public void setUseTrueNoise(boolean useTrueNoise) { this.useTrueNoise = useTrueNoise; } public void setLocationAttributeName(String name) { coordinatesName = name; longitudeName = (coordinatesName + 2); latitudeName = (coordinatesName + 1); } public void setRateAttributeName(String name) { rateString = name; } public void setPrecisionAttName(String name) { precisionString = name; } public void setKmlWriterPath(String path) throws FileNotFoundException { kmlPath = path; } public void setMaxAltitudeMapping(double max) { maxAltMapping = max; } public void setMinPolygonRedMapping(double min) { minPolygonRedMapping = min; } public void setMinPolygonGreenMapping(double min) { minPolygonGreenMapping = min; } public void setMinPolygonBlueMapping(double min) { minPolygonBlueMapping = min; } public void setMinPolygonOpacityMapping(double min) { minPolygonOpacityMapping = min; } public void setMaxPolygonRedMapping(double max) { maxPolygonRedMapping = max; } public void setMaxPolygonGreenMapping(double max) { maxPolygonGreenMapping = max; } public void setMaxPolygonBlueMapping(double max) { maxPolygonBlueMapping = max; } public void setMaxPolygonOpacityMapping(double max) { maxPolygonOpacityMapping = max; } public void setMinBranchRedMapping(double min) { minBranchRedMapping = min; } public void setMinBranchGreenMapping(double min) { minBranchGreenMapping = min; } public void setMinBranchBlueMapping(double min) { minBranchBlueMapping = min; } public void setMinBranchOpacityMapping(double min) { minBranchOpacityMapping = min; } public void setMaxBranchRedMapping(double max) { maxBranchRedMapping = max; } public void setMaxBranchGreenMapping(double max) { maxBranchGreenMapping = max; } public void setMaxBranchBlueMapping(double max) { maxBranchBlueMapping = max; } public void setMaxBranchOpacityMapping(double max) { maxBranchOpacityMapping = max; } public void setBranchWidth(double width) { branchWidth = width; } public void GenerateKML() throws IOException, ImportException, ParseException, RuntimeException, OutOfMemoryError { // start timing time = -System.currentTimeMillis(); mrsd = new ThreadLocalSpreadDate(mrsdString); switch (analysisType) { case FIRST_ANALYSIS: tree = (RootedTree) treeImporter.importNextTree(); treeRootHeight = Utils.getNodeHeight(tree, tree.getRootNode()); sliceHeights = Utils.generateTreeSliceHeights(treeRootHeight, numberOfIntervals); timeLine = Utils.generateTreeTimeLine(tree, timescaler, numberOfIntervals, mrsd); break; case SECOND_ANALYSIS: timeLine = Utils.generateCustomTimeLine(sliceHeights, timescaler, mrsd); break; } //sort them in ascending numerical order Arrays.sort(sliceHeights); System.out.println(""Using as slice times: ""); Utils.printArray(sliceHeights); System.out.println(); // this is to generate kml output layers = new ArrayList(); // Executor for threads int NTHREDS = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(NTHREDS * 2); int treesAssumed = 10000; int treesRead = 0; System.out.println(""Analyzing trees (bar assumes 10,000 trees)""); System.out .println(""0 25 50 75 100""); System.out .println(""|---------------------|---------------------|---------------------|---------------------|""); // System.out.println(""0 25 50 75 100""); // System.out.println(""|--------------|--------------|--------------|--------------|""); int stepSize = treesAssumed / 60; if (stepSize < 1) { stepSize = 1; } // This is for collecting coordinates into polygons slicesMap = new ConcurrentHashMap>(); int totalTrees = 0; while (treesImporter.hasTree()) { currentTree = (RootedTree) treesImporter.importNextTree(); if (totalTrees >= burnIn) { executor.submit(new AnalyzeTree(currentTree, // precisionString,// coordinatesName, // rateString, // sliceHeights, // timescaler,// mrsd, // slicesMap, // useTrueNoise// )); // new AnalyzeTree(currentTree, // precisionString, coordinatesName, rateString, // sliceHeights, timescaler, mrsd, slicesMap, // useTrueNoise).run(); treesRead += 1; }// END: if burn-in if (totalTrees > 0 && totalTrees % stepSize == 0) { System.out.print(""*""); System.out.flush(); } totalTrees++; }// END: while has trees // Wait until all threads are finished executor.shutdown(); while (!executor.isTerminated()) { } if ((totalTrees - burnIn) <= 0.0) { throw new RuntimeException(""Burnt too many trees!""); } else { System.out.println(""\nAnalyzed "" + treesRead + "" trees with burn-in of "" + burnIn + "" for the total of "" + totalTrees + "" trees""); } System.out.println(""Generating polygons...""); Iterator iterator = slicesMap.keySet().iterator(); executor = Executors.newFixedThreadPool(NTHREDS); formatter = new SimpleDateFormat(""yyyy-MM-dd G"", Locale.US); startTime = timeLine.getStartTime(); endTime = timeLine.getEndTime(); System.out.println(""Iterating through Map...""); int polygonsStyleId = 1; while (iterator.hasNext()) { System.out.println(""Key "" + polygonsStyleId + ""...""); Double sliceTime = iterator.next(); // executor.submit(new Polygons(sliceTime, polygonsStyleId)); new Polygons(sliceTime, polygonsStyleId).run(); polygonsStyleId++; }// END: while has next switch (analysisType) { case FIRST_ANALYSIS: System.out.println(""Generating branches...""); executor.submit(new Branches()); break; case SECOND_ANALYSIS: break; } executor.shutdown(); while (!executor.isTerminated()) { } System.out.println(""Writing to kml...""); PrintWriter writer = new PrintWriter(kmlPath); KMLGenerator kmloutput = new KMLGenerator(); kmloutput.generate(writer, timeLine, layers); // stop timing time += System.currentTimeMillis(); }// END: GenerateKML // /////////////////////////// // ---CONCURRENT POLYGONS---// // /////////////////////////// public class Polygons implements Runnable { private double sliceTime; private int polygonsStyleId; public Polygons(Double sliceTime, int polygonsStyleId) { this.sliceTime = sliceTime; this.polygonsStyleId = polygonsStyleId; } public void run() throws OutOfMemoryError { Layer polygonsLayer = new Layer(""Time_Slice_"" + formatter.format(sliceTime), null); /** * Color and Opacity mapping * */ int red = (int) Utils.map(sliceTime, startTime, endTime, minPolygonRedMapping, maxPolygonRedMapping); int green = (int) Utils.map(sliceTime, startTime, endTime, minPolygonGreenMapping, maxPolygonGreenMapping); int blue = (int) Utils.map(sliceTime, startTime, endTime, minPolygonBlueMapping, maxPolygonBlueMapping); int alpha = (int) Utils.map(sliceTime, startTime, endTime, maxPolygonOpacityMapping, minPolygonOpacityMapping); // System.out.println(""sliceTime: "" + sliceTime + "" startTime: "" + // startTime + "" endTime: "" + endTime); // System.out.println(""red: "" + red + "" green: "" + green + "" blue: "" // + blue); Color color = new Color(red, green, blue, alpha); Style polygonsStyle = new Style(color, 0); polygonsStyle.setId(""polygon_style"" + polygonsStyleId); List list = slicesMap.get(sliceTime); double[] x = new double[list.size()]; double[] y = new double[list.size()]; for (int i = 0; i < list.size(); i++) { if (list.get(i) == null) { System.out.println(""null found""); } x[i] = list.get(i).getLatitude(); y[i] = list.get(i).getLongitude(); } ContourMaker contourMaker = new ContourWithSynder(x, y, gridSize); ContourPath[] paths = contourMaker.getContourPaths(hpd); int pathCounter = 1; for (ContourPath path : paths) { double[] latitude = path.getAllX(); double[] longitude = path.getAllY(); List coords = new ArrayList(); for (int i = 0; i < latitude.length; i++) { coords.add(new Coordinates(longitude[i], latitude[i], 0.0)); } polygonsLayer.addItem(new Polygon(""HPDRegion_"" + pathCounter, // name coords, // List polygonsStyle, // Style style sliceTime, // double startime 0.0 // double duration )); pathCounter++; }// END: paths loop layers.add(polygonsLayer); slicesMap.remove(sliceTime); }// END: run }// END: Polygons // /////////////////////////// // ---CONCURRENT BRANCHES---// // /////////////////////////// private class Branches implements Runnable { public void run() { try { double treeHeightMax = Utils.getTreeHeightMax(tree); // this is for Branches folder: String branchesDescription = null; Layer branchesLayer = new Layer(""Branches"", branchesDescription); int branchStyleId = 1; for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { Double longitude = (Double) node .getAttribute(longitudeName); Double latitude = (Double) node .getAttribute(latitudeName); Double nodeHeight = Utils.getNodeHeight(tree, node); Node parentNode = tree.getParent(node); Double parentLongitude = (Double) parentNode .getAttribute(longitudeName); Double parentLatitude = (Double) parentNode .getAttribute(latitudeName); Double parentHeight = Utils.getNodeHeight(tree, parentNode); if (longitude != null && latitude != null && parentLongitude != null && parentLatitude != null) { /** * Mapping * */ double maxAltitude = Utils.map(nodeHeight, 0, treeHeightMax, 0, maxAltMapping); int red = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchRedMapping, maxBranchRedMapping); int green = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchGreenMapping, maxBranchGreenMapping); int blue = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchBlueMapping, maxBranchBlueMapping); int alpha = (int) Utils.map(nodeHeight, 0, treeHeightMax, maxBranchOpacityMapping, minBranchOpacityMapping); Color col = new Color(red, green, blue, alpha); Style linesStyle = new Style(col, branchWidth); linesStyle.setId(""branch_style"" + branchStyleId); branchStyleId++; double startTime = mrsd.minus((int) (nodeHeight * Utils.DAYS_IN_YEAR * timescaler)); double endTime = mrsd.minus((int) (parentHeight * Utils.DAYS_IN_YEAR * timescaler)); branchesLayer.addItem(new Line((parentLongitude + "","" + parentLatitude + "":"" + longitude + "","" + latitude), // name new Coordinates(parentLongitude, parentLatitude), // startCoords startTime, // double startime linesStyle, // style startstyle new Coordinates(longitude, latitude), // endCoords endTime, // double endtime linesStyle, // style endstyle maxAltitude, // double maxAltitude 0.0) // double duration ); }// END: null checks }// END: root check }// END: node loop layers.add(branchesLayer); } catch (RuntimeException e) { e.printStackTrace(); } }// END: run }// END: Branches class }// END: class","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/SpatialStatsToTerminal.java",".java","4976","188","package templates; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import readers.SliceHeightsReader; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.io.TreeImporter; import jebl.evolution.trees.RootedTree; import utils.Utils; public class SpatialStatsToTerminal { public long time; private int analysisType; public final static int FIRST_ANALYSIS = 1; public final static int SECOND_ANALYSIS = 2; private RootedTree tree; private double treeRootHeight; private double[] sliceHeights; private int numberOfIntervals; private TreeImporter treeImporter; private TreeImporter treesImporter; private RootedTree currentTree; private int burnIn; private boolean useTrueNoise; private String coordinatesName; private String rateString; private String precisionString; public SpatialStatsToTerminal() { }// END: Constructor public void setAnalysisType(int analysisType) { this.analysisType = analysisType; } public void setNumberOfIntervals(int numberOfIntervals) { this.numberOfIntervals = numberOfIntervals; } public void setTreePath(String path) throws FileNotFoundException { treeImporter = new NexusImporter(new FileReader(path)); } public void setTreesPath(String path) throws FileNotFoundException { treesImporter = new NexusImporter(new FileReader(path)); } public void setBurnIn(int burnIn) { this.burnIn = burnIn; } public void setLocationAttributeName(String name) { coordinatesName = name; } public void setRateAttributeName(String name) { rateString = name; } public void setPrecisionAttName(String name) { precisionString = name; } public void setUseTrueNoise(boolean useTrueNoise) { this.useTrueNoise = useTrueNoise; } public void setCustomSliceHeightsPath(String path) { sliceHeights = new SliceHeightsReader(path).getSliceHeights(); } public void calculate() { try { // start timing time = -System.currentTimeMillis(); switch (analysisType) { case FIRST_ANALYSIS: tree = (RootedTree) treeImporter.importNextTree(); treeRootHeight = Utils.getNodeHeight(tree, tree.getRootNode()); sliceHeights = Utils.generateTreeSliceHeights(treeRootHeight, numberOfIntervals); break; case SECOND_ANALYSIS: break; }// END: switch on analysisType // sort them in ascending numerical order Arrays.sort(sliceHeights); System.out.println(""Using as slice times: ""); Utils.printArray(sliceHeights); System.out.println(); // Executor for threads int NTHREDS = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(NTHREDS * 2); int treesAssumed = 10000; int treesRead = 0; System.out.println(""Analyzing trees (bar assumes 10,000 trees)""); System.out.println(""0 25 50 75 100""); System.out.println(""|---------------------|---------------------|---------------------|---------------------|""); // System.out.println(""0 25 50 75 100""); // System.out.println(""|--------------|--------------|--------------|--------------|""); int stepSize = treesAssumed / 60; if (stepSize < 1) { stepSize = 1; } int totalTrees = 0; List treesRatesList = new ArrayList(); while (treesImporter.hasTree()) { currentTree = (RootedTree) treesImporter.importNextTree(); if (totalTrees >= burnIn) { CalculateTreeSpatialStats calculateTreeSpatialStats = new CalculateTreeSpatialStats(currentTree,// coordinatesName, // rateString, // precisionString,// sliceHeights, // useTrueNoise // ); calculateTreeSpatialStats.run(); // executor.submit(calculateTreeSpatialStats); treesRatesList.add(calculateTreeSpatialStats.getTreeRate()); treesRead += 1; }// END: if burn-in if (totalTrees > 0 && totalTrees % stepSize == 0) { System.out.print(""*""); System.out.flush(); } totalTrees++; }// END: while has trees // Wait until all threads are finished executor.shutdown(); while (!executor.isTerminated()) { } if ((totalTrees - burnIn) <= 0.0) { throw new RuntimeException(""Burnt too many trees!""); } else { System.out.println(""\nAnalyzed "" + treesRead + "" trees with burn-in of "" + burnIn + "" for the total of "" + totalTrees + "" trees""); } // System.out.println(""rate statistic: ""); // stop timing time += System.currentTimeMillis(); } catch (IOException e) { e.printStackTrace(); } catch (ImportException e) { e.printStackTrace(); }// END: try-catch block }// END: calculate }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/ContinuousTreeToProcessing.java",".java","7888","313","package templates; import java.io.FileReader; import java.io.IOException; import java.util.List; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.io.TreeImporter; import jebl.evolution.trees.RootedTree; import processing.core.PApplet; import structure.Coordinates; import utils.Utils; @SuppressWarnings(""serial"") public class ContinuousTreeToProcessing extends PApplet { private TreeImporter importer; private RootedTree tree; private String longitudeName; private String latitudeName; private double treeHeightMax; private String HPDString; private MapBackground mapBackground; private double minPolygonRedMapping; private double minPolygonGreenMapping; private double minPolygonBlueMapping; private double minPolygonOpacityMapping; private double maxPolygonRedMapping; private double maxPolygonGreenMapping; private double maxPolygonBlueMapping; private double maxPolygonOpacityMapping; private double minBranchRedMapping; private double minBranchGreenMapping; private double minBranchBlueMapping; private double minBranchOpacityMapping; private double maxBranchRedMapping; private double maxBranchGreenMapping; private double maxBranchBlueMapping; private double maxBranchOpacityMapping; private double branchWidth; // min/max longitude private float minX, maxX; // min/max latitude private float minY, maxY; public ContinuousTreeToProcessing() { }// END:ContinuousTreeToProcessing public void setHPDString(String HPDString) { this.HPDString = HPDString; } public void setLongitudeName(String name) { longitudeName = name; } public void setLatitudeName(String name) { latitudeName = name; } public void setTreePath(String path) throws IOException, ImportException { importer = new NexusImporter(new FileReader(path)); tree = (RootedTree) importer.importNextTree(); // this is for mappings treeHeightMax = Utils.getTreeHeightMax(tree); } public void setMinPolygonRedMapping(double min) { minPolygonRedMapping = min; } public void setMinPolygonGreenMapping(double min) { minPolygonGreenMapping = min; } public void setMinPolygonBlueMapping(double min) { minPolygonBlueMapping = min; } public void setMinPolygonOpacityMapping(double min) { minPolygonOpacityMapping = min; } public void setMaxPolygonRedMapping(double max) { maxPolygonRedMapping = max; } public void setMaxPolygonGreenMapping(double max) { maxPolygonGreenMapping = max; } public void setMaxPolygonBlueMapping(double max) { maxPolygonBlueMapping = max; } public void setMaxPolygonOpacityMapping(double max) { maxPolygonOpacityMapping = max; } public void setMinBranchRedMapping(double min) { minBranchRedMapping = min; } public void setMinBranchGreenMapping(double min) { minBranchGreenMapping = min; } public void setMinBranchBlueMapping(double min) { minBranchBlueMapping = min; } public void setMinBranchOpacityMapping(double min) { minBranchOpacityMapping = min; } public void setMaxBranchRedMapping(double max) { maxBranchRedMapping = max; } public void setMaxBranchGreenMapping(double max) { maxBranchGreenMapping = max; } public void setMaxBranchBlueMapping(double max) { maxBranchBlueMapping = max; } public void setMaxBranchOpacityMapping(double max) { maxBranchOpacityMapping = max; } public void setBranchWidth(double width) { branchWidth = width; } public void setup() { minX = -180; maxX = 180; minY = -90; maxY = 90; mapBackground = new MapBackground(this); }// END:setup public void draw() { smooth(); mapBackground.drawMapBackground(); drawPolygons(); drawBranches(); }// END:draw // //////////////// // ---BRANCHES---// // //////////////// private void drawBranches() { strokeWeight((float) branchWidth); for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { Double longitude = (Double) node.getAttribute(longitudeName); Double latitude = (Double) node.getAttribute(latitudeName); Double nodeHeight = Utils.getNodeHeight(tree, node); Node parentNode = tree.getParent(node); Double parentLongitude = (Double) parentNode .getAttribute(longitudeName); Double parentLatitude = (Double) parentNode .getAttribute(latitudeName); if (longitude != null && latitude != null && parentLongitude != null && parentLatitude != null) { // Equirectangular projection: double x0 = Utils .map(parentLongitude, minX, maxX, 0, width); double y0 = Utils .map(parentLatitude, maxY, minY, 0, height); double x1 = Utils.map(longitude, minX, maxX, 0, width); double y1 = Utils.map(latitude, maxY, minY, 0, height); /** * Color mapping * */ int red = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchRedMapping, maxBranchRedMapping); int green = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchGreenMapping, maxBranchGreenMapping); int blue = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchBlueMapping, maxBranchBlueMapping); int alpha = (int) Utils.map(nodeHeight, 0, treeHeightMax, maxBranchOpacityMapping, minBranchOpacityMapping); stroke(red, green, blue, alpha); line((float) x0, (float) y0, (float) x1, (float) y1); }// END: null check }// END: root check }// END: nodes loop }// END: DrawBranches // //////////////// // ---POLYGONS---// // //////////////// private void drawPolygons() { String modalityAttributeName = Utils.getModalityAttributeName(longitudeName, HPDString); for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { if (!tree.isExternal(node)) { Integer modality = (Integer) node .getAttribute(modalityAttributeName); if (modality != null) { for (int i = 1; i <= modality; i++) { Object[] longitudeHPD = Utils .getObjectArrayNodeAttribute(node, longitudeName + ""_"" + HPDString + ""_"" + i); Object[] latitudeHPD = Utils .getObjectArrayNodeAttribute(node, latitudeName + ""_"" + HPDString + ""_"" + i); /** * Color mapping * */ double nodeHeight = Utils.getNodeHeight(tree, node); int red = (int) Utils.map(nodeHeight, 0, treeHeightMax, minPolygonRedMapping, maxPolygonRedMapping); int green = (int) Utils.map(nodeHeight, 0, treeHeightMax, minPolygonGreenMapping, maxPolygonGreenMapping); int blue = (int) Utils.map(nodeHeight, 0, treeHeightMax, minPolygonBlueMapping, maxPolygonBlueMapping); int alpha = (int) Utils.map(nodeHeight, 0, treeHeightMax, maxPolygonOpacityMapping, minPolygonOpacityMapping); stroke(red, green, blue, alpha); fill(red, green, blue, alpha); List coordinates = Utils .parsePolygons(longitudeHPD, latitudeHPD); beginShape(); for (int row = 0; row < coordinates.size() - 1; row++) { double X = Utils.map(coordinates.get(row) .getLongitude(), minX, maxX, 0, width); double Y = Utils.map(coordinates.get(row) .getLatitude(), maxY, minY, 0, height); double XEND = Utils.map(coordinates .get(row + 1).getLongitude(), minX, maxX, 0, width); double YEND = Utils.map((coordinates .get(row + 1).getLatitude()), maxY, minY, 0, height); vertex((float) X, (float) Y); vertex((float) XEND, (float) YEND); }// END: coordinates loop endShape(CLOSE); }// END: modality loop }// END: null check }// END: external node check }// END: root check }// END: node loop }// END: drawPolygons }// END: PlotOnMap class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/BayesFactorTest.java",".java","4106","161","package templates; import gui.InteractiveTableModel; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import readers.LogFileReader; import utils.Holder; import utils.Utils; import utils.Utils.PoissonPriorEnum; /** * Pass by reference * * */ public class BayesFactorTest { private Holder meanPoissonPrior; private Holder poissonPriorOffset; private InteractiveTableModel table; private PoissonPriorEnum meanPoissonPriorSwitcher; private PoissonPriorEnum poissonPriorOffsetSwitcher; private LogFileReader indicators; private ArrayList combin; private ArrayList bayesFactors; private ArrayList posteriorProbabilities; public BayesFactorTest(InteractiveTableModel table, // PoissonPriorEnum meanPoissonPriorSwitcher, // Holder meanPoissonPriorHolder, // PoissonPriorEnum poissonPriorOffsetSwitcher, // Holder poissonPriorOffsetHolder, // LogFileReader indicators, // ArrayList combin, // ArrayList bayesFactors, // ArrayList posteriorProbabilities // ) { this.table = table; this.meanPoissonPriorSwitcher = meanPoissonPriorSwitcher; this.meanPoissonPrior = meanPoissonPriorHolder; this.poissonPriorOffsetSwitcher = poissonPriorOffsetSwitcher; this.poissonPriorOffset = poissonPriorOffsetHolder; this.indicators = indicators; this.combin = combin; this.bayesFactors = bayesFactors; this.posteriorProbabilities = posteriorProbabilities; } public void ComputeBFTest() { int n = table.getRowCount(); switch (meanPoissonPriorSwitcher) { case DEFAULT: meanPoissonPrior.value = Math.log(2); break; case USER: break; } switch (poissonPriorOffsetSwitcher) { case DEFAULT: poissonPriorOffset.value = (double) (n - 1); break; case USER: break; } boolean symmetrical = false; if (indicators.ncol == n * (n - 1)) { symmetrical = false; } else if (indicators.ncol == (n * (n - 1)) / 2) { symmetrical = true; } else { throw new RuntimeException( ""the number of rate indicators does not match the number of locations!""); } String[] locations = table.getColumn(0); for (int row = 0; row < n - 1; row++) { String[] subset = Utils.subset(locations, row, n - row); for (int i = 1; i < subset.length; i++) { combin.add(locations[row] + "":"" + subset[i]); } } if (symmetrical == false) { List combinReverse = new ArrayList(); for (int i = 0; i < combin.size(); i++) { String state = combin.get(i).split("":"")[1]; String parentState = combin.get(i).split("":"")[0]; combinReverse.add(state + "":"" + parentState); } combin.addAll(combinReverse); } double qk = Double.NaN; if (symmetrical) { qk = (meanPoissonPrior.value + poissonPriorOffset.value) / ((n * (n - 1)) / 2); } else { qk = (meanPoissonPrior.value + poissonPriorOffset.value) / ((n * (n - 1)) / 1); } double[] pk = Utils.colMeans(indicators.indicators); double denominator = qk / (1 - qk); for (int row = 0; row < pk.length; row++) { double bf = (pk[row] / (1 - pk[row])) / denominator; if (bf == Double.POSITIVE_INFINITY) { bf = ((pk[row] - (double) (1.0 / indicators.nrow)) / (1 - (pk[row] - (double) (1.0 / indicators.nrow)))) / denominator; System.out.println(""Correcting for infinite bf: "" + bf); }// END: infinite BF check bayesFactors.add(bf); posteriorProbabilities.add(pk[row]); }// END: row loop }// END: ComputeBFTest /** * @return array with sort order indices to be used to print bayesFactors * and combin lists in descending order * */ public Integer[] getSortOrder() { Integer[] sortOrder = new Integer[bayesFactors.size()]; for (int i = 0; i < sortOrder.length; i++) { sortOrder[i] = i; } Arrays.sort(sortOrder, new Comparator() { public int compare(Integer a, Integer b) { return (bayesFactors.get(b) > bayesFactors.get(a)) ? 1 : -1; } }); return sortOrder; }// END: getSortOrder }// END: BayesFactorTest ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/TimeSlicerToTab.java",".java","5280","208","package templates; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentMap; import math.MultivariateNormalDistribution; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.io.TreeImporter; import jebl.evolution.trees.RootedTree; import structure.Coordinates; import utils.Utils; public class TimeSlicerToTab { public static void main(String args[]) { try { Map> slicesMap = new HashMap>(); double[] sliceHeights = new double[] {1,2,3,4,5}; String path=""/home/filip/Dropbox/WNV_drift_hom_het.trees""; TreeImporter treesImporter; treesImporter = new NexusImporter(new FileReader(path)); int totalTrees = 0; while (treesImporter.hasTree()) { RootedTree currentTree = (RootedTree) treesImporter.importNextTree(); double currentTreeNormalization = Utils.getTreeLength(currentTree, currentTree.getRootNode()); double[] precisionArray = Utils.getTreeDoubleArrayAttribute( currentTree, ""precision""); for (Node node : currentTree.getNodes()) { if (!currentTree.isRoot(node)) { Node parentNode = currentTree.getParent(node); double nodeHeight = Utils.getNodeHeight(currentTree, node); double parentHeight = Utils.getNodeHeight(currentTree, parentNode); double trait1 = Utils.getDoubleNodeAttribute(node, ""location.driftModels.1"", 0.0); double parentTrait1 = Utils.getDoubleNodeAttribute(parentNode, ""location.driftModels.1"", 0.0); double trait2 = Utils.getDoubleNodeAttribute(node, ""location.driftModels.2"", 0.0); double parentTrait2 = Utils.getDoubleNodeAttribute(parentNode, ""location.driftModels.2"", 0.0); double[] trait = new double[2]; trait[0] = trait1; trait[1] = trait2; double[] parentTrait = new double[2]; parentTrait[0] = parentTrait1; parentTrait[1] = parentTrait2; double rate = Utils .getDoubleNodeAttribute(node, ""rate""); for (int i = 0; i < sliceHeights.length; i++) { double sliceHeight = sliceHeights[i]; if (nodeHeight < sliceHeight && sliceHeight <= parentHeight) { System.out.println(""HIT""); double[] imputedTrait = imputeValue(trait, parentTrait, sliceHeight, nodeHeight, parentHeight, rate, currentTreeNormalization, precisionArray); Utils.printArray(imputedTrait); // grow map entry if key exists if (slicesMap.containsKey(sliceHeight)) { slicesMap.get(sliceHeight).add( new double[]{imputedTrait[0], // imputedTrait[1] // }); // start new entry if no such key in the map } else { List traits = new ArrayList(); traits.add( new double[]{imputedTrait[0], // imputedTrait[1] // }); slicesMap.put(sliceHeight, traits); }// END: key check }// END: sliceTime check }//END: slices loop }//END: root check }//END: nodes loop }//END: trees loop } catch (Exception e) { e.printStackTrace(); } }//END: main private static double[] imputeValue(double[] trait, double[] parentTrait, double sliceHeight, double nodeHeight, double parentHeight, double rate, double treeNormalization, double[] precisionArray) { int dim = (int) Math.sqrt(1 + 8 * precisionArray.length) / 2; double[][] precision = new double[dim][dim]; int c = 0; for (int i = 0; i < dim; i++) { for (int j = i; j < dim; j++) { precision[j][i] = precision[i][j] = precisionArray[c++] * treeNormalization; } } dim = trait.length; double[] nodeValue = new double[2]; double[] parentValue = new double[2]; for (int i = 0; i < dim; i++) { nodeValue[i] = trait[i]; parentValue[i] = parentTrait[i]; } final double scaledTimeChild = (sliceHeight - nodeHeight) * rate; final double scaledTimeParent = (parentHeight - sliceHeight) * rate; final double scaledWeightTotal = (1.0 / scaledTimeChild) + (1.0 / scaledTimeParent); if (scaledTimeChild == 0) return trait; if (scaledTimeParent == 0) return parentTrait; // Find mean value, weighted average double[] mean = new double[dim]; double[][] scaledPrecision = new double[dim][dim]; for (int i = 0; i < dim; i++) { mean[i] = (nodeValue[i] / scaledTimeChild + parentValue[i] / scaledTimeParent) / scaledWeightTotal; for (int j = i; j < dim; j++) scaledPrecision[j][i] = scaledPrecision[i][j] = precision[i][j] * scaledWeightTotal; } mean = MultivariateNormalDistribution .nextMultivariateNormalPrecision(mean, scaledPrecision); double[] result = new double[dim]; for (int i = 0; i < dim; i++) { result[i] = mean[i]; } return result; }// END: ImputeValue }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/CalculateTreeSpatialStats.java",".java","6956","261","package templates; import java.util.ArrayList; import java.util.List; import jebl.evolution.graphs.Node; import jebl.evolution.trees.RootedTree; import utils.Utils; public class CalculateTreeSpatialStats implements Runnable { private static final boolean DEBUG = true; private RootedTree currentTree; private String coordinatesName; private String rateString; private double[] sliceHeights; private String precisionString; private boolean useTrueNoise; private List timesList; private List distancesList; // private double timesSum = 0.0; // private double distancesSum = 0.0; private double treeRate = 0.0; public CalculateTreeSpatialStats(RootedTree currentTree, String coordinatesName, String rateString, String precisionString, double[] sliceHeights, boolean useTrueNoise) { this.currentTree = currentTree; this.coordinatesName = coordinatesName; this.sliceHeights = sliceHeights; this.rateString = rateString; this.useTrueNoise = useTrueNoise; this.precisionString = precisionString; timesList = new ArrayList(); distancesList = new ArrayList(); }// END: Constructor @Override public void run() { try { // parsed once per analysis int lastSliceNumber = sliceHeights.length - 2; // attributes parsed once per tree double currentTreeNormalization = Utils.getTreeLength(currentTree, currentTree.getRootNode()); double[] precisionArray = Utils.getTreeDoubleArrayAttribute( currentTree, precisionString); for (Node node : currentTree.getNodes()) { if (!currentTree.isRoot(node)) { Node parentNode = currentTree.getParent(node); double nodeHeight = Utils.getNodeHeight(currentTree, node); double parentHeight = Utils.getNodeHeight(currentTree, parentNode); double branchLength = currentTree.getEdgeLength(node, parentNode); double[] location = Utils.getDoubleArrayNodeAttribute(node, coordinatesName); double[] parentLocation = Utils .getDoubleArrayNodeAttribute(parentNode, coordinatesName); double rate = Utils .getDoubleNodeAttribute(node, rateString); if (parentHeight <= sliceHeights[0]) { timesList.add(branchLength); double distance = Utils.rhumbDistance(location[1],// startLon location[0],// startLat parentLocation[1],// endLon parentLocation[0]// endLat ); distancesList.add(distance); } else { // first case: 0-th slice height if (nodeHeight < sliceHeights[0] && sliceHeights[0] <= parentHeight) { timesList.add(sliceHeights[0] - nodeHeight); double[] imputedLocation = Utils.imputeValue( location, parentLocation, sliceHeights[0], nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray); double distance = Utils.rhumbDistance(location[1],// startLon location[0],// startLat imputedLocation[1],// endLon imputedLocation[0]// endLat ); distancesList.add(distance); } else { // do nothing }// END: 0-th slice check // second case: i to i+1 slice for (int i = 1; i <= lastSliceNumber; i++) { if (nodeHeight < sliceHeights[i]) { // full branch length falls into middle slices if (parentHeight <= sliceHeights[i] && sliceHeights[i - 1] < nodeHeight) { timesList.add(branchLength); double distance = Utils.rhumbDistance( location[1],// startLon location[0],// startLat parentLocation[1],// endLon parentLocation[0]// endLat ); distancesList.add(distance); } else { double startTime = Math.max(nodeHeight, sliceHeights[i - 1]); double endTime = Math.min(parentHeight, sliceHeights[i]); if (endTime >= startTime) { timesList.add(endTime - startTime); double[] imputedLocation1 = Utils .imputeValue( location, parentLocation, startTime, nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray); double[] imputedLocation2 = Utils .imputeValue( location, parentLocation, endTime, nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray); double distance = Utils.rhumbDistance( imputedLocation1[1],// startLon imputedLocation1[0],// startLat imputedLocation2[1],// endLon imputedLocation2[0]// endLat ); distancesList.add(distance); }// END: negative times check }// END: full branch in middle slice check }// END: i-th slice check }// END: i loop // third case: last slice height if (parentHeight >= sliceHeights[lastSliceNumber] && sliceHeights[lastSliceNumber] > nodeHeight) { timesList.add(parentHeight - sliceHeights[lastSliceNumber]); double[] imputedLocation = Utils.imputeValue( location, parentLocation, sliceHeights[lastSliceNumber], nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray); double distance = Utils.rhumbDistance( imputedLocation[1],// startLon imputedLocation[0],// startLat parentLocation[1],// endLon parentLocation[0]// endLat ); distancesList.add(distance); } else if (nodeHeight > sliceHeights[lastSliceNumber]) { timesList.add(branchLength); double distance = Utils.rhumbDistance(location[1],// startLon location[0],// startLat parentLocation[1],// endLon parentLocation[0]// endLat ); distancesList.add(distance); } else { // nothing to add }// END: last transition time check }// END: if branch below first transition time bail out if (DEBUG) { if (timesList.size() != distancesList.size()) { System.out.println(""FUBAR""); } } double timesSum = 0.0; double distancesSum = 0.0; for (int i = 0; i < timesList.size(); i++) { timesSum += timesList.get(i); distancesSum += distancesList.get(i); } rate = distancesSum / timesSum; if (DEBUG) { System.out.println(""rate for tree: "" + rate); } }// END: root node check }// END: node loop } catch (Exception e) { e.printStackTrace(); }// END: try-catch block }// END: run public double getTreeRate() { return treeRate; }// END: getTreeDistancesSum }// END: class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/DiscreteTreeToKML.java",".java","15155","577","package templates; import generator.KMLGenerator; import gui.InteractiveTableModel; import java.awt.Color; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.io.TreeImporter; import jebl.evolution.trees.RootedTree; import structure.Coordinates; import structure.Layer; import structure.Line; import structure.Place; import structure.Polygon; import structure.Style; import structure.TimeLine; import utils.ThreadLocalSpreadDate; import utils.Utils; public class DiscreteTreeToKML { public long time; // how many millisecond one day holds private static final int DayInMillis = 86400000; // how many days one year holds private static final int DaysInYear = 365; // Earths radius in km private static final double EarthRadius = 6371; private RootedTree tree; private String stateAttName; private InteractiveTableModel table; private String mrsdString; private ThreadLocalSpreadDate mrsd; private int numberOfIntervals; private int timescaler; private double rootHeight; private List layers; private double maxAltMapping; private double minPolygonRedMapping; private double minPolygonGreenMapping; private double minPolygonBlueMapping; private double minPolygonOpacityMapping; private double maxPolygonRedMapping; private double maxPolygonGreenMapping; private double maxPolygonBlueMapping; private double maxPolygonOpacityMapping; private double minBranchRedMapping; private double minBranchGreenMapping; private double minBranchBlueMapping; private double minBranchOpacityMapping; private double maxBranchRedMapping; private double maxBranchGreenMapping; private double maxBranchBlueMapping; private double maxBranchOpacityMapping; private double polygonsRadiusMultiplier; private double branchWidth; private PrintWriter writer; private TreeImporter importer; private Random generator; public DiscreteTreeToKML() { generator = new Random(); }// END: DiscreteTreeToKML() public void setTimescaler(int timescaler) { this.timescaler = timescaler; } public void setStateAttName(String name) { stateAttName = name; } public void setMrsdString(String mrsd) { mrsdString = mrsd; } public void setNumberOfIntervals(int number) { numberOfIntervals = number; } public void setMaxAltitudeMapping(double max) { maxAltMapping = max; } public void setKmlWriterPath(String kmlpath) throws FileNotFoundException { writer = new PrintWriter(kmlpath); } public void setTreePath(String path) throws FileNotFoundException { importer = new NexusImporter(new FileReader(path)); } public void setTable(InteractiveTableModel tableModel) { table = tableModel; } public void setPolygonsRadiusMultiplier(double multiplier) { polygonsRadiusMultiplier = multiplier; } public void setMinPolygonRedMapping(double min) { minPolygonRedMapping = min; } public void setMinPolygonGreenMapping(double min) { minPolygonGreenMapping = min; } public void setMinPolygonBlueMapping(double min) { minPolygonBlueMapping = min; } public void setMinPolygonOpacityMapping(double min) { minPolygonOpacityMapping = min; } public void setMaxPolygonRedMapping(double max) { maxPolygonRedMapping = max; } public void setMaxPolygonGreenMapping(double max) { maxPolygonGreenMapping = max; } public void setMaxPolygonBlueMapping(double max) { maxPolygonBlueMapping = max; } public void setMaxPolygonOpacityMapping(double max) { maxPolygonOpacityMapping = max; } public void setMinBranchRedMapping(double min) { minBranchRedMapping = min; } public void setMinBranchGreenMapping(double min) { minBranchGreenMapping = min; } public void setMinBranchBlueMapping(double min) { minBranchBlueMapping = min; } public void setMinBranchOpacityMapping(double min) { minBranchOpacityMapping = min; } public void setMaxBranchRedMapping(double max) { maxBranchRedMapping = max; } public void setMaxBranchGreenMapping(double max) { maxBranchGreenMapping = max; } public void setMaxBranchBlueMapping(double max) { maxBranchBlueMapping = max; } public void setMaxBranchOpacityMapping(double max) { maxBranchOpacityMapping = max; } public void setBranchWidth(double width) { branchWidth = width; } public void GenerateKML() throws IOException, ImportException, ParseException, RuntimeException { // start timing time = -System.currentTimeMillis(); tree = (RootedTree) importer.importNextTree(); // this is for time calculations rootHeight = tree.getHeight(tree.getRootNode()); // This is a general time span for the tree mrsd = new ThreadLocalSpreadDate(mrsdString); TimeLine timeLine = new TimeLine(mrsd.getTime() - (rootHeight * DayInMillis * DaysInYear * timescaler), mrsd .getTime(), numberOfIntervals); // this is to generate kml output KMLGenerator kmloutput = new KMLGenerator(); layers = new ArrayList(); // Execute threads final int NTHREDS = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); executor.submit(new Places()); executor.submit(new Branches()); executor.submit(new Circles()); executor.shutdown(); // Wait until all threads are finished while (!executor.isTerminated()) { } // generate kml kmloutput.generate(writer, timeLine, layers); // stop timing time += System.currentTimeMillis(); }// END: GenerateKML // ////////////// // ---PLACES---// // ////////////// private class Places implements Runnable { public void run() { // this is for Places folder: String placesDescription = null; Layer placesLayer = new Layer(""Places"", placesDescription); for (int i = 0; i < table.getRowCount(); i++) { String name = String.valueOf(table.getValueAt(i, 0)); Double longitude = Double.valueOf(String.valueOf(table .getValueAt(i, 2))); Double latitude = Double.valueOf(String.valueOf(table .getValueAt(i, 1))); placesLayer.addItem(new Place(name, null, new Coordinates( longitude, latitude), 0, 0)); } layers.add(placesLayer); } }// END: Places class // //////////////// // ---BRANCHES---// // //////////////// private class Branches implements Runnable { public void run() { try { // this is for Branches folder: String branchesDescription = null; Layer branchesLayer = new Layer(""Branches"", branchesDescription); double treeHeightMax = Utils.getTreeHeightMax(tree); int branchStyleId = 1; for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { String state = getRandomState((String) node .getAttribute(stateAttName), true); Node parentNode = tree.getParent(node); String parentState = getRandomState((String) parentNode .getAttribute(stateAttName), false); if (state != null && parentState != null) { if (!state.toLowerCase().equals( parentState.toLowerCase())) { float longitude = Utils.matchStateCoordinate( table, state, 2); float latitude = Utils.matchStateCoordinate( table, state, 1); float parentLongitude = Utils .matchStateCoordinate(table, parentState, 2); float parentLatitude = Utils .matchStateCoordinate(table, parentState, 1); double nodeHeight = Utils.getNodeHeight(tree, node); double parentHeight = Utils.getNodeHeight(tree, parentNode); /** * altitude mapping * */ double maxAltitude = Utils.map(Utils .rhumbDistance(parentLongitude, parentLatitude, longitude, latitude), 0, EarthRadius, 0, maxAltMapping); /** * Color mapping * */ int red = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchRedMapping, maxBranchRedMapping); int green = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchGreenMapping, maxBranchGreenMapping); int blue = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchBlueMapping, maxBranchBlueMapping); /** * opacity mapping * */ int alpha = (int) Utils.map(nodeHeight, 0, treeHeightMax, maxBranchOpacityMapping, minBranchOpacityMapping); Color col = new Color(red, green, blue, alpha); Style linesStyle = new Style(col, branchWidth); linesStyle .setId(""branch_style"" + branchStyleId); double startTime = mrsd.minus((int) (nodeHeight * DaysInYear * timescaler)); double endTime = mrsd.minus((int) (parentHeight * DaysInYear * timescaler)); // TODO // System.out.println(""*******************************""); // System.out.println(parentState + "":"" + state); // System.out.println(""*******************************""); branchesLayer.addItem(new Line((parentState + "":"" + state), // string name new Coordinates(parentLongitude, parentLatitude), // startcoords startTime, // startime linesStyle, // style startstyle new Coordinates(longitude, latitude), // endcoords endTime, // double endtime linesStyle, // style endstyle maxAltitude, // double maxAltitude 0.0) // double duration ); branchStyleId++; }// END: state and parent state equality check }// END: null check }// END: root check }// END: nodes loop layers.add(branchesLayer); } catch (RuntimeException e) { e.printStackTrace(); } }// END: run }// END Branches class // /////////////// // ---CIRCLES---// // /////////////// private class Circles implements Runnable { public void run() { try { // this is for Circles folder: String circlesDescription = null; Layer circlesLayer = new Layer(""Circles"", circlesDescription); double[][] numberOfLineages = countLineagesHoldingState( numberOfIntervals, rootHeight); double lineagesCountMax = Utils.get2DArrayMax(numberOfLineages); int circleStyleId = 1; for (int i = 0; i < (numberOfIntervals - 1); i++) { for (int j = 0; j < (table.getRowCount()); j++) { if (numberOfLineages[i][j + 1] > 0) { /** * Color mapping * */ int red = (int) Utils.map( numberOfLineages[i][j + 1], 0, lineagesCountMax, minPolygonRedMapping, maxPolygonRedMapping); int green = (int) Utils.map( numberOfLineages[i][j + 1], 0, lineagesCountMax, minPolygonGreenMapping, maxPolygonGreenMapping); int blue = (int) Utils.map( numberOfLineages[i][j + 1], 0, lineagesCountMax, minPolygonBlueMapping, maxPolygonBlueMapping); /** * Opacity mapping * Larger the values more opaque the colors * */ int alpha = (int) Utils.map( numberOfLineages[i][j + 1], 0, lineagesCountMax, maxPolygonOpacityMapping, minPolygonOpacityMapping); Color col = new Color(red, green, blue, alpha); Style circlesStyle = new Style(col, 0); circlesStyle.setId(""circle_style"" + circleStyleId); circleStyleId++; double radius = Math.round(100 * Math .sqrt(numberOfLineages[i][j + 1])) * polygonsRadiusMultiplier; int days = (int) (numberOfLineages[i][0] * DaysInYear * timescaler); double startTime = mrsd.minus(days); // this is to get duration in milliseconds: double duration = ((rootHeight - numberOfLineages[i][0]) / (i + 1)) * DayInMillis; String name = String .valueOf(table.getValueAt(j, 0)); Double longitude = Double.valueOf(String .valueOf(table.getValueAt(j, 1))); Double latitude = Double.valueOf(String .valueOf(table.getValueAt(j, 2))); circlesLayer.addItem(new Polygon(name + ""_"" + radius + ""_"" + ""km"", // String name Utils.generateCircle( // List latitude, // centerLat longitude, // centerLong radius, // radius 36), // numPoints circlesStyle, // Style style startTime, // double startime duration * DaysInYear * timescaler // duration )); } }// END: row loop }// END: col loop layers.add(circlesLayer); } catch (RuntimeException e) { e.printStackTrace(); } }// END: run }// END: Circles class private double[][] countLineagesHoldingState(int numberOfIntervals, double rootHeight) { double delta = rootHeight / numberOfIntervals; double[][] numberOfLineages = new double[(numberOfIntervals - 1)][table .getRowCount() + 1]; for (int i = 0; i < (numberOfIntervals - 1); i++) { numberOfLineages[i][0] = rootHeight - ((i + 1) * delta); } for (int i = 0; i < (numberOfIntervals - 1); i++) { for (int j = 0; j < table.getRowCount(); j++) { int numberOfLineagesOfState = 0; for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { String state = getRandomState((String) node .getAttribute(stateAttName), false); Node parentNode = tree.getParent(node); String parentState = getRandomState((String) parentNode .getAttribute(stateAttName), false); if (state != null && parentState != null) { if ((tree.getHeight(node) <= numberOfLineages[i][0]) && (tree.getHeight(parentNode) > numberOfLineages[i][0])) { String name = String.valueOf(table.getValueAt( j, 0)); if ((state.toLowerCase().equals(parentState .toLowerCase())) && (parentState.toLowerCase() .equals(name.toLowerCase()))) { numberOfLineagesOfState++; }// END: state }// END: height check }// END: null check }// END: root check }// END: node loop numberOfLineages[i][j + 1] = numberOfLineagesOfState; }// END: col loop }// END: row loop return numberOfLineages; }// END: countLineagesHoldingState private String getRandomState(String state, boolean verbose) { // pick always the same states in this run generator.setSeed(time); if (!state.contains(""+"")) {// single state so return state return state; } else {// this breaks ties if (verbose) System.out.println(""Found combined "" + stateAttName + "" attribute: "" + state); state = Utils.pickRand(state.split(""\\+""), generator); if (verbose) System.out.println(""Randomly picking: "" + state); return state; } }// END: getRandomState }// END: DiscreteTreeToKML class","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/TimeSlicerToProcessing.java",".java","14354","545","package templates; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.io.TreeImporter; import jebl.evolution.trees.RootedTree; import processing.core.PApplet; import readers.SliceHeightsReader; import structure.Coordinates; import structure.TimeLine; import utils.ThreadLocalSpreadDate; import utils.Utils; import contouring.ContourMaker; import contouring.ContourPath; import contouring.ContourWithSynder; @SuppressWarnings(""serial"") public class TimeSlicerToProcessing extends PApplet { private int analysisType; public final static int FIRST_ANALYSIS = 1; public final static int SECOND_ANALYSIS = 2; // how many millisecond one day holds private final int DayInMillis = 86400000; // how many days one year holds private static final int DaysInYear = 365; // Concurrency stuff private ConcurrentMap> slicesMap; private RootedTree currentTree; private RootedTree tree; private int numberOfIntervals; private double[] sliceHeights; private double minPolygonRedMapping; private double minPolygonGreenMapping; private double minPolygonBlueMapping; private double minPolygonOpacityMapping; private double maxPolygonRedMapping; private double maxPolygonGreenMapping; private double maxPolygonBlueMapping; private double maxPolygonOpacityMapping; private double minBranchRedMapping; private double minBranchGreenMapping; private double minBranchBlueMapping; private double minBranchOpacityMapping; private double maxBranchRedMapping; private double maxBranchGreenMapping; private double maxBranchBlueMapping; private double maxBranchOpacityMapping; private double branchWidth; private TreeImporter treesImporter; private TreeImporter treeImporter; private double treeRootHeight; private String precisionString; private String coordinatesName; private String longitudeName; private String latitudeName; private String rateString; private boolean useTrueNoise; private String mrsdString; private ThreadLocalSpreadDate mrsd; private double timescaler; private TimeLine timeLine; private double startTime; private double endTime; private double burnIn; private double hpd; private int gridSize; private MapBackground mapBackground; private float minX, maxX; private float minY, maxY; public TimeSlicerToProcessing() { }// END: constructor public void setAnalysisType(int analysisType) { this.analysisType = analysisType; } public void setCustomSliceHeightsPath(String path) { sliceHeights = new SliceHeightsReader(path).getSliceHeights(); } public void setTimescaler(double timescaler) { this.timescaler = timescaler; } public void setHPD(double hpd) { this.hpd = hpd; } public void setGridSize(int gridSize) { this.gridSize = gridSize; } public void setTreePath(String path) throws FileNotFoundException { treeImporter = new NexusImporter(new FileReader(path)); } public void setTreesPath(String path) throws FileNotFoundException { treesImporter = new NexusImporter(new FileReader(path)); } public void setMrsdString(String mrsd) { mrsdString = mrsd; } public void setCoordinatesName(String name) { coordinatesName = name; // this is for coordinate attribute names latitudeName = (coordinatesName + 1); longitudeName = (coordinatesName + 2); } public void setRateAttributeName(String name) { rateString = name; } public void setPrecisionAttributeName(String name) { precisionString = name; } public void setNumberOfIntervals(int number) { numberOfIntervals = number; } public void setBurnIn(double burnIn) { this.burnIn = burnIn; } public void setUseTrueNoise(boolean useTrueNoise) { this.useTrueNoise = useTrueNoise; } public void setMinPolygonRedMapping(double min) { minPolygonRedMapping = min; } public void setMinPolygonGreenMapping(double min) { minPolygonGreenMapping = min; } public void setMinPolygonBlueMapping(double min) { minPolygonBlueMapping = min; } public void setMinPolygonOpacityMapping(double min) { minPolygonOpacityMapping = min; } public void setMaxPolygonRedMapping(double max) { maxPolygonRedMapping = max; } public void setMaxPolygonGreenMapping(double max) { maxPolygonGreenMapping = max; } public void setMaxPolygonBlueMapping(double max) { maxPolygonBlueMapping = max; } public void setMaxPolygonOpacityMapping(double max) { maxPolygonOpacityMapping = max; } public void setMinBranchRedMapping(double min) { minBranchRedMapping = min; } public void setMinBranchGreenMapping(double min) { minBranchGreenMapping = min; } public void setMinBranchBlueMapping(double min) { minBranchBlueMapping = min; } public void setMinBranchOpacityMapping(double min) { minBranchOpacityMapping = min; } public void setMaxBranchRedMapping(double max) { maxBranchRedMapping = max; } public void setMaxBranchGreenMapping(double max) { maxBranchGreenMapping = max; } public void setMaxBranchBlueMapping(double max) { maxBranchBlueMapping = max; } public void setMaxBranchOpacityMapping(double max) { maxBranchOpacityMapping = max; } public void setBranchWidth(double width) { branchWidth = width; } public void setup() { minX = -180; maxX = 180; minY = -90; maxY = 90; mapBackground = new MapBackground(this); }// END:setup public void draw() { noLoop(); smooth(); mapBackground.drawMapBackground(); System.out.println(""Drawing polygons...""); drawPolygons(); switch (analysisType) { case 1: System.out.println(""Drawing branches...""); drawBranches(); break; case 2: break; } }// END:draw private void drawPolygons() throws OutOfMemoryError { System.out.println(""Iterating through Map...""); Set hostKeys = slicesMap.keySet(); Iterator iterator = hostKeys.iterator(); int polygonsStyleId = 1; while (iterator.hasNext()) { System.out.println(""Key "" + polygonsStyleId + ""...""); Double sliceTime = iterator.next(); drawPolygon(sliceTime); polygonsStyleId++; // slicesMap.remove(sliceTime); } }// END: drawPolygons private void drawPolygon(Double sliceTime) throws OutOfMemoryError { /** * Color and Opacity mapping * */ int red = (int) Utils.map(sliceTime, startTime, endTime, minPolygonRedMapping, maxPolygonRedMapping); int green = (int) Utils.map(sliceTime, startTime, endTime, minPolygonGreenMapping, maxPolygonGreenMapping); int blue = (int) Utils.map(sliceTime, startTime, endTime, minPolygonBlueMapping, maxPolygonBlueMapping); int alpha = (int) Utils.map(sliceTime, startTime, endTime, maxPolygonOpacityMapping, minPolygonOpacityMapping); stroke(red, green, blue, alpha); fill(red, green, blue, alpha); List list = slicesMap.get(sliceTime); double[] x = new double[list.size()]; double[] y = new double[list.size()]; for (int i = 0; i < list.size(); i++) { x[i] = list.get(i).getLatitude(); y[i] = list.get(i).getLongitude(); } ContourMaker contourMaker = new ContourWithSynder(x, y, gridSize); ContourPath[] paths = contourMaker.getContourPaths(hpd); for (ContourPath path : paths) { double[] latitude = path.getAllX(); double[] longitude = path.getAllY(); List coordinates = new ArrayList(); for (int i = 0; i < latitude.length; i++) { coordinates .add(new Coordinates(longitude[i], latitude[i], 0.0)); } beginShape(); for (int row = 0; row < coordinates.size() - 1; row++) { double X = Utils.map(coordinates.get(row).getLongitude(), minX, maxX, 0, width); double Y = Utils.map(coordinates.get(row).getLatitude(), maxY, minY, 0, height); double XEND = Utils.map( coordinates.get(row + 1).getLongitude(), minX, maxX, 0, width); double YEND = Utils.map( (coordinates.get(row + 1).getLatitude()), maxY, minY, 0, height); vertex((float) X, (float) Y); vertex((float) XEND, (float) YEND); }// END: coordinates loop endShape(CLOSE); }// END: paths loop slicesMap.remove(sliceTime); }// END: drawPolygon() private void drawBranches() { double treeHeightMax = Utils.getTreeHeightMax(tree); strokeWeight((float) branchWidth); for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { Double longitude = (Double) node.getAttribute(longitudeName); Double latitude = (Double) node.getAttribute(latitudeName); Node parentNode = tree.getParent(node); Double parentLongitude = (Double) parentNode .getAttribute(longitudeName); Double parentLatitude = (Double) parentNode .getAttribute(latitudeName); // Equirectangular projection: double x0 = Utils.map(parentLongitude, minX, maxX, 0, width); double y0 = Utils.map(parentLatitude, maxY, minY, 0, height); double x1 = Utils.map(longitude, minX, maxX, 0, width); double y1 = Utils.map(latitude, maxY, minY, 0, height); /** * Color mapping * */ double nodeHeight = Utils.getNodeHeight(tree, node); int red = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchRedMapping, maxBranchRedMapping); int green = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchGreenMapping, maxBranchGreenMapping); int blue = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchBlueMapping, maxBranchBlueMapping); int alpha = (int) Utils.map(nodeHeight, 0, treeHeightMax, maxBranchOpacityMapping, minBranchOpacityMapping); stroke(red, green, blue, alpha); line((float) x0, (float) y0, (float) x1, (float) y1); } }// END: nodes loop }// END: DrawBranches public void analyzeTrees() throws IOException, ImportException, ParseException { mrsd = new ThreadLocalSpreadDate(mrsdString); switch (analysisType) { case 1: tree = (RootedTree) treeImporter.importNextTree(); treeRootHeight = Utils.getNodeHeight(tree, tree.getRootNode()); sliceHeights = generateTreeSliceHeights(treeRootHeight, numberOfIntervals); timeLine = generateTreeTimeLine(tree); break; case 2: timeLine = generateCustomTimeLine(sliceHeights); break; } //sort them in ascending numerical order Arrays.sort(sliceHeights); System.out.println(""Using as slice times: ""); Utils.printArray(sliceHeights); System.out.println(); startTime = timeLine.getStartTime(); endTime = timeLine.getEndTime(); // This is for slice times slicesMap = new ConcurrentHashMap>(); // Executor for threads int NTHREDS = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(NTHREDS * 2); int treesAssumed = 10000; int treesRead = 0; System.out.println(""Analyzing trees (bar assumes 10,000 trees)""); System.out.println(""0 25 50 75 100""); System.out.println(""|---------------------|---------------------|---------------------|---------------------|""); // System.out.println(""0 25 50 75 100""); // System.out.println(""|--------------|--------------|--------------|--------------|""); int stepSize = treesAssumed / 60; if (stepSize < 1) { stepSize = 1; } // This is for collecting coordinates into polygons slicesMap = new ConcurrentHashMap>(); int totalTrees = 0; while (treesImporter.hasTree()) { currentTree = (RootedTree) treesImporter.importNextTree(); if (totalTrees >= burnIn) { executor.submit(new AnalyzeTree(currentTree, // precisionString,// coordinatesName, // rateString, // sliceHeights, // timescaler,// mrsd, // slicesMap, // useTrueNoise// )); // new AnalyzeTree(currentTree, // precisionString, coordinatesName, rateString, // sliceHeights, timescaler, mrsd, slicesMap, // useTrueNoise).run(); treesRead += 1; }// END: if burn-in if (totalTrees > 0 && totalTrees % stepSize == 0) { System.out.print(""*""); System.out.flush(); } totalTrees++; }// END: while has trees if ((totalTrees - burnIn) <= 0.0) { throw new RuntimeException(""Burnt too many trees!""); } else { System.out.println(""\nAnalyzed "" + treesRead + "" trees with burn-in of "" + burnIn + "" for the total of "" + totalTrees + "" trees""); } // Wait until all threads are finished executor.shutdown(); while (!executor.isTerminated()) { } }// END: AnalyzeTrees private TimeLine generateTreeTimeLine(RootedTree tree) { // This is a general time span for all of the trees double treeRootHeight = Utils.getNodeHeight(tree, tree.getRootNode()); double startTime = mrsd.getTime() - (treeRootHeight * DayInMillis * DaysInYear * timescaler); double endTime = mrsd.getTime(); TimeLine timeLine = new TimeLine(startTime, endTime, numberOfIntervals); return timeLine; }// END: generateTreeTimeLine private double[] generateTreeSliceHeights(double treeRootHeight, int numberOfIntervals) { double[] timeSlices = new double[numberOfIntervals]; for (int i = 0; i < numberOfIntervals; i++) { timeSlices[i] = treeRootHeight - (treeRootHeight / (double) numberOfIntervals) * ((double) i); } return timeSlices; }// END: generateTimeSlices private TimeLine generateCustomTimeLine(double[] timeSlices) { // This is a general time span for all of the trees int numberOfSlices = timeSlices.length; double firstSlice = timeSlices[0]; double startTime = mrsd.getTime() - (firstSlice * DayInMillis * DaysInYear * timescaler); double endTime = mrsd.getTime(); return new TimeLine(startTime, endTime, numberOfSlices); }// END: generateCustomTimeLine }// END: TimeScalerToProcessing class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/DiscreteTreeToProcessing.java",".java","11975","490","package templates; import gui.InteractiveTableModel; import java.io.FileReader; import java.io.IOException; import java.util.List; import java.util.Random; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.io.TreeImporter; import jebl.evolution.trees.RootedTree; import processing.core.PApplet; import processing.core.PFont; import structure.Coordinates; import utils.Utils; @SuppressWarnings(""serial"") public class DiscreteTreeToProcessing extends PApplet { public long time; private TreeImporter importer; private RootedTree tree; private InteractiveTableModel table; private String stateAttName; private int numberOfIntervals; private double rootHeight; private MapBackground mapBackground; private double minBranchRedMapping; private double minBranchGreenMapping; private double minBranchBlueMapping; private double minBranchOpacityMapping; private double maxBranchRedMapping; private double maxBranchGreenMapping; private double maxBranchBlueMapping; private double maxBranchOpacityMapping; private double minPolygonRedMapping; private double minPolygonGreenMapping; private double minPolygonBlueMapping; private double minPolygonOpacityMapping; private double maxPolygonRedMapping; private double maxPolygonGreenMapping; private double maxPolygonBlueMapping; private double maxPolygonOpacityMapping; private double branchWidth; private double polygonsRadiusMultiplier; private Random generator; // min/max longitude private float minX, maxX; // min/max latitude private float minY, maxY; public DiscreteTreeToProcessing() { }// END: DiscreteTreeToProcessing public void setStateAttName(String name) { stateAttName = name; } public void setNumberOfIntervals(int number) { numberOfIntervals = number; } public void setTreePath(String path) throws IOException, ImportException { importer = new NexusImporter(new FileReader(path)); } public void setTable(InteractiveTableModel tableModel) { table = tableModel; } public void setMinBranchRedMapping(double min) { minBranchRedMapping = min; } public void setMinBranchGreenMapping(double min) { minBranchGreenMapping = min; } public void setMinBranchBlueMapping(double min) { minBranchBlueMapping = min; } public void setMinBranchOpacityMapping(double min) { minBranchOpacityMapping = min; } public void setMaxBranchRedMapping(double max) { maxBranchRedMapping = max; } public void setMaxBranchGreenMapping(double max) { maxBranchGreenMapping = max; } public void setMaxBranchBlueMapping(double max) { maxBranchBlueMapping = max; } public void setMaxBranchOpacityMapping(double max) { maxBranchOpacityMapping = max; } public void setMinPolygonRedMapping(double min) { minPolygonRedMapping = min; } public void setMinPolygonGreenMapping(double min) { minPolygonGreenMapping = min; } public void setMinPolygonBlueMapping(double min) { minPolygonBlueMapping = min; } public void setMinPolygonOpacityMapping(double min) { minPolygonOpacityMapping = min; } public void setMaxPolygonRedMapping(double max) { maxPolygonRedMapping = max; } public void setMaxPolygonGreenMapping(double max) { maxPolygonGreenMapping = max; } public void setMaxPolygonBlueMapping(double max) { maxPolygonBlueMapping = max; } public void setMaxPolygonOpacityMapping(double max) { maxPolygonOpacityMapping = max; } public void setPolygonsRadiusMultiplier(double multiplier) { polygonsRadiusMultiplier = multiplier; } public void setBranchWidth(double width) { branchWidth = width; } public void setup() { try { minX = -180; maxX = 180; minY = -90; maxY = 90; generator = new Random(); // will improve font rendering speed with default renderer hint(ENABLE_NATIVE_FONTS); PFont plotFont = createFont(""Monaco"", 12); textFont(plotFont); tree = (RootedTree) importer.importNextTree(); // this is for time calculations rootHeight = tree.getHeight(tree.getRootNode()); mapBackground = new MapBackground(this); } catch (IOException e) { e.printStackTrace(); } catch (ImportException e) { e.printStackTrace(); } }// END: setup public void draw() { // start timing time = -System.currentTimeMillis(); noLoop(); smooth(); mapBackground.drawMapBackground(); drawCircles(); drawPlaces(); drawBranches(); drawPlacesLabels(); // stop timing time += System.currentTimeMillis(); }// END:draw // ////////////// // ---PLACES---// // ////////////// private void drawPlaces() { float radius = 7; // White fill(255, 255, 255); noStroke(); for (int row = 0; row < table.getRowCount(); row++) { Float longitude = Float.valueOf(String.valueOf(table.getValueAt( row, 2))); Float latitude = Float.valueOf(String.valueOf(table.getValueAt(row, 1))); // Equirectangular projection: float X = map(longitude, minX, maxX, 0, width); float Y = map(latitude, maxY, minY, 0, height); ellipse(X, Y, radius, radius); } }// END DrawPlaces private void drawPlacesLabels() { textSize(7); // Black labels fill(0, 0, 0); for (int row = 0; row < table.getRowCount(); row++) { String name = String.valueOf(table.getValueAt(row, 0)); Float longitude = Float.valueOf(String.valueOf(table.getValueAt( row, 2))); Float latitude = Float.valueOf(String.valueOf(table.getValueAt(row, 1))); float X = map(longitude, minX, maxX, 0, width); float Y = map(latitude, maxY, minY, 0, height); text(name, X, Y); } }// END: DrawPlacesLabels // //////////////// // ---BRANCHES---// // //////////////// private void drawBranches() { strokeWeight((float) branchWidth); double treeHeightMax = Utils.getTreeHeightMax(tree); for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { String state = getRandomState((String) node .getAttribute(stateAttName), true); Node parentNode = tree.getParent(node); String parentState = getRandomState((String) parentNode .getAttribute(stateAttName), false); if (state != null && parentState != null) { if (!state.toLowerCase().equals(parentState.toLowerCase())) { float longitude = Utils.matchStateCoordinate(table, state, 2); float latitude = Utils.matchStateCoordinate(table, state, 1); float parentLongitude = Utils.matchStateCoordinate( table, parentState, 2); float parentLatitude = Utils.matchStateCoordinate( table, parentState, 1); float x0 = map(parentLongitude, minX, maxX, 0, width); float y0 = map(parentLatitude, maxY, minY, 0, height); float x1 = map(longitude, minX, maxX, 0, width); float y1 = map(latitude, maxY, minY, 0, height); /** * Color mapping * */ double nodeHeight = tree.getHeight(node); int red = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchRedMapping, maxBranchRedMapping); int green = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchGreenMapping, maxBranchGreenMapping); int blue = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchBlueMapping, maxBranchBlueMapping); int alpha = (int) Utils.map(nodeHeight, 0, treeHeightMax, maxBranchOpacityMapping, minBranchOpacityMapping); stroke(red, green, blue, alpha); line(x0, y0, x1, y1); }// END: state and parent state equality check }// END: null check }// END: root check }// END: nodes loop }// END: DrawBranches // /////////////// // ---CIRCLES---// // /////////////// private void drawCircles() { double[][] numberOfLineages = CountLineagesHoldingState( numberOfIntervals, rootHeight); double lineagesCountMax = Utils.get2DArrayMax(numberOfLineages); for (int i = 0; i < (numberOfIntervals - 1); i++) { for (int j = 0; j < (table.getRowCount()); j++) { if (numberOfLineages[i][j + 1] > 0) { /** * Color mapping * */ int red = (int) Utils.map(numberOfLineages[i][j + 1], 0, lineagesCountMax, minPolygonRedMapping, maxPolygonRedMapping); int green = (int) Utils.map(numberOfLineages[i][j + 1], 0, lineagesCountMax, minPolygonGreenMapping, maxPolygonGreenMapping); int blue = (int) Utils.map(numberOfLineages[i][j + 1], 0, lineagesCountMax, minPolygonBlueMapping, maxPolygonBlueMapping); /** * Opacity mapping * * Larger the values more opaque the colors * */ int alpha = (int) Utils.map(numberOfLineages[i][j + 1], 0, lineagesCountMax, maxPolygonOpacityMapping, minPolygonOpacityMapping); stroke(red, green, blue, alpha); fill(red, green, blue, alpha); double radius = Math.round(100 * Math .sqrt(numberOfLineages[i][j + 1])) * polygonsRadiusMultiplier; Double longitude = Double.valueOf(String.valueOf(table .getValueAt(j, 1))); Double latitude = Double.valueOf(String.valueOf(table .getValueAt(j, 2))); List coordinates = Utils.generateCircle( latitude, // centerLat longitude, // centerLong radius, // radius 36); // numPoints beginShape(); for (int row = 0; row < coordinates.size() - 1; row++) { double X = Utils.map(coordinates.get(row) .getLongitude(), minX, maxX, 0, width); double Y = Utils.map( coordinates.get(row).getLatitude(), maxY, minY, 0, height); double XEND = Utils.map(coordinates.get(row + 1) .getLongitude(), minX, maxX, 0, width); double YEND = Utils.map((coordinates.get(row + 1) .getLatitude()), maxY, minY, 0, height); vertex((float) X, (float) Y); vertex((float) XEND, (float) YEND); }// END: coordinates loop endShape(CLOSE); }// END: if numberOfLineages }// END: table rows loop }// END: numberOfIntervals loop }// END: drawCircles private double[][] CountLineagesHoldingState(int numberOfIntervals, double rootHeight) { double delta = rootHeight / numberOfIntervals; double[][] numberOfLineages = new double[(numberOfIntervals - 1)][table .getRowCount() + 1]; for (int i = 0; i < (numberOfIntervals - 1); i++) { numberOfLineages[i][0] = rootHeight - ((i + 1) * delta); } for (int i = 0; i < (numberOfIntervals - 1); i++) { for (int j = 0; j < table.getRowCount(); j++) { int numberOfLineagesOfState = 0; for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { String state = getRandomState((String) node .getAttribute(stateAttName), false); Node parentNode = tree.getParent(node); String parentState = getRandomState((String) parentNode .getAttribute(stateAttName), false); if ((tree.getHeight(node) <= numberOfLineages[i][0]) && (tree.getHeight(parentNode) > numberOfLineages[i][0])) { String name = String .valueOf(table.getValueAt(j, 0)); if ((state.toLowerCase().equals(parentState .toLowerCase())) && (parentState.toLowerCase().equals(name .toLowerCase()))) { numberOfLineagesOfState++; } } } }// END: node loop numberOfLineages[i][j + 1] = numberOfLineagesOfState; }// END: col loop }// END: row loop return numberOfLineages; }// END: CountLineagesHoldingState private String getRandomState(String state, boolean verbose) { generator.setSeed(time); if (!state.contains(""+"")) { return state; } else {// this breaks ties if (verbose) System.out.println(""Found combined "" + stateAttName + "" attribute: "" + state); state = Utils.pickRand(state.split(""\\+""), generator); if (verbose) System.out.println(""Randomly picking: "" + state); return state; } }// END: getRandomState }// END: PlotOnMap class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/MapBackground.java",".java","1296","53","package templates; import processing.core.PApplet; import processing.core.PImage; public class MapBackground { private PApplet parent; private PImage mapImage; private String imgPath; public static int MAP_IMAGE_WIDTH = 2048; public static int MAP_IMAGE_HEIGHT = 1025; public MapBackground(PApplet p) { parent = p; String runningJarName = getRunningJarName(); if (runningJarName != null) { imgPath = ""jar:"" + this.getClass().getResource(""world_map.png"").getPath(); } else { imgPath = this.getClass().getResource(""world_map.png"").getPath(); } // World map in Equirectangular projection mapImage = parent.loadImage(imgPath); }// END: MapBackground(PApplet p) public void drawMapBackground() { parent.image(mapImage, 0, 0, parent.width, parent.height); }// END: drawMapBackground public String getRunningJarName() { String className = this.getClass().getName().replace('.', '/'); String classJar = this.getClass().getResource(""/"" + className + "".class"").toString(); if (classJar.startsWith(""jar:"")) { String vals[] = classJar.split(""/""); for (String val : vals) { if (val.contains(""!"")) { return val.substring(0, val.length() - 1); } } } return null; }// END: getRunningJarName }// END: MapBackground class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/AnalyzeTree.java",".java","3641","126","package templates; import java.util.ArrayList; import java.util.ConcurrentModificationException; import java.util.List; import java.util.concurrent.ConcurrentMap; import jebl.evolution.graphs.Node; import jebl.evolution.trees.RootedTree; import structure.Coordinates; import utils.ThreadLocalSpreadDate; import utils.Utils; public class AnalyzeTree implements Runnable { private static final int DaysInYear = 365; private RootedTree currentTree; private String precisionString; private String coordinatesName; private String rateString; private double timescaler; private double[] sliceHeights; private ThreadLocalSpreadDate mrsd; private ConcurrentMap> slicesMap; private boolean useTrueNoise; public AnalyzeTree(RootedTree currentTree, String precisionString, String coordinatesName, String rateString, double[] sliceHeights, double timescaler, ThreadLocalSpreadDate mrsd, ConcurrentMap> slicesMap, boolean useTrueNoise) { this.currentTree = currentTree; this.precisionString = precisionString; this.coordinatesName = coordinatesName; this.rateString = rateString; this.sliceHeights = sliceHeights; this.timescaler = timescaler; this.mrsd = mrsd; this.slicesMap = slicesMap; this.useTrueNoise = useTrueNoise; }// END: Constructor public void run() throws ConcurrentModificationException { try { // attributes parsed once per tree double currentTreeNormalization = Utils.getTreeLength(currentTree, currentTree.getRootNode()); double[] precisionArray = Utils.getTreeDoubleArrayAttribute( currentTree, precisionString); for (Node node : currentTree.getNodes()) { if (!currentTree.isRoot(node)) { // attributes parsed once per node Node parentNode = currentTree.getParent(node); double nodeHeight = Utils.getNodeHeight(currentTree, node); double parentHeight = Utils.getNodeHeight(currentTree, parentNode); double[] location = Utils.getDoubleArrayNodeAttribute(node, coordinatesName); double[] parentLocation = Utils .getDoubleArrayNodeAttribute(parentNode, coordinatesName); double rate = Utils .getDoubleNodeAttribute(node, rateString); for (int i = 0; i < sliceHeights.length; i++) { double sliceHeight = sliceHeights[i]; if (nodeHeight < sliceHeight && sliceHeight <= parentHeight) { double[] imputedLocation = Utils.imputeValue(location, parentLocation, sliceHeight, nodeHeight, parentHeight, rate, useTrueNoise, currentTreeNormalization, precisionArray); // calculate key int days = (int) (sliceHeight * DaysInYear * timescaler); double sliceTime = mrsd.minus(days); // grow map entry if key exists if (slicesMap.containsKey(sliceTime)) { slicesMap.get(sliceTime).add( new Coordinates(imputedLocation[1], // longitude imputedLocation[0], // latitude 0.0 // altitude )); // start new entry if no such key in the map } else { List coords = new ArrayList(); coords.add(new Coordinates(imputedLocation[1], // longitude imputedLocation[0], // latitude 0.0 // altitude )); slicesMap.put(sliceTime, coords); }// END: key check }// END: sliceTime check }// END: numberOfIntervals loop }// END: root node check }// END: node loop } catch (Exception e) { e.printStackTrace(); }// END: try-caych block }// END: run }// END: AnalyzeTree ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/RateIndicatorBFToProcessing.java",".java","9972","364","package templates; import gui.InteractiveTableModel; import java.util.ArrayList; import processing.core.PApplet; import processing.core.PFont; import readers.LogFileReader; import utils.Holder; import utils.Utils; import utils.Utils.PoissonPriorEnum; @SuppressWarnings(""serial"") public class RateIndicatorBFToProcessing extends PApplet { private InteractiveTableModel table; private LogFileReader indicators; private double bfCutoff; private MapBackground mapBackground; private ArrayList bayesFactors; private ArrayList posteriorProbabilities; private ArrayList combin; private BayesFactorTest bfTest; // private int numberOfIntervals; private double minBranchRedMapping; private double minBranchGreenMapping; private double minBranchBlueMapping; private double minBranchOpacityMapping; private double maxBranchRedMapping; private double maxBranchGreenMapping; private double maxBranchBlueMapping; private double maxBranchOpacityMapping; private double branchWidth; private Holder meanPoissonPrior = new Holder(0.0); private Holder poissonPriorOffset = new Holder(0.0); // min/max longitude private float minX, maxX; // min/max latitude private float minY, maxY; private PoissonPriorEnum poissonPriorOffsetSwitcher; private PoissonPriorEnum meanPoissonPriorSwitcher; public RateIndicatorBFToProcessing() { }// END: RateIndicatorBFToProcessing() // public void setNumberOfIntervals(int number) { // numberOfIntervals = number; // } public void setDefaultPoissonPriorOffset() { poissonPriorOffsetSwitcher = PoissonPriorEnum.DEFAULT; } public void setUserPoissonPriorOffset(double offset) { poissonPriorOffsetSwitcher = PoissonPriorEnum.USER; poissonPriorOffset.value = offset; } public void setDefaultMeanPoissonPrior() { meanPoissonPriorSwitcher = PoissonPriorEnum.DEFAULT; } public void setUserMeanPoissonPrior(double mean) { meanPoissonPriorSwitcher = PoissonPriorEnum.USER; meanPoissonPrior.value = mean; } public void setBfCutoff(double cutoff) { bfCutoff = cutoff; } public void setTable(InteractiveTableModel tableModel) { table = tableModel; } public void setLogFilePath(String path, double burnIn, String indicatorName) { indicators = new LogFileReader(path, burnIn, indicatorName); } public void setMinBranchRedMapping(double min) { minBranchRedMapping = min; } public void setMinBranchGreenMapping(double min) { minBranchGreenMapping = min; } public void setMinBranchBlueMapping(double min) { minBranchBlueMapping = min; } public void setMinBranchOpacityMapping(double min) { minBranchOpacityMapping = min; } public void setMaxBranchRedMapping(double max) { maxBranchRedMapping = max; } public void setMaxBranchGreenMapping(double max) { maxBranchGreenMapping = max; } public void setMaxBranchBlueMapping(double max) { maxBranchBlueMapping = max; } public void setMaxBranchOpacityMapping(double max) { maxBranchOpacityMapping = max; } public void setBranchWidth(double width) { branchWidth = width; } public void setup() { minX = -180; maxX = 180; minY = -90; maxY = 90; // will improve font rendering speed with default renderer hint(ENABLE_NATIVE_FONTS); PFont plotFont = createFont(""Monaco"", 12); textFont(plotFont); mapBackground = new MapBackground(this); }// END: setup public void draw() { noLoop(); smooth(); computeBFTest(); mapBackground.drawMapBackground(); DrawPlaces(); DrawRates(); // DrawRateSlices(); DrawPlacesLabels(); }// END:draw // ////////////// // ---PLACES---// // ////////////// private void DrawPlaces() { float radius = 7; // White fill(255, 255, 255); noStroke(); for (int row = 0; row < table.getRowCount(); row++) { Float longitude = Float.valueOf(String.valueOf(table.getValueAt( row, 2))); Float latitude = Float.valueOf(String.valueOf(table.getValueAt(row, 1))); // Equirectangular projection: float X = map(longitude, minX, maxX, 0, width); float Y = map(latitude, maxY, minY, 0, height); ellipse(X, Y, radius, radius); } }// END DrawPlaces private void DrawPlacesLabels() { textSize(7); // Black labels fill(0, 0, 0); for (int row = 0; row < table.getRowCount(); row++) { String name = String.valueOf(table.getValueAt(row, 0)); Float longitude = Float.valueOf(String.valueOf(table.getValueAt( row, 2))); Float latitude = Float.valueOf(String.valueOf(table.getValueAt(row, 1))); float X = map(longitude, minX, maxX, 0, width); float Y = map(latitude, maxY, minY, 0, height); text(name, X, Y); } }// END: DrawPlacesLabels private void DrawRates() { System.out.println(""BF cutoff = "" + bfCutoff); System.out.println(""mean Poisson Prior = "" + meanPoissonPrior.value); System.out.println(""Poisson Prior offset = "" + poissonPriorOffset.value); strokeWeight((float) branchWidth); Integer[] sortOrder = bfTest.getSortOrder(); float bfMax = (float) Math.log(Utils.getListMax(bayesFactors)); int index = 0; for (int i = 0; i < combin.size(); i++) { if (bayesFactors.get(sortOrder[i]) > bfCutoff) { /** * Color mapping * */ float bf = (float) Math.log(bayesFactors.get(sortOrder[i])); int red = (int) Utils.map(bf, 0, bfMax, minBranchRedMapping, maxBranchRedMapping); int green = (int) Utils.map(bf, 0, bfMax, minBranchGreenMapping, maxBranchGreenMapping); int blue = (int) Utils.map(bf, 0, bfMax, minBranchBlueMapping, maxBranchBlueMapping); int alpha = (int) Utils.map(bf, 0, bfMax, maxBranchOpacityMapping, minBranchOpacityMapping); stroke(red, green, blue, alpha); String state = combin.get(sortOrder[i]).split("":"")[1]; String parentState = combin.get(sortOrder[i]).split("":"")[0]; float longitude = Utils.matchStateCoordinate(table, state, 2); float latitude = Utils.matchStateCoordinate(table, state, 1); float parentLongitude = Utils.matchStateCoordinate(table, parentState, 2); float parentLatitude = Utils.matchStateCoordinate(table, parentState, 1); float x0 = map(parentLongitude, minX, maxX, 0, width); float y0 = map(parentLatitude, maxY, minY, 0, height); float x1 = map(longitude, minX, maxX, 0, width); float y1 = map(latitude, maxY, minY, 0, height); line(x0, y0, x1, y1); System.out.println(index + ""\t"" + ""pk="" + posteriorProbabilities.get(sortOrder[i]) + ""\t"" + ""BF="" + bayesFactors.get(sortOrder[i]) + ""\t"" + ""between "" + parentState + "" (long: "" + parentLongitude + ""; lat: "" + parentLatitude + "") and "" + state + "" (long: "" + longitude + ""; lat: "" + latitude + "")""); index++; }// END: cutoff check }// END: ArrayList loop }// END: DrawRates // @SuppressWarnings(""unused"") // private void DrawRateSlices() { // // System.out.println(""BF cutoff = "" + bfCutoff); // System.out.println(""mean Poisson Prior = "" + meanPoissonPrior.value); // System.out.println(""Poisson Prior offset = "" + poissonPriorOffset.value); // // strokeWeight((float) branchWidth); // // Integer[] sortOrder = bfTest.getSortOrder(); // float bfMax = (float) Math.log(Utils.getListMax(bayesFactors)); // int index = 0; // // for (int i = 0; i < combin.size(); i++) { // // if (bayesFactors.get(sortOrder[i]) > bfCutoff) { // // /** // * Color mapping // * */ // float bf = (float) Math.log(bayesFactors.get(sortOrder[i])); // // int red = (int) Utils.map(bf, 0, bfMax, minBranchRedMapping, // maxBranchRedMapping); // // int green = (int) Utils.map(bf, 0, bfMax, // minBranchGreenMapping, maxBranchGreenMapping); // // int blue = (int) Utils.map(bf, 0, bfMax, minBranchBlueMapping, // maxBranchBlueMapping); // // int alpha = (int) Utils.map(bf, 0, bfMax, // maxBranchOpacityMapping, minBranchOpacityMapping); // // stroke(red, green, blue, alpha); // // String state = combin.get(sortOrder[i]).split("":"")[1]; // String parentState = combin.get(sortOrder[i]).split("":"")[0]; // // float longitude = Utils.matchStateCoordinate(table, state, 2); // float latitude = Utils.matchStateCoordinate(table, state, 1); // // float parentLongitude = Utils.matchStateCoordinate(table, // parentState, 2); // float parentLatitude = Utils.matchStateCoordinate(table, // parentState, 1); // // GeoIntermediate rhumbIntermediate = new GeoIntermediate( // parentLongitude, parentLatitude, longitude, latitude, // 100); // double[][] coords = rhumbIntermediate.getCoords(); // // for (int row = 0; row < coords.length - 1; row++) { // // float x0 = map((float) coords[row][0], minX, maxX, 0, width); // float y0 = map((float) coords[row][1], maxY, minY, 0, // height); // // float x1 = map((float) coords[row + 1][0], minX, maxX, 0, // width); // float y1 = map((float) coords[row + 1][1], maxY, minY, 0, // height); // // line(x0, y0, x1, y1); // // }// END: numberOfIntervals loop // // System.out.println(index + ""\t"" + ""I="" + posteriorProbabilities.get(sortOrder[i]) + // "" BF="" + bayesFactors.get(sortOrder[i]) + "" : between "" // + parentState + "" (long: "" + parentLongitude // + ""; lat: "" + parentLatitude + "") and "" + state // + "" (long: "" + longitude + ""; lat: "" + latitude + "")""); // // index++; // // }// END: cutoff check // }// END: ArrayList loop // }// END: DrawRatesSlices private void computeBFTest() { combin = new ArrayList(); bayesFactors = new ArrayList(); posteriorProbabilities = new ArrayList(); bfTest = new BayesFactorTest(table, meanPoissonPriorSwitcher, meanPoissonPrior, poissonPriorOffsetSwitcher, poissonPriorOffset, indicators, combin, bayesFactors, posteriorProbabilities); bfTest.ComputeBFTest(); }// END: computeBFTest }// END: RateIndicatorBFToProcessing class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/RateIndicatorBFToKML.java",".java","8597","318","package templates; import generator.KMLGenerator; import gui.InteractiveTableModel; import java.awt.Color; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jebl.evolution.io.ImportException; import readers.LogFileReader; import structure.Coordinates; import structure.Layer; import structure.Line; import structure.Place; import structure.Style; import structure.TimeLine; import utils.Holder; import utils.Utils; import utils.Utils.PoissonPriorEnum; public class RateIndicatorBFToKML { public static long time; private InteractiveTableModel table; private LogFileReader indicators; private List layers; private PrintWriter writer; private int numberOfIntervals; private double maxAltMapping; private double bfCutoff; private ArrayList bayesFactors; private ArrayList posteriorProbabilities; private ArrayList combin; private BayesFactorTest bfTest; private double minBranchRedMapping; private double minBranchGreenMapping; private double minBranchBlueMapping; private double minBranchOpacityMapping; private double maxBranchRedMapping; private double maxBranchGreenMapping; private double maxBranchBlueMapping; private double maxBranchOpacityMapping; private double branchWidth; private Holder meanPoissonPrior = new Holder(0.0); private Holder poissonPriorOffset = new Holder(0.0); private PoissonPriorEnum poissonPriorOffsetSwitcher; private PoissonPriorEnum meanPoissonPriorSwitcher; public RateIndicatorBFToKML() { }// END: RateIndicatorBF() public void setDefaultPoissonPriorOffset() { poissonPriorOffsetSwitcher = PoissonPriorEnum.DEFAULT; } public void setUserPoissonPriorOffset(double offset) { poissonPriorOffsetSwitcher = PoissonPriorEnum.USER; poissonPriorOffset.value = offset; } public void setDefaultMeanPoissonPrior() { meanPoissonPriorSwitcher = PoissonPriorEnum.DEFAULT; } public void setUserMeanPoissonPrior(double mean) { meanPoissonPriorSwitcher = PoissonPriorEnum.USER; meanPoissonPrior.value = mean; } public void setNumberOfIntervals(int number) { numberOfIntervals = number; } public void setMaxAltitudeMapping(double max) { maxAltMapping = max; } public void setBfCutoff(double cutoff) { bfCutoff = cutoff; } public void setTable(InteractiveTableModel tableModel) { table = tableModel; } public void setLogFileParser(String path, double burnIn, String indicatorName) { indicators = new LogFileReader(path, burnIn, indicatorName); } public void setKmlWriterPath(String kmlpath) throws FileNotFoundException { writer = new PrintWriter(kmlpath); } public void setMinBranchRedMapping(double min) { minBranchRedMapping = min; } public void setMinBranchGreenMapping(double min) { minBranchGreenMapping = min; } public void setMinBranchBlueMapping(double min) { minBranchBlueMapping = min; } public void setMinBranchOpacityMapping(double min) { minBranchOpacityMapping = min; } public void setMaxBranchRedMapping(double max) { maxBranchRedMapping = max; } public void setMaxBranchGreenMapping(double max) { maxBranchGreenMapping = max; } public void setMaxBranchBlueMapping(double max) { maxBranchBlueMapping = max; } public void setMaxBranchOpacityMapping(double max) { maxBranchOpacityMapping = max; } public void setBranchWidth(double width) { branchWidth = width; } public void GenerateKML() throws IOException, ImportException, ParseException, RuntimeException { // start timing time = -System.currentTimeMillis(); combin = new ArrayList(); bayesFactors = new ArrayList(); posteriorProbabilities = new ArrayList(); bfTest = new BayesFactorTest(table, meanPoissonPriorSwitcher, meanPoissonPrior, poissonPriorOffsetSwitcher, poissonPriorOffset, indicators, combin, bayesFactors, posteriorProbabilities); bfTest.ComputeBFTest(); // this is to generate kml output KMLGenerator kmloutput = new KMLGenerator(); layers = new ArrayList(); // Execute threads final int NTHREDS = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); executor.submit(new Places()); executor.submit(new Rates()); executor.shutdown(); // Wait until all threads are finished while (!executor.isTerminated()) { } // generate kml TimeLine timeLine = new TimeLine(Double.NaN, Double.NaN, numberOfIntervals); kmloutput.generate(writer, timeLine, layers); // stop timing time += System.currentTimeMillis(); }// END: GenerateKML // ////////////// // ---PLACES---// // ////////////// private class Places implements Runnable { public void run() { // this is for Places folder: String placesDescription = null; Layer placesLayer = new Layer(""Places"", placesDescription); for (int i = 0; i < table.getRowCount(); i++) { String name = String.valueOf(table.getValueAt(i, 0)); Double longitude = Double.valueOf(String.valueOf(table .getValueAt(i, 2))); Double latitude = Double.valueOf(String.valueOf(table .getValueAt(i, 1))); placesLayer.addItem(new Place(name, null, new Coordinates( longitude, latitude), 0, 0)); } layers.add(placesLayer); } }// END: Places // ///////////// // ---RATES---// // ///////////// private class Rates implements Runnable { public void run() { try { System.out.println(""BF cutoff = "" + bfCutoff); System.out.println(""mean Poisson Prior = "" + meanPoissonPrior.value); System.out.println(""Poisson Prior offset = "" + poissonPriorOffset.value); // this is for Branches folder: String ratesDescription = null; Layer ratesLayer = new Layer(""Discrete rates"", ratesDescription); double bfMax = Math.log(Utils.getListMax(bayesFactors)); Integer[] sortOrder = bfTest.getSortOrder(); int branchStyleId = 1; int index = 0; for (int i = 0; i < combin.size(); i++) { if (bayesFactors.get(sortOrder[i]) > bfCutoff) { /** * Color mapping * */ double bf = Math.log(bayesFactors.get(sortOrder[i])); int red = (int) Utils.map(bf, 0, bfMax, minBranchRedMapping, maxBranchRedMapping); int green = (int) Utils.map(bf, 0, bfMax, minBranchGreenMapping, maxBranchGreenMapping); int blue = (int) Utils.map(bf, 0, bfMax, minBranchBlueMapping, maxBranchBlueMapping); int alpha = (int) Utils.map(bf, 0, bfMax, maxBranchOpacityMapping, minBranchOpacityMapping); Style linesStyle = new Style(new Color(red, green, blue, alpha), branchWidth); linesStyle.setId(""branch_style"" + branchStyleId); /** * altitude mapping * */ double maxAltitude = (int) Utils.map(bf, 0, bfMax, 0, maxAltMapping); String state = combin.get(sortOrder[i]).split("":"")[1]; String parentState = combin.get(sortOrder[i]).split("":"")[0]; float longitude = Utils.matchStateCoordinate(table, state, 2); float latitude = Utils.matchStateCoordinate(table, state, 1); float parentLongitude = Utils.matchStateCoordinate( table, parentState, 2); float parentLatitude = Utils.matchStateCoordinate( table, parentState, 1); ratesLayer.addItem(new Line(combin.get(sortOrder[i]) + "", BF="" + bayesFactors.get(sortOrder[i]), // name new Coordinates(parentLongitude, parentLatitude), Double.NaN, // startime linesStyle, // style startstyle new Coordinates(longitude, latitude), // endCoords Double.NaN, // double endtime linesStyle, // style endstyle maxAltitude, // double maxAltitude Double.NaN) // double duration ); branchStyleId++; System.out.println(index + ""\t"" + ""pk="" + posteriorProbabilities.get(sortOrder[i]) + ""\t"" + ""BF="" + bayesFactors.get(sortOrder[i]) + ""\t"" + ""between "" + parentState + "" (long: "" + parentLongitude + ""; lat: "" + parentLatitude + "") and "" + state + "" (long: "" + longitude + ""; lat: "" + latitude + "")""); index++; }// END: cutoff check }// END: i loop layers.add(ratesLayer); } catch (Exception e) { e.printStackTrace(); } }// END: run }// END: Rates }// END: RateIndicatorBF ","Java" "Bio foundation model","phylogeography/SPREADv1","src/templates/ContinuousTreeToKML.java",".java","11560","449","package templates; import generator.KMLGenerator; import java.awt.Color; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.util.ArrayList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import jebl.evolution.graphs.Node; import jebl.evolution.io.ImportException; import jebl.evolution.io.NexusImporter; import jebl.evolution.io.TreeImporter; import jebl.evolution.trees.RootedTree; import structure.Coordinates; import structure.Layer; import structure.Line; import structure.Polygon; import structure.Style; import structure.TimeLine; import utils.ThreadLocalSpreadDate; import utils.Utils; public class ContinuousTreeToKML { public long time; // how many millisecond one day holds private static final int DayInMillis = 86400000; // how many days one year holds private static final int DaysInYear = 365; // Earths radius in km private static final double EarthRadius = 6371; private RootedTree tree; private String HPDString; private String mrsdString; private ThreadLocalSpreadDate mrsd; private int numberOfIntervals; private double timescaler; private double rootHeight; private ArrayList layers; private TimeLine timeLine; private double maxAltMapping; private double minPolygonRedMapping; private double minPolygonGreenMapping; private double minPolygonBlueMapping; private double minPolygonOpacityMapping; private double maxPolygonRedMapping; private double maxPolygonGreenMapping; private double maxPolygonBlueMapping; private double maxPolygonOpacityMapping; private double minBranchRedMapping; private double minBranchGreenMapping; private double minBranchBlueMapping; private double minBranchOpacityMapping; private double maxBranchRedMapping; private double maxBranchGreenMapping; private double maxBranchBlueMapping; private double maxBranchOpacityMapping; private double branchWidth; private String longitudeName; private String latitudeName; private double treeHeightMax; private TreeImporter importer; private PrintWriter writer; public ContinuousTreeToKML() { }// END: ContinuousTreeToKML() public void setTimescaler(double timescaler) { this.timescaler = timescaler; } public void setHPDString(String HPDString) { this.HPDString = HPDString; } public void setLongitudeName(String name) { longitudeName = name; } public void setLatitudeName(String name) { latitudeName = name; } public void setMrsdString(String mrsd) { mrsdString = mrsd; } public void setNumberOfIntervals(int number) { numberOfIntervals = number; } public void setMaxAltitudeMapping(double max) { maxAltMapping = max; } public void setKmlWriterPath(String kmlPath) throws FileNotFoundException { writer = new PrintWriter(kmlPath); } public void setTreePath(String path) throws FileNotFoundException { importer = new NexusImporter(new FileReader(path)); } public void setMinPolygonRedMapping(double min) { minPolygonRedMapping = min; } public void setMinPolygonGreenMapping(double min) { minPolygonGreenMapping = min; } public void setMinPolygonBlueMapping(double min) { minPolygonBlueMapping = min; } public void setMinPolygonOpacityMapping(double min) { minPolygonOpacityMapping = min; } public void setMaxPolygonRedMapping(double max) { maxPolygonRedMapping = max; } public void setMaxPolygonGreenMapping(double max) { maxPolygonGreenMapping = max; } public void setMaxPolygonBlueMapping(double max) { maxPolygonBlueMapping = max; } public void setMaxPolygonOpacityMapping(double max) { maxPolygonOpacityMapping = max; } public void setMinBranchRedMapping(double min) { minBranchRedMapping = min; } public void setMinBranchGreenMapping(double min) { minBranchGreenMapping = min; } public void setMinBranchBlueMapping(double min) { minBranchBlueMapping = min; } public void setMinBranchOpacityMapping(double min) { minBranchOpacityMapping = min; } public void setMaxBranchRedMapping(double max) { maxBranchRedMapping = max; } public void setMaxBranchGreenMapping(double max) { maxBranchGreenMapping = max; } public void setMaxBranchBlueMapping(double max) { maxBranchBlueMapping = max; } public void setMaxBranchOpacityMapping(double max) { maxBranchOpacityMapping = max; } public void setBranchWidth(double width) { branchWidth = width; } public void GenerateKML() throws IOException, ImportException, ParseException { // start timing time = -System.currentTimeMillis(); // import tree tree = (RootedTree) importer.importNextTree(); // this is for time calculations rootHeight = tree.getHeight(tree.getRootNode()); // this is for mappings treeHeightMax = Utils.getTreeHeightMax(tree); // This is a general time span for the tree mrsd = new ThreadLocalSpreadDate(mrsdString); timeLine = new TimeLine(mrsd.getTime() - (rootHeight * DayInMillis * DaysInYear * timescaler), mrsd .getTime(), numberOfIntervals); // this is to generate kml output KMLGenerator kmloutput = new KMLGenerator(); layers = new ArrayList(); // Execute threads final int NTHREDS = Runtime.getRuntime().availableProcessors(); ExecutorService executor = Executors.newFixedThreadPool(NTHREDS); executor.submit(new Branches()); executor.submit(new Polygons()); executor.shutdown(); // Wait until all threads are finished while (!executor.isTerminated()) { } kmloutput.generate(writer, timeLine, layers); // stop timing time += System.currentTimeMillis(); }// END: GenerateKML // //////////////// // ---BRANCHES---// // //////////////// private class Branches implements Runnable { public void run() { try { // this is for Branches folder: Layer branchesLayer = new Layer(""Branches"", null); int branchStyleId = 1; for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { Double longitude = (Double) node .getAttribute(longitudeName); Double latitude = (Double) node .getAttribute(latitudeName); Double nodeHeight = Utils.getNodeHeight(tree, node); Node parentNode = tree.getParent(node); Double parentLongitude = (Double) parentNode .getAttribute(longitudeName); Double parentLatitude = (Double) parentNode .getAttribute(latitudeName); Double parentHeight = Utils.getNodeHeight(tree, parentNode); if (longitude != null && latitude != null && parentLongitude != null && parentLatitude != null) { /** * altitude mapping * */ double maxAltitude = Utils .map(Utils .rhumbDistance(parentLongitude, parentLatitude, longitude, latitude), 0, EarthRadius, 0, maxAltMapping); /** * Color mapping * */ int red = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchRedMapping, maxBranchRedMapping); int green = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchGreenMapping, maxBranchGreenMapping); int blue = (int) Utils.map(nodeHeight, 0, treeHeightMax, minBranchBlueMapping, maxBranchBlueMapping); /** * opacity mapping * */ int alpha = (int) Utils.map(nodeHeight, 0, treeHeightMax, maxBranchOpacityMapping, minBranchOpacityMapping); Color col = new Color(red, green, blue, alpha); Style linesStyle = new Style(col, branchWidth); linesStyle.setId(""branch_style"" + branchStyleId); branchStyleId++; double startTime = mrsd.minus((int) (nodeHeight * DaysInYear * timescaler)); double endTime = mrsd.minus((int) (parentHeight * DaysInYear * timescaler)); //TODO: correlate with node names Line line = new Line( (parentLongitude + "","" + parentLatitude + "":"" + longitude + "","" + latitude), // name new Coordinates(parentLongitude, parentLatitude), // startCoords startTime, // double startime linesStyle, // style startstyle new Coordinates(longitude, latitude), // endCoords endTime, // double endtime linesStyle, // style endstyle maxAltitude, // double maxAltitude 0.0 // double duration ); branchesLayer.addItem(line); }// END: null checks }// END: root check }// END: nodes loop layers.add(branchesLayer); } catch (RuntimeException e) { e.printStackTrace(); } }// END: run }// END: Branches class // //////////////// // ---POLYGONS---// // //////////////// private class Polygons implements Runnable { public void run() { try { String modalityAttributeName = Utils.getModalityAttributeName(longitudeName, HPDString); // this is for Polygons folder: String polygonsDescription = null; Layer polygonsLayer = new Layer(""Polygons"", polygonsDescription); int polygonsStyleId = 1; for (Node node : tree.getNodes()) { if (!tree.isRoot(node)) { if (!tree.isExternal(node)) { Integer modality = (Integer) node .getAttribute(modalityAttributeName); if (modality != null) { for (int i = 1; i <= modality; i++) { Object[] longitudeHPD = Utils .getObjectArrayNodeAttribute(node, longitudeName + ""_"" + HPDString + ""_"" + i); Object[] latitudeHPD = Utils .getObjectArrayNodeAttribute(node, latitudeName + ""_"" + HPDString + ""_"" + i); /** * Color mapping * */ double nodeHeight = tree.getHeight(node); int red = (int) Utils.map(nodeHeight, 0, treeHeightMax, minPolygonRedMapping, maxPolygonRedMapping); int green = (int) Utils.map(nodeHeight, 0, treeHeightMax, minPolygonGreenMapping, maxPolygonGreenMapping); int blue = (int) Utils.map(nodeHeight, 0, treeHeightMax, minPolygonBlueMapping, maxPolygonBlueMapping); /** * opacity mapping * */ int alpha = (int) Utils.map(nodeHeight, 0, treeHeightMax, maxPolygonOpacityMapping, minPolygonOpacityMapping); Color col = new Color(red, green, blue, alpha); Style polygonsStyle = new Style(col, 0); polygonsStyle.setId(""polygon_style"" + polygonsStyleId); int days = (int) (nodeHeight * DaysInYear * timescaler); double startTime = mrsd.minus(days); //TODO: correlate with node names polygonsLayer.addItem(new Polygon(""node"" + polygonsStyleId + ""_"" + HPDString + ""_"" + i, // String name Utils.parsePolygons(longitudeHPD, latitudeHPD),// List polygonsStyle, // Style style startTime, // double startime 0.0 // double duration )); polygonsStyleId++; }// END: modality loop }// END: null check }// END: external node check }// END: root check }// END: nodes loop layers.add(polygonsLayer); } catch (RuntimeException e) { e.printStackTrace(); } }// END: run }// END: polygons class }// END: ContinuousTreeToKML class ","Java" "Bio foundation model","phylogeography/SPREADv1","src/contouring/KernelDensityEstimator2D.java",".java","6846","269","package contouring; import java.util.Arrays; import math.DiscreteStatistics; import math.Matrix; import math.NormalDistribution; import math.Vector; import cern.colt.list.DoubleArrayList; import cern.jet.stat.Descriptive; /** * KernelDensityEstimator2D creates a bi-variate kernel density smoother for * data * * @author Marc A. Suchard * @author Philippe Lemey */ public class KernelDensityEstimator2D implements ContourMaker { // kde2d = // function (x, y, h, n = 25, lims = c(range(x), range(y))) // { // nx <- length(x) // if (length(y) != nx) // stop(""data vectors must be the same length"") // if (any(!is.finite(x)) || any(!is.finite(y))) // stop(""missing or infinite values in the data are not allowed"") // if (any(!is.finite(lims))) // stop(""only finite values are allowed in 'lims'"") // gx <- seq.int(lims[1], lims[2], length.out = n) // gy <- seq.int(lims[3], lims[4], length.out = n) // if (missing(h)) // h <- c(bandwidth.nrd(x), bandwidth.nrd(y)) // h <- h/4 // ax <- outer(gx, x, ""-"")/h[1] // ay <- outer(gy, y, ""-"")/h[2] // z <- matrix(dnorm(ax), n, nx) %*% t(matrix(dnorm(ay), n, // nx))/(nx * h[1] * h[2]) // return(list(x = gx, y = gy, z = z)) // } /* * @param x x-coordinates of observations * * @param y y-coordinates of observations * * @param h bi-variate smoothing bandwidths * * @param n smoothed grid size * * @param lims bi-variate min/max for grid */ public KernelDensityEstimator2D(final double[] x, final double[] y, final double[] h, final int n, final double[] lims) { this.x = x; this.y = y; if (x.length != y.length) throw new RuntimeException(""data vectors must be the same length""); this.nx = x.length; if (n <= 0) throw new RuntimeException( ""must have a positive number of grid points""); this.n = n; if (lims != null) this.lims = lims; else setupLims(); if (h != null) this.h = h; else setupH(); doKDE2D(); } public KernelDensityEstimator2D(final double[] x, final double[] y) { this(x, y, null, 50, null); } public KernelDensityEstimator2D(final double[] x, final double[] y, final int n) { this(x, y, null, n, null); } public void doKDE2D() { gx = makeSequence(lims[0], lims[1], n); gy = makeSequence(lims[2], lims[3], n); double[][] ax = outerMinusScaled(gx, x, h[0]); double[][] ay = outerMinusScaled(gy, y, h[1]); normalize(ax); normalize(ay); z = new double[n][n]; double scale = nx * h[0] * h[1]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { double value = 0; for (int k = 0; k < nx; k++) { value += ax[i][k] * ay[j][k]; } z[i][j] = value / scale; } } } public double findLevelCorrespondingToMass(double probabilityMass) { double level = 0; double[] sz = new double[n * n]; double[] c1 = new double[n * n]; for (int i = 0; i < n; i++) System.arraycopy(z[i], 0, sz, i * n, n); Arrays.sort(sz); final double dx = gx[1] - gx[0]; final double dy = gy[1] - gy[0]; final double dxdy = dx * dy; c1[0] = sz[0] * dxdy; final double criticalValue = 1.0 - probabilityMass; if (criticalValue < c1[0] || criticalValue >= 1.0) throw new RuntimeException(); // do linearInterpolation on density (y) as function of cumulative sum // (x) for (int i = 1; i < n * n; i++) { c1[i] = sz[i] * dxdy + c1[i - 1]; if (c1[i] > criticalValue) { // first largest point final double diffC1 = c1[i] - c1[i - 1]; final double diffSz = sz[i] - sz[i - 1]; level = sz[i] - (c1[i] - criticalValue) / diffC1 * diffSz; break; } } return level; } public ContourPath[] getContourPaths(double hpdValue) { double thresholdDensity = findLevelCorrespondingToMass(hpdValue); ContourGenerator contour = new ContourGenerator(getXGrid(), getYGrid(), getKDE(), new ContourAttrib[] { new ContourAttrib( thresholdDensity) }); ContourPath[] paths = null; try { paths = contour.getContours(); } catch (InterruptedException e) { e.printStackTrace(); } return paths; } public double[][] getKDE() { return z; } public double[] getXGrid() { return gx; } public double[] getYGrid() { return gy; } public void normalize(double[][] X) { for (int i = 0; i < X.length; i++) { for (int j = 0; j < X[0].length; j++) X[i][j] = NormalDistribution.pdf(X[i][j], 0, 1); } } public double[][] outerMinusScaled(double[] X, double[] Y, double scale) { double[][] A = new double[X.length][Y.length]; for (int indexX = 0; indexX < X.length; indexX++) { for (int indexY = 0; indexY < Y.length; indexY++) { A[indexX][indexY] = (X[indexX] - Y[indexY]) / scale; } } return A; } public double[] makeSequence(double start, double end, int length) { double[] seq = new double[length]; double by = (end - start) / (length - 1); double value = start; for (int i = 0; i < length; i++, value += by) { seq[i] = value; } return seq; } private double margin = 0.1; private void setupLims() { lims = new double[4]; lims[0] = DiscreteStatistics.min(x); lims[1] = DiscreteStatistics.max(x); lims[2] = DiscreteStatistics.min(y); lims[3] = DiscreteStatistics.max(y); double xDelta = (lims[1] - lims[0]) * margin; double yDelta = (lims[3] - lims[2]) * margin; lims[0] -= xDelta; lims[1] += xDelta; lims[2] -= yDelta; lims[3] += yDelta; } private void setupH() { h = new double[2]; h[0] = bandwidthNRD(x) / 4; h[1] = bandwidthNRD(y) / 4; } // bandwidth.nrd = // function (x) // { // r <- quantile(x, c(0.25, 0.75)) // h <- (r[2] - r[1])/1.34 // 4 * 1.06 * min(sqrt(var(x)), h) * length(x)^(-1/5) // } public double bandwidthNRD(double[] in) { DoubleArrayList inList = new DoubleArrayList(in.length); for (double d : in) inList.add(d); inList.sort(); final double h = (Descriptive.quantile(inList, 0.75) - Descriptive .quantile(inList, 0.25)) / 1.34; return 4 * 1.06 * Math.min(Math.sqrt(DiscreteStatistics.variance(in)), h) * Math.pow(in.length, -0.2); } public static void main(String[] arg) { double[] x = { 3.4, 1.2, 5.6, 2.2, 3.1 }; double[] y = { 1.0, 2.0, 1.0, 2.0, 1.0 }; KernelDensityEstimator2D kde = new KernelDensityEstimator2D(x, y, 4); System.out.println(new Vector(kde.getXGrid())); System.out.println(new Vector(kde.getYGrid())); System.out.println(new Matrix(kde.getKDE())); System.exit(-1); } public double[] getLims() { return lims; } private final double[] x; // x coordinates private final double[] y; // y coordinates private double[] h; // h[0] x-bandwidth, h[1] y-bandwidth private final int n; // grid size private double[] lims; // x,y limits private int nx; // length of vectors private double[] gx; // x-grid points private double[] gy; // y-grid points private double[][] z; // KDE estimate; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/contouring/ContourPath.java",".java","2865","131","package contouring; /** *

    * This object represents a single contour line or path and all the data that is * associated with it. *

    * *

    * Modified by: Joseph A. Huwaldt *

    * * @author Joseph A. Huwaldt Date: November 11, 2000 * @version November 17, 2000 * * * @author Marc Suchard **/ @SuppressWarnings(""serial"") public class ContourPath implements Cloneable, java.io.Serializable { // Tolerance for path closure. private static final double kSmallX = 0.001; private static final double kSmallY = kSmallX; // X & Y coordinate arrays. private double[] xArr, yArr; // The level index for this contour path. private int levelIndex; // Indicates if this path is open or closed. private boolean closed = false; // The attributes assigned to this contour level. private ContourAttrib attributes; /** * Construct a contour path or line using the given arrays of X & Y values. * * @param attr * Attributes assigned to this contour path. * @param levelIndex * The index to then level this path belongs to. * @param x * Array of X coordinate values. * @param y * Array of Y coordinate values. **/ public ContourPath(ContourAttrib attr, int levelIndex, double[] x, double[] y) { xArr = x; yArr = y; this.levelIndex = levelIndex; attributes = attr; int np = xArr.length; // Determine if the contour path is open or closed. if (Math.abs(x[0] - x[np - 1]) < kSmallX && Math.abs(y[0] - y[np - 1]) < kSmallY) { closed = true; x[np - 1] = x[0]; y[np - 1] = y[0]; // Guarantee closure. } else closed = false; // Contour not closed. } /** * Return the X coordinate values for this contour path. **/ public double[] getAllX() { return xArr; } /** * Return the Y coordinate values for this contour path. **/ public double[] getAllY() { return yArr; } /** * Return the level index for this contour path. The level index is an index * to the level that this path belongs to: the i'th level. **/ public int getLevelIndex() { return levelIndex; } /** * Return the attributes assigned to this contour path. **/ public ContourAttrib getAttributes() { return attributes; } /** * Returns true if this contour path is closed (loops back on itself) or * false if it is not. **/ public boolean isClosed() { return closed; } /** * Make a copy of this ContourPath object. * * @return Returns a clone of this object. **/ public Object clone() { ContourPath newObject = null; try { // Make a shallow copy of this object. newObject = (ContourPath) super.clone(); // There is no ""deep"" data to be cloned. } catch (CloneNotSupportedException e) { // Can't happen. e.printStackTrace(); } // Output the newly cloned object. return newObject; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/contouring/ContourMaker.java",".java","136","12","package contouring; /** * @author Marc Suchard */ public interface ContourMaker { ContourPath[] getContourPaths(double level); } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/contouring/ContourAttrib.java",".java","1536","77","package contouring; /** *

    * This object represents the attributes assigned to a contour path. Typically, * the same attributes are assigned to all the contour paths of a given contour * level. *

    * *

    * Right now, the only attribute used is ""level"", but in the future I may add * more. *

    * *

    * Modified by: Joseph A. Huwaldt *

    * * @author Joseph A. Huwaldt Date: November 11, 2000 * @version November 17, 2000 * * * @author Marc Suchard **/ @SuppressWarnings(""serial"") public class ContourAttrib implements Cloneable, java.io.Serializable { // The level (altitude) of a contour path. private double level; /** * Create a contour attribute object where only the contour level is * specified. **/ public ContourAttrib(double level) { this.level = level; } /** * Return the level stored in this contour attribute. **/ public double getLevel() { return level; } /** * Set or change the level stored in this contour attribute. **/ public void setLevel(double level) { this.level = level; } /** * Make a copy of this ContourAttrib object. * * @return Returns a clone of this object. **/ public Object clone() { ContourAttrib newObject = null; try { // Make a shallow copy of this object. newObject = (ContourAttrib) super.clone(); // There is no ""deep"" data to be cloned. } catch (CloneNotSupportedException e) { // Can't happen. e.printStackTrace(); } // Output the newly cloned object. return newObject; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/contouring/SnyderContour.java",".java","14359","518","package contouring; import java.awt.Dimension; import java.awt.geom.Point2D; import java.util.LinkedList; import java.util.List; /* This class provides 2D contouring functionality. This code is adapted from * ContourPlot.java by David Rand (1997) ""Contour Plotting in Java"" MacTech, volume 13. * Rand, in turn, ported to Java from Fortan: * * Snyder WV (1978) ""Algorithm 531, Contour Plotting [J6]"", ACM Trans. Math. Softw., 4, 290-294. * * @author Marc Suchard */ public class SnyderContour { // Below, constant data members: final static boolean SHOW_NUMBERS = true; final static int BLANK = 32, OPEN_SUITE = (int) '{', CLOSE_SUITE = (int) '}', BETWEEN_ARGS = (int) ',', N_CONTOURS = 1, PLOT_MARGIN = 20, WEE_BIT = 3, NUMBER_LENGTH = 3; final static double Z_MAX_MAX = 1.0E+10, Z_MIN_MIN = -Z_MAX_MAX; final static String EOL = System.getProperty(""line.separator""); // Below, data members which store the grid steps, // the z values, the interpolation flag, the dimensions // of the contour plot and the increments in the grid: int xSteps, ySteps; float z[][]; boolean logInterpolation = false; Dimension d; double deltaX, deltaY; // Below, data members, most of which are adapted from // Fortran variables in Snyder's code: int ncv = N_CONTOURS; int l1[] = new int[4]; int l2[] = new int[4]; int ij[] = new int[2]; int i1[] = new int[2]; int i2[] = new int[2]; int i3[] = new int[6]; int ibkey, icur, jcur, ii, jj, elle, ix, iedge, iflag, ni, ks; int cntrIndex, prevIndex; int idir, nxidir, k; double z1, z2, cval, zMax, zMin; double intersect[] = new double[4]; double xy[] = new double[2]; double prevXY[] = new double[2]; float cv[] = new float[ncv]; boolean jump; // ------------------------------------------------------- // A constructor method. // ------------------------------------------------------- public SnyderContour(int x, int y) { super(); xSteps = x; ySteps = y; } public void setDeltas(double xDelta, double yDelta) { this.deltaX = xDelta; this.deltaY = yDelta; } double offsetX, offsetY; public void setOffsets(double xOffset, double yOffset) { this.offsetX = xOffset; this.offsetY = yOffset; } // ------------------------------------------------------- int sign(int a, int b) { a = Math.abs(a); if (b < 0) return -a; else return a; } // ------------------------------------------------------- // ""DrawKernel"" is the guts of drawing and is called // directly or indirectly by ""ContourPlotKernel"" in order // to draw a segment of a contour or to set the pen // position ""prevXY"". Its action depends on ""iflag"": // // iflag == 1 means Continue a contour // iflag == 2 means Start a contour at a boundary // iflag == 3 means Start a contour not at a boundary // iflag == 4 means Finish contour at a boundary // iflag == 5 means Finish closed contour not at boundary // iflag == 6 means Set pen position // // If the constant ""SHOW_NUMBERS"" is true then when // completing a contour (""iflag"" == 4 or 5) the contour // index is drawn adjacent to where the contour ends. // ------------------------------------------------------- void DrawKernel(List> allPaths) { double // prevU,prevV, u, v; if ((iflag == 1) || (iflag == 4) || (iflag == 5)) { // continue drawing // ... if (cntrIndex != prevIndex) { // Must change colour // SetColour(g); prevIndex = cntrIndex; } // prevU = ((prevXY[0] - 1.0) * deltaX); // prevV = ((prevXY[1] - 1.0) * deltaY); u = ((xy[0] - 1.0) * deltaX) + offsetX; v = ((xy[1] - 1.0) * deltaY) + offsetY; // Interchange horizontal & vertical // g.drawLine(PLOT_MARGIN+prevV,PLOT_MARGIN+prevU, // PLOT_MARGIN+v, PLOT_MARGIN+u); LinkedList path = allPaths.get(allPaths.size() - 1); path.add(new Point2D.Double(u, v)); // if ((SHOW_NUMBERS) && ((iflag==4) || (iflag==5))) { // if (u == 0) u = u - WEE_BIT; // else if (u == d.width) u = u + PLOT_MARGIN/2; // else if (v == 0) v = v - PLOT_MARGIN/2; // else if (v == d.height) v = v + WEE_BIT; // g.drawString(Integer.toString(cntrIndex), // PLOT_MARGIN+v, PLOT_MARGIN+u); // } // TODO If end at boundary, close path. } if ((iflag == 2) || (iflag == 3)) { // start new path u = ((xy[0] - 1.0) * deltaX) + offsetX; v = ((xy[1] - 1.0) * deltaY) + offsetY; LinkedList path = new LinkedList(); path.add(new Point2D.Double(u, v)); allPaths.add(path); } prevXY[0] = xy[0]; prevXY[1] = xy[1]; } // ------------------------------------------------------- // ""DetectBoundary"" // ------------------------------------------------------- void DetectBoundary() { ix = 1; if (ij[1 - elle] != 1) { ii = ij[0] - i1[1 - elle]; jj = ij[1] - i1[elle]; if (z[ii - 1][jj - 1] <= Z_MAX_MAX) { ii = ij[0] + i2[elle]; jj = ij[1] + i2[1 - elle]; if (z[ii - 1][jj - 1] < Z_MAX_MAX) ix = 0; } if (ij[1 - elle] >= l1[1 - elle]) { ix = ix + 2; return; } } ii = ij[0] + i1[1 - elle]; jj = ij[1] + i1[elle]; if (z[ii - 1][jj - 1] > Z_MAX_MAX) { ix = ix + 2; return; } if (z[ij[0]][ij[1]] >= Z_MAX_MAX) ix = ix + 2; } // ------------------------------------------------------- // ""Routine_label_020"" corresponds to a block of code // starting at label 20 in Synder's subroutine ""GCONTR"". // ------------------------------------------------------- boolean Routine_label_020() { l2[0] = ij[0]; l2[1] = ij[1]; l2[2] = -ij[0]; l2[3] = -ij[1]; idir = 0; nxidir = 1; k = 1; ij[0] = Math.abs(ij[0]); ij[1] = Math.abs(ij[1]); if (z[ij[0] - 1][ij[1] - 1] > Z_MAX_MAX) { elle = idir % 2; ij[elle] = sign(ij[elle], l1[k - 1]); return true; } elle = 0; return false; } // ------------------------------------------------------- // ""Routine_label_050"" corresponds to a block of code // starting at label 50 in Synder's subroutine ""GCONTR"". // ------------------------------------------------------- boolean Routine_label_050() { while (true) { if (ij[elle] >= l1[elle]) { if (++elle <= 1) continue; elle = idir % 2; ij[elle] = sign(ij[elle], l1[k - 1]); if (Routine_label_150()) return true; continue; } ii = ij[0] + i1[elle]; jj = ij[1] + i1[1 - elle]; if (z[ii - 1][jj - 1] > Z_MAX_MAX) { if (++elle <= 1) continue; elle = idir % 2; ij[elle] = sign(ij[elle], l1[k - 1]); if (Routine_label_150()) return true; continue; } break; } jump = false; return false; } // ------------------------------------------------------- // ""Routine_label_150"" corresponds to a block of code // starting at label 150 in Synder's subroutine ""GCONTR"". // ------------------------------------------------------- boolean Routine_label_150() { while (true) { // ------------------------------------------------ // Lines from z[ij[0]-1][ij[1]-1] // to z[ij[0] ][ij[1]-1] // and z[ij[0]-1][ij[1]] // are not satisfactory. Continue the spiral. // ------------------------------------------------ if (ij[elle] < l1[k - 1]) { ij[elle]++; if (ij[elle] > l2[k - 1]) { l2[k - 1] = ij[elle]; idir = nxidir; nxidir = idir + 1; k = nxidir; if (nxidir > 3) nxidir = 0; } ij[0] = Math.abs(ij[0]); ij[1] = Math.abs(ij[1]); if (z[ij[0] - 1][ij[1] - 1] > Z_MAX_MAX) { elle = idir % 2; ij[elle] = sign(ij[elle], l1[k - 1]); continue; } elle = 0; return false; } if (idir != nxidir) { nxidir++; ij[elle] = l1[k - 1]; k = nxidir; elle = 1 - elle; ij[elle] = l2[k - 1]; if (nxidir > 3) nxidir = 0; continue; } if (ibkey != 0) return true; ibkey = 1; ij[0] = icur; ij[1] = jcur; if (Routine_label_020()) continue; return false; } } // ------------------------------------------------------- // ""Routine_label_200"" corresponds to a block of code // starting at label 200 in Synder's subroutine ""GCONTR"". // It has return values 0, 1 or 2. // ------------------------------------------------------- short Routine_label_200(// Graphics g List> allPaths, boolean workSpace[]) { while (true) { xy[elle] = 1.0 * ij[elle] + intersect[iedge - 1]; xy[1 - elle] = 1.0 * ij[1 - elle]; workSpace[2 * (xSteps * (ySteps * cntrIndex + ij[1] - 1) + ij[0] - 1) + elle] = true; DrawKernel(allPaths); if (iflag >= 4) { icur = ij[0]; jcur = ij[1]; return 1; } ContinueContour(); if (!workSpace[2 * (xSteps * (ySteps * cntrIndex + ij[1] - 1) + ij[0] - 1) + elle]) return 2; iflag = 5; // 5. Finish a closed contour iedge = ks + 2; if (iedge > 4) iedge = iedge - 4; intersect[iedge - 1] = intersect[ks - 1]; } } // ------------------------------------------------------- // ""CrossedByContour"" is true iff the current segment in // the grid is crossed by one of the contour values and // has not already been processed for that value. // ------------------------------------------------------- boolean CrossedByContour(boolean workSpace[]) { ii = ij[0] + i1[elle]; jj = ij[1] + i1[1 - elle]; z1 = z[ij[0] - 1][ij[1] - 1]; z2 = z[ii - 1][jj - 1]; for (cntrIndex = 0; cntrIndex < ncv; cntrIndex++) { int i = 2 * (xSteps * (ySteps * cntrIndex + ij[1] - 1) + ij[0] - 1) + elle; if (!workSpace[i]) { float x = cv[cntrIndex]; if ((x > Math.min(z1, z2)) && (x <= Math.max(z1, z2))) { workSpace[i] = true; return true; } } } return false; } // ------------------------------------------------------- // ""ContinueContour"" continues tracing a contour. Edges // are numbered clockwise, the bottom edge being # 1. // ------------------------------------------------------- void ContinueContour() { short local_k; ni = 1; if (iedge >= 3) { ij[0] = ij[0] - i3[iedge - 1]; ij[1] = ij[1] - i3[iedge + 1]; } for (local_k = 1; local_k < 5; local_k++) if (local_k != iedge) { ii = ij[0] + i3[local_k - 1]; jj = ij[1] + i3[local_k]; z1 = z[ii - 1][jj - 1]; ii = ij[0] + i3[local_k]; jj = ij[1] + i3[local_k + 1]; z2 = z[ii - 1][jj - 1]; if ((cval > Math.min(z1, z2) && (cval <= Math.max(z1, z2)))) { if ((local_k == 1) || (local_k == 4)) { double zz = z2; z2 = z1; z1 = zz; } intersect[local_k - 1] = (cval - z1) / (z2 - z1); ni++; ks = local_k; } } if (ni != 2) { // ------------------------------------------------- // The contour crosses all 4 edges of cell being // examined. Choose lines top-to-left & bottom-to- // right if interpolation point on top edge is // less than interpolation point on bottom edge. // Otherwise, choose the other pair. This method // produces the same results if axes are reversed. // The contour may close at any edge, but must not // cross itself inside any cell. // ------------------------------------------------- ks = 5 - iedge; if (intersect[2] >= intersect[0]) { ks = 3 - iedge; if (ks <= 0) ks = ks + 4; } } // ---------------------------------------------------- // Determine whether the contour will close or run // into a boundary at edge ks of the current cell. // ---------------------------------------------------- elle = ks - 1; iflag = 1; // 1. Continue a contour jump = true; if (ks >= 3) { ij[0] = ij[0] + i3[ks - 1]; ij[1] = ij[1] + i3[ks + 1]; elle = ks - 3; } } void ContourKernel(double[][] data, List> allPaths, double level) { ncv = 1; cv[0] = (float) level; int workLength = 2 * xSteps * ySteps * ncv; boolean workSpace[]; // Allocate below if data valid z = new float[data.length][data[0].length]; for (int i = 0; i < data.length; i++) { for (int j = 0; j < data[i].length; j++) z[i][j] = (float) data[i][j]; } workSpace = new boolean[workLength]; ContourPlotKernel(allPaths, workSpace); } // ------------------------------------------------------- // ""ContourPlotKernel"" is the guts of this class and // corresponds to Synder's subroutine ""GCONTR"". // ------------------------------------------------------- void ContourPlotKernel(List> allPaths, boolean workSpace[]) { short val_label_200; l1[0] = xSteps; l1[1] = ySteps; l1[2] = -1; l1[3] = -1; i1[0] = 1; i1[1] = 0; i2[0] = 1; i2[1] = -1; i3[0] = 1; i3[1] = 0; i3[2] = 0; i3[3] = 1; i3[4] = 1; i3[5] = 0; prevXY[0] = 0.0; prevXY[1] = 0.0; xy[0] = 1.0; xy[1] = 1.0; cntrIndex = 0; prevIndex = -1; iflag = 6; // DrawKernel(g); icur = Math.max(1, Math.min((int) Math.floor(xy[0]), xSteps)); jcur = Math.max(1, Math.min((int) Math.floor(xy[1]), ySteps)); ibkey = 0; ij[0] = icur; ij[1] = jcur; if (Routine_label_020() && Routine_label_150()) return; if (Routine_label_050()) return; while (true) { DetectBoundary(); if (jump) { if (ix != 0) iflag = 4; // Finish contour at boundary iedge = ks + 2; if (iedge > 4) iedge = iedge - 4; intersect[iedge - 1] = intersect[ks - 1]; val_label_200 = Routine_label_200(allPaths, workSpace); if (val_label_200 == 1) { if (Routine_label_020() && Routine_label_150()) return; if (Routine_label_050()) return; continue; } if (val_label_200 == 2) continue; return; } if ((ix != 3) && (ix + ibkey != 0) && CrossedByContour(workSpace)) { // // An acceptable line segment has been found. // Follow contour until it hits a // boundary or closes. // iedge = elle + 1; cval = cv[cntrIndex]; if (ix != 1) iedge = iedge + 2; iflag = 2 + ibkey; intersect[iedge - 1] = (cval - z1) / (z2 - z1); val_label_200 = Routine_label_200(allPaths, workSpace); if (val_label_200 == 1) { if (Routine_label_020() && Routine_label_150()) return; if (Routine_label_050()) return; continue; } if (val_label_200 == 2) continue; return; } if (++elle > 1) { elle = idir % 2; ij[elle] = sign(ij[elle], l1[k - 1]); if (Routine_label_150()) return; } if (Routine_label_050()) return; } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/contouring/ContourWithSynder.java",".java","1647","63","package contouring; import java.awt.geom.Point2D; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; /** * @author Marc A. Suchard */ public class ContourWithSynder extends KernelDensityEstimator2D { public ContourWithSynder(final double[] x, final double[] y, final double[] h, final int n, final double[] lims) { super(x, y, h, n, lims); } public ContourWithSynder(final double[] x, final double[] y) { super(x, y); } public ContourWithSynder(final double[] x, final double[] y, int n) { super(x, y, n); } public ContourPath[] getContourPaths(double hpdValue) { if (contourPaths == null) { double thresholdDensity = findLevelCorrespondingToMass(hpdValue); SnyderContour contourPlot = new SnyderContour(getXGrid().length, getYGrid().length); contourPlot.setDeltas(getXGrid()[1] - getXGrid()[0], getYGrid()[1] - getYGrid()[0]); contourPlot.setOffsets(getXGrid()[0], getYGrid()[0]); List> allPaths = new ArrayList>(); contourPlot.ContourKernel(getKDE(), allPaths, thresholdDensity); contourPaths = new ContourPath[allPaths.size()]; for (int i = 0; i < allPaths.size(); i++) { LinkedList path = allPaths.get(i); int len = path.size(); double[] x = new double[len]; double[] y = new double[len]; for (int j = 0; j < len; j++) { Point2D pt = path.get(j); x[j] = pt.getX(); y[j] = pt.getY(); } contourPaths[i] = new ContourPath(new ContourAttrib( thresholdDensity), 1, x, y); } } return contourPaths; } private ContourPath[] contourPaths = null; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/contouring/ContourGenerator.java",".java","24097","931","package contouring; import java.util.ArrayList; import java.util.List; /** *

    * An object used to generate a list of contour lines or paths from a set of * gridded three dimensional data. *

    * *

    * Based on contour_plot.c from NeXTcontour1.4 by Thomas H. Pulliam, * pulliam@rft29.nas.nasa.gov, MS 202A-1 NASA Ames Research Center, Moffett * Field, CA 94035. I don't know how the original Fortran code looked like or * where it came from, other than that NeXTcontour1.4 is based on Pieter * Bunings' PLOT3D package for Computational Fluid Dynamics. *

    * *

    * Ported from C to Java by Joseph A. Huwaldt, November 16, 2000. *

    * *

    * Modified by: Joseph A. Huwaldt *

    * * @author Joseph A. Huwaldt Date: November 11, 2000 * @version November 23, 2000 * * @author Marc Suchard * **/ public class ContourGenerator { // Debug flag. private static final boolean DEBUG = false; // Error messages. private static final String kCancelMsg = ""Method ContourGenerator.getContours() canceled by user.""; private static final String kInconsistantArrMsg = ""Inconsistant array sizes.""; private static final String kArrSizeMsg = ""Data arrays must have more than one row or column.""; private static final String kNegLogDataMsg = ""Function data must be > 0 for logarithmic intervals.""; // Path buffer size. private static final int kBufSize = 1000; // The minimum number of points allowed in a contour path. private static final int kMinNumPoints = 3; // A list of contour paths. private List pathList = new ArrayList(); // A flag to indicate that the contours have been computed or not. private boolean cCalculated = false; // Data arrays used for generating the contours. private double[][] xArray, yArray, funcArray; // Data arrays used when generating contours for 1D X & Y arrays. private double[] xArr1D, yArr1D; // Array of contour attributes, one for each contour level. private ContourAttrib[] cAttr; // The fraction of the task that is completed. private float fracComplete = 0; /** * Used to indicate that the user wishes to cancel the calculation of * contours. **/ private boolean isCanceled = false; // Variables in the original FORTRAN program. private double[] pathbufxt, pathbufyt; private int[] pathbufia; private int lnstrt; // lnstrt=1 indicates starting a new line. private int ignext; private int icont; // Current contour level index. private double cont; // The current contour level. private int iss, iee, jss, jee; // i & j start and end index values. private int ima; // ima tells which boundary region we are on. private int iae; // Index to last element in the IA list. private int ibeg, jbeg; private int gi, gj; // Indexes into data arrays. private double fij; // Data value at i,j in data array. private int idir; // Indicates current direction. private int np = 0; // Number of points in current contour line. private double wx = 0, wy = 0; // Starting point of a contour line. /** * Construct a ContourGenerator object using the specified data arrays and * the specified attribute array. This constructor allows you to use data on * an uneven X, Y grid. * * @param xArr * 2D array containing the grid x coordinate data. * @param yArr * 2D array containing the grid y coordinate data. * @param fArr * 2D array containing the grid function (z) data. * @param cAttr * Array containing attributes of the contour levels. **/ public ContourGenerator(double[][] xArr, double[][] yArr, double[][] fArr, ContourAttrib[] cAttr) { // Make sure input data is reasonable. if (yArr.length != xArr.length || yArr.length != fArr.length) throw new IllegalArgumentException(kInconsistantArrMsg); if (yArr[0].length != xArr[0].length || yArr[0].length != fArr[0].length) throw new IllegalArgumentException(kInconsistantArrMsg); if (xArr.length <= 1 || xArr[0].length <= 1) throw new IllegalArgumentException(kArrSizeMsg); this.cAttr = cAttr; xArray = xArr; yArray = yArr; funcArray = fArr; } /** * Construct a ContourGenerator object using the specified data arrays and * the specified attribute array. This constructor allows you to use data on * an evenly spaced grid where ""X"" values are invarient with ""Y"" and ""Y"" * values are invarient with ""X"". This often occures where the data is on an * evenly spaced cartesian grid. * * @param xArr * 1D array containing the grid x coordinate data. * @param yArr * 1D array containing the grid y coordinate data. * @param fArr * 2D array containing the grid function (z) data. * @param cAttr * Array containing attributes of the contour levels. **/ public ContourGenerator(double[] xArr, double[] yArr, double[][] fArr, ContourAttrib[] cAttr) { // Make sure input data is reasonable. if (yArr.length != fArr.length || xArr.length != fArr[0].length) throw new IllegalArgumentException(kInconsistantArrMsg); if (xArr.length <= 1) throw new IllegalArgumentException(kArrSizeMsg); this.cAttr = cAttr; xArr1D = xArr; yArr1D = yArr; funcArray = fArr; } /** * Construct a ContourGenerator object using the specified data arrays. * Contour attributes, including the interval, are generated automatically. * This constructor allows you to use data on an uneven X, Y grid. * * @param xArr * 2D array containing the grid x coordinate data. * @param yArr * 2D array containing the grid y coordinate data. * @param fArr * 2D array containing the grid function (z) data. * @param nc * The number of contour levels to generate. * @param logInterval * Uses a logarithmic contour interval if true, and uses a linear * interval if false. **/ public ContourGenerator(double[][] xArr, double[][] yArr, double[][] fArr, int nc, boolean logInterval) { // Make sure input data is reasonable. if (yArr.length != xArr.length || yArr.length != fArr.length) throw new IllegalArgumentException(kInconsistantArrMsg); if (yArr[0].length != xArr[0].length || yArr[0].length != fArr[0].length) throw new IllegalArgumentException(kInconsistantArrMsg); if (xArr.length <= 1 || xArr[0].length <= 1) throw new IllegalArgumentException(kArrSizeMsg); xArray = xArr; yArray = yArr; funcArray = fArr; if (logInterval) findLogIntervals(nc); else findLinearIntervals(nc); } /** * Construct a ContourGenerator object using the specified data arrays. * Contour attributes, including the interval, are generated automatically. * This constructor allows you to use data on an evenly spaced grid where * ""X"" values are invarient with ""Y"" and ""Y"" values are invarient with ""X"". * This often occures where the data is on an evenly spaced cartesian grid. * * @param xArr * 1D array containing the grid x coordinate data. * @param yArr * 1D array containing the grid y coordinate data. * @param fArr * 2D array containing the grid function (z) data. * @param nc * The number of contour levels to generate. * @param logInterval * Uses a logarithmic contour interval if true, and uses a linear * interval if false. **/ public ContourGenerator(double[] xArr, double[] yArr, double[][] fArr, int nc, boolean logInterval) { // Make sure input data is reasonable. if (yArr.length != fArr.length || xArr.length != fArr[0].length) throw new IllegalArgumentException(kInconsistantArrMsg); if (xArr.length <= 1) throw new IllegalArgumentException(kArrSizeMsg); xArr1D = xArr; yArr1D = yArr; funcArray = fArr; if (logInterval) findLogIntervals(nc); else findLinearIntervals(nc); } /** * Generate the contour paths and return them as an array of ContourPath * objects. If there is a lot of data, this method method may take a long * time, so be patient. Progress can be checked from another thread by * calling ""getProgress()"". * * @return An array of contour path objects. * @throws InterruptedException * if the user cancels this process (by calling ""cancel()"" from * another thread). **/ public ContourPath[] getContours() throws InterruptedException { if (!cCalculated) { isCanceled = false; pathList.clear(); // Go off an compute the contour paths. computeContours(); // Now turn loose all our data arrays to be garbage collected. cAttr = null; xArray = yArray = funcArray = null; xArr1D = yArr1D = null; // Set our ""done"" flags. cCalculated = true; fracComplete = 1; } // Turn our pathList into an array and return the array. int size = pathList.size(); ContourPath[] arr = new ContourPath[size]; for (int i = 0; i < size; ++i) arr[i] = (ContourPath) pathList.get(i); return arr; } /** * Returns true if the contour generation process is done. False if it is * not. **/ public boolean done() { return cCalculated; } /** * Call this method to cancel the generation of contours. **/ public void cancel() { isCanceled = true; } /** * Returns the progress of the currently executing contour generation * process: 0.0 (just starting) to 1.0 (done). **/ public float getProgress() { return fracComplete; } /** * Find contour intervals that are linearly spaced through the data. **/ private void findLinearIntervals(int nc) { // Find min and max Z values. double zMin = Double.MAX_VALUE; double zMax = -zMin; int ni = funcArray.length; for (int i = 0; i < ni; ++i) { int nj = funcArray[i].length; for (int j = 0; j < nj; ++j) { double zVal = funcArray[i][j]; zMin = Math.min(zMin, zVal); zMax = Math.max(zMax, zVal); } } // Allocate memory for contour attribute array. cAttr = new ContourAttrib[nc]; // Determine contour levels. double delta = (zMax - zMin) / (nc + 1); for (int i = 0; i < nc; i++) { cAttr[i] = new ContourAttrib(zMin + (i + 1) * delta); if (DEBUG) System.out.println(""level["" + i + ""] = "" + (zMin + (i + 1) * delta)); } } /** * Find contour intervals that are logarithmically spaced through the data. **/ private void findLogIntervals(int nc) { // Find min and max Z values. double zMin = Double.MAX_VALUE; double zMax = -zMin; int ni = funcArray.length; for (int i = 0; i < ni; ++i) { int nj = funcArray[i].length; for (int j = 0; j < nj; ++j) { double zVal = funcArray[i][j]; zMin = Math.min(zMin, zVal); zMax = Math.max(zMax, zVal); } } if (zMin < 0) throw new IllegalArgumentException(kNegLogDataMsg); // Allocate memory for contour attribute array. cAttr = new ContourAttrib[nc]; // Determine contour levels. double temp = Math.log(zMin); double delta = (Math.log(zMax) - temp) / (nc + 1); for (int i = 0; i < nc; i++) cAttr[i] = new ContourAttrib(Math.exp(temp + (i + 1) * delta)); } /** * Computes contour lines for gridded data and stores information about * those contours. The result of this routine is a list of contour lines or * paths. **/ private void computeContours() throws InterruptedException { int ncont = cAttr.length; // Number of contour levels. // Find the number of data points in ""I"" and ""J"" directions. int nx = 0, ny = 0; if (xArray != null) { ny = xArray.length; nx = xArray[0].length; } else { nx = xArr1D.length; ny = yArr1D.length; } // Allocate temporary storage space for path buffers. pathbufxt = new double[kBufSize]; pathbufyt = new double[kBufSize]; pathbufia = new int[kBufSize * 3]; // lnstrt=1 (line start) means we're starting a new line. lnstrt = 1; ignext = 0; // Loop through each contour level. for (icont = 0; icont < ncont; ++icont) { // Check to see if the user has canceled. if (isCanceled) throw new InterruptedException(kCancelMsg); // Begin working on this contour level. cont = cAttr[icont].getLevel(); iss = 1; iee = nx; jss = 1; jee = ny; boolean subDivFlg = false; /* L110 */do { // Find where function increases through the contour level. FlagContourPassings(); boolean L10flg = false; /* L210 */do { if (!L10flg) { /* * Search along the boundaries for contour line starts. * IMA tells which boundary of the region we're on. */ ima = 1; ibeg = iss - 1; jbeg = jss; } /* L6 */imaLoop: do { if (!L10flg) { boolean imb = false; boolean doneFlg = false; do { switch (ima) { case 1: ++ibeg; if (ibeg == iee) ima = 2; break; case 2: ++jbeg; if (jbeg == jee) ima = 3; break; case 3: --ibeg; if (ibeg == iss) ima = 4; break; case 4: --jbeg; if (jbeg == jss) ima = 5; break; case 5: continue imaLoop; } if (funcArray[jbeg - 1][ibeg - 1] <= cont) { imb = true; doneFlg = false; } else if (imb == true) doneFlg = true; } while (!doneFlg); // Got a start point. gi = ibeg; // x index of starting point. gj = jbeg; // y index of starting point. fij = funcArray[jbeg - 1][ibeg - 1]; // z value of // starting // point. // Round the corner if necessary. /* * Look different directions to see which way the * contour line went: 4 1-|-3 2 */ switch (ima) { case 1: Routine_L21(); break; case 2: if (gj != jss) { if (!Routine_L31()) Routine_L21(); } else Routine_L21(); break; case 3: if (gi != iee) { if (!Routine_L41()) Routine_L21(); } else { if (!Routine_L31()) Routine_L21(); } break; case 4: if (gj != jee) { if (!Routine_L51()) Routine_L21(); } else { if (!Routine_L41()) Routine_L21(); } break; case 5: if (!Routine_L51()) Routine_L21(); break; } } // end if(!L10flg) // This is the end of a contour line. After this, we'll // start a // new line. L10flg = false; /* L90 */lnstrt = 1; // Contour line start flag. ignext = 0; accumContour(np, icont, pathbufxt, pathbufyt, cAttr[icont]); // If we're not done looking along the boundaries, // go look there some more. } while (ima != 5); // Otherwise, get the next start out of IA. /* L91 */if (iae != 0) { int ntmp3 = iae; for (int iia = 1; iia <= ntmp3; ++iia) { if (pathbufia[iia - 1] != 0) { // This is how we start in the middle of the // region, using IA. gi = pathbufia[iia - 1] / 1000; gj = pathbufia[iia - 1] - gi * 1000; fij = funcArray[gj - 1][gi - 1]; pathbufia[iia - 1] = 0; Routine_L21(); L10flg = true; break; } } } } while (L10flg); /* * And if there are no more of these, we're done with this * region. If we've subdivided, update the region pointers and * go back for more. */ subDivFlg = false; if (iee == nx) { if (jee != ny) { jss = jee; jee = ny; subDivFlg = true; } } else { iss = iee; iee = nx; subDivFlg = true; } } while (subDivFlg); // Update progress information. fracComplete = (float) (icont + 1) / (float) (ncont); // Loop back for the next contour level. } // Next icont // Turn loose temporary arrays used to generate contours. pathbufxt = null; pathbufyt = null; pathbufia = null; } /** * Flag points in IA where the the function increases through the contour * level, not including the boundaries. This is so we have a list of at * least one point on each contour line that doesn't intersect a boundary. **/ private void FlagContourPassings() { iae = 0; int ntmp2 = jee - 1; for (int j = jss + 1; j <= ntmp2; ++j) { boolean imb = false; int iaend = iae; int ntmp3 = iee; for (int i = iss; i <= ntmp3; ++i) { if (funcArray[j - 1][i - 1] <= cont) imb = true; else if (imb == true) { ++iae; pathbufia[iae - 1] = i * 1000 + j; imb = false; /* * Check if the IA array is full. If so, the subdividing * algorithm goes like this: if we've marked at least one J * row, drop back to the last completed J and call that the * region. If we haven't even finished one J row, our region * just extends to this I location. */ if (iae == kBufSize * 3) { if (j > jss + 1) { iae = iaend; jee = j; } else { // Compute minimum. jee = Math.min(j + 1, jee); iee = i; } // Break out of i & j loops. return; } } } // Next i } // Next j } /** * This function represents the block of code in the original FORTRAN * program that comes after line 21. **/ private void Routine_L21() { while (true) { --gi; if (gi < iss) return; // Goto L90. idir = 1; if (funcArray[gj - 1][gi - 1] <= cont) { // Wipe this point out of IA if it's in the list. /* L52 */if (iae != 0) { int ij = gi * 1000 + gj + 1000; int ntmp3 = iae; for (int iia = 1; iia <= ntmp3; ++iia) { if (pathbufia[iia - 1] == ij) { pathbufia[iia - 1] = 0; break; } } } doInterpolation(); return; // Goto L90. } fij = funcArray[gj - 1][gi - 1]; if (Routine_L31()) return; // Goto L90 } } /** * This function represents the block of code in the original FORTRAN * program that comes after line 31. **/ private boolean Routine_L31() { --gj; if (gj < jss) return true; idir = 2; if (funcArray[gj - 1][gi - 1] <= cont) { doInterpolation(); return true; } fij = funcArray[gj - 1][gi - 1]; return (Routine_L41()); } /** * This function represents the block of code in the original FORTRAN * program that comes after line 41. **/ private boolean Routine_L41() { ++gi; if (gi > iee) return true; idir = 3; if (funcArray[gj - 1][gi - 1] <= cont) { doInterpolation(); return true; } fij = funcArray[gj - 1][gi - 1]; return (Routine_L51()); } /** * This function represents the block of code in the original FORTRAN * program that comes after line 51. **/ private boolean Routine_L51() { ++gj; idir = 4; if (gj > jee) return true; if (funcArray[gj - 1][gi - 1] <= cont) { doInterpolation(); return true; } fij = funcArray[gj - 1][gi - 1]; return false; } /** * Do interpolation for X, Y coordinates. * * This function represents the block of code in the original FORTRAN * program that comes after line 60. **/ private void doInterpolation() { // Do interpolation for X,Y coordinates. double func = funcArray[gj - 1][gi - 1]; double xyf = (cont - func) / (fij - func); /* * This tests for a contour point coinciding with a grid point. In this * case the contour routine comes up with the same physical coordinate * twice. If If we don't trap it, it can (in some cases significantly) * increase the number of points in a contour line. Also, if this * happens on the first point in a line, the second point could be * misinterpreted as the end of a (circling) contour line. */ if (xyf == 0) ++ignext; double wxx = 0, wyy = 0; double xVal = 0, yVal = 0; if (xArray != null) { // We have 2D arrays for the X & Y grid points. xVal = xArray[gj - 1][gi - 1]; yVal = yArray[gj - 1][gi - 1]; switch (idir) { case 1: // East wxx = xVal + xyf * (xArray[gj - 1][gi + 1 - 1] - xVal); wyy = yVal + xyf * (yArray[gj - 1][gi + 1 - 1] - yVal); break; case 2: // North wxx = xVal + xyf * (xArray[gj + 1 - 1][gi - 1] - xVal); wyy = yVal + xyf * (yArray[gj + 1 - 1][gi - 1] - yVal); break; case 3: // West wxx = xVal + xyf * (xArray[gj - 1][gi - 1 - 1] - xVal); wyy = yVal + xyf * (yArray[gj - 1][gi - 1 - 1] - yVal); break; case 4: // South wxx = xVal + xyf * (xArray[gj - 1 - 1][gi - 1] - xVal); wyy = yVal + xyf * (yArray[gj - 1 - 1][gi - 1] - yVal); break; } } else { // We have 1D arrays for the X & Y grid points. xVal = xArr1D[gi - 1]; yVal = yArr1D[gj - 1]; switch (idir) { case 1: // East wxx = xVal + xyf * (xArr1D[gi + 1 - 1] - xVal); wyy = yVal; break; case 2: // North wxx = xVal; wyy = yVal + xyf * (yArr1D[gj + 1 - 1] - yVal); break; case 3: // West wxx = xVal + xyf * (xArr1D[gi - 1 - 1] - xVal); wyy = yVal; break; case 4: // South wxx = xVal; wyy = yVal + xyf * (yArr1D[gj - 1 - 1] - yVal); break; } } if (DEBUG) { System.out.println(""i, j = "" + gi + "","" + gj); System.out.println(""cont = "" + (float) cont + "", fij = "" + (float) fij + "", func = "" + (float) func + "", xyf = "" + (float) xyf); System.out.println(""xVal = "" + (float) xVal + "", yVal = "" + (float) yVal); System.out.println(""wxx = "" + (float) wxx + "", wyy = "" + (float) wyy); } // Figure out what to do with this point. if (lnstrt == 1) { // This is the 1st point in the contour line. np = 1; pathbufxt[np - 1] = wxx; pathbufyt[np - 1] = wyy; // Save starting point as wx, wy. wx = wxx; wy = wyy; // Clear the first point flag, we've got one now. lnstrt = 0; } else { boolean skipFlg = false; // Second point and after comes here. // Add a point to this line. Check for duplicate point first. if (ignext == 2) { if (wxx == pathbufxt[np - 1] && wyy == pathbufyt[np - 1]) { ignext = 0; skipFlg = true; } else ignext = 1; } if (!skipFlg) { // Increment # of points in contour. ++np; pathbufxt[np - 1] = wxx; pathbufyt[np - 1] = wyy; // See if the temporary array xt, yt are full. if (np == kBufSize) { accumContour(np, icont, pathbufxt, pathbufyt, cAttr[icont]); // Last point becomes 1st point to continue. pathbufxt[0] = pathbufxt[np - 1]; pathbufyt[0] = pathbufyt[np - 1]; np = 1; } // Check to see if we're back to the intial point. if (wxx == wx && wyy == wy) return; } } // Search for the next point on this line. /* L67 */switch (idir) { case 1: ++gi; if (!Routine_L51()) Routine_L21(); break; case 2: ++gj; Routine_L21(); break; case 3: --gi; if (!Routine_L31()) Routine_L21(); break; case 4: --gj; if (!Routine_L41()) Routine_L21(); break; } return; } /** * Accumulate contour paths, as they are generated, into an overall list of * contours. * * @param np * The number of points in the contour path buffers. * @param icont * The index to the current contour level. * @param x * ,y Buffers containing x & y coordinates of contour points. * @param cAttr * The attributes for this particular contour level. **/ private void accumContour(int np, int icont, double[] x, double[] y, ContourAttrib cAttr) { // To few points for a contour line. if (np < kMinNumPoints) return; // Copy over coordinate points from buffers to their own arrays. double[] xArr = new double[np]; double[] yArr = new double[np]; System.arraycopy(x, 0, xArr, 0, np); System.arraycopy(y, 0, yArr, 0, np); // Create a new contour path and add it to the list. ContourPath path = new ContourPath(cAttr, icont, xArr, yArr); pathList.add(path); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/utils/KmlUtils.java",".java","1451","54","/* * KmlUtils.java Created Oct 14, 2010 by Andrew Butler, PSL */ package kmlframework.utils; /** Contains utility methods useful for creating KML documents */ public class KmlUtils { private static final java.text.SimpleDateFormat GOOGLE_TIME_FORMAT; static { GOOGLE_TIME_FORMAT = new java.text.SimpleDateFormat(""yyyy-MM-dd'T'HH:mm:ss'Z'""); GOOGLE_TIME_FORMAT.setTimeZone(java.util.TimeZone.getTimeZone(""GMT"")); } /** * Writes a time to correct KML format * * @param time The time (in milliseconds from the epoch) to convert * @return The KML-formatted time */ public static String formatTime(long time) { return GOOGLE_TIME_FORMAT.format(new java.util.Date(time)); } private static final String HEX = ""0123456789abcdef""; /** * Writes a color to correct KML format * * @param color The color to convert * @return The KML-formatted color */ public static String formatColor(java.awt.Color color) { StringBuilder ret = new StringBuilder(); int a = color.getAlpha(); ret.append(HEX.charAt(a / 16)); ret.append(HEX.charAt(a % 16)); int b = color.getBlue(); ret.append(HEX.charAt(b / 16)); ret.append(HEX.charAt(b % 16)); int g = color.getGreen(); ret.append(HEX.charAt(g / 16)); ret.append(HEX.charAt(g % 16)); int r = color.getRed(); ret.append(HEX.charAt(r / 16)); ret.append(HEX.charAt(r % 16)); return ret.toString(); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/utils/MathUtils.java",".java","739","28","package kmlframework.utils; public class MathUtils { public static double degreesToDecimal(String input) { char direction = input.charAt(0); int degrees; int minutes; int seconds; if (direction == 'E' || direction == 'W') { degrees = Integer.parseInt(input.substring(1,4)); minutes = Integer.parseInt(input.substring(4,6)); seconds = Integer.parseInt(input.substring(6)); } else { degrees = Integer.parseInt(input.substring(1,3)); minutes = Integer.parseInt(input.substring(3,5)); seconds = Integer.parseInt(input.substring(5)); } double decimal = degrees + (float) minutes / 60 + (float) seconds / 3600; if (direction == 'W' || direction == 'S') { decimal *= -1; } return decimal; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/utils/Ellipsoid.java",".java","1288","43","package kmlframework.utils; public class Ellipsoid { private static double a = 6378137; // default to wgs 84 private static double f = 298.257223563; // default to wgs 84 private static double fInverted = 1 / f; private static double eps2 = fInverted * (2d - fInverted); private static double k1 = Math.toRadians(a * (1d - eps2)); private static double k2 = Math.toRadians(a); /** * Convert meter to longitude at ref latitude */ public static final double meterToLongitude(double latitude) { return 1.0 / longitudeToMeter(latitude); } /** * Convert meter to latitude at ref latitude */ public static final double meterToLatitude(double latitude) { return 1.0 / latitudeToMeter(latitude); } /** * Convert longitude to meter at ref latitude */ public static final double longitudeToMeter(double latitude) { return (Math.cos(Math.toRadians(latitude)) * k2) / Math.sqrt(getDiv0(latitude)); } /** * Convert latitude to meter at ref latitude */ public static final double latitudeToMeter(double latitude) { return (k1 / Math.sqrt(Math.pow(getDiv0(latitude), 3))); } private static final double getDiv0(double latitude) { return 1.0 - eps2 * Math.pow(Math.sin(Math.toRadians(latitude)), 2); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/coordinates/CartesianCoordinate.java",".java","3580","134","package kmlframework.coordinates; import kmlframework.utils.Ellipsoid; public class CartesianCoordinate implements Coordinate { private double x; private double y; private double z; public CartesianCoordinate() {} public CartesianCoordinate(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } public double getX() { return x; } public void setX(double x) { this.x = x; } public double getY() { return y; } public void setY(double y) { this.y = y; } public double getZ() { return z; } public void setZ(double z) { this.z = z; } public double distanceTo(CartesianCoordinate cartesianCoordinate) { return Math.sqrt( Math.pow(Math.abs(cartesianCoordinate.getX()-x), 2) + Math.pow(Math.abs(cartesianCoordinate.getY()-y), 2) + Math.pow(Math.abs(cartesianCoordinate.getZ()-z), 2)); } public void rotateAroundZAxis(double rotation) { double xTemp = Math.cos(rotation) * x - Math.sin(rotation) * y; y = Math.sin(rotation) * x + Math.cos(rotation) * y; x = xTemp; } public void rotateAroundYAxis(double rotation) { double xTemp = Math.cos(rotation) * x + Math.sin(rotation) * z; z = - Math.sin(rotation) * x + Math.cos(rotation) * z; x = xTemp; } public void rotateAroundXAxis(double rotation) { double yTemp = Math.cos(rotation) * y - Math.sin(rotation) * z; z = Math.sin(rotation) * y + Math.cos(rotation) * z; y = yTemp; } public void add(CartesianCoordinate cartesianCoordinate) { x += cartesianCoordinate.getX(); y += cartesianCoordinate.getY(); z += cartesianCoordinate.getZ(); } public void subtract(CartesianCoordinate cartesianCoordinate) { x -= cartesianCoordinate.getX(); y -= cartesianCoordinate.getY(); z -= cartesianCoordinate.getZ(); } public double length() { return Math.sqrt(x*x + y*y + z*z); } public void normalize() { double length = length(); x /= length; y /= length; z /= length; } public void scale(double scalingFactor) { x *= scalingFactor; y *= scalingFactor; z *= scalingFactor; } public String toString() { return ""["" + x + "", "" + y + "", "" + z + ""]""; } public EarthCoordinate toEarthCoordinate(EarthCoordinate location, Double rotation, CartesianCoordinate localReferenceCoordinate, CartesianCoordinate scale) { // We scale the coordinates double xTransformed = x; double yTransformed = y; double zTransformed = z; if (scale != null) { xTransformed = x * scale.getX(); yTransformed = y * scale.getY(); zTransformed = z * scale.getZ(); } // We move the coordinates according to the local reference coordinate if (localReferenceCoordinate != null) { xTransformed -= localReferenceCoordinate.getX(); yTransformed -= localReferenceCoordinate.getY(); zTransformed -= localReferenceCoordinate.getZ(); } //rotation = Math.PI/4; // We rotate the coordinates according to the rotation. We do only support rotation around the z axis if (rotation != null) { double xTmp = xTransformed; xTransformed = Math.cos(rotation) * xTmp + Math.sin(rotation) * yTransformed; yTransformed = -Math.sin(rotation) * xTmp + Math.cos(rotation) * yTransformed; } // Move to world coordinates if (location != null) { xTransformed = location.getLongitude() + xTransformed * Ellipsoid.meterToLongitude(location.getLatitude()); yTransformed = location.getLatitude() + yTransformed * Ellipsoid.meterToLatitude(location.getLatitude()); zTransformed += location.getAltitude(); } return new EarthCoordinate(zTransformed, yTransformed, xTransformed); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/coordinates/EarthCoordinate.java",".java","1766","48","package kmlframework.coordinates; import kmlframework.kml.AltitudeModeEnum; import kmlframework.kml.Point; public class EarthCoordinate extends Point implements Coordinate { public static double EARTHRADIUS = 6372795.477598; // in meters public EarthCoordinate() {} public EarthCoordinate(Double longitude, Double latitude) { super(longitude, latitude); } public EarthCoordinate(Double longitude, Double latitude, Double altitude) { super(longitude, latitude, altitude); } public EarthCoordinate(Boolean extrude, AltitudeModeEnum altitudeMode, Double longitude, Double latitude, Double altitude) { super(extrude, altitudeMode, longitude, latitude, altitude); } public double getRadius() { return getAltitude() + EARTHRADIUS; } public CartesianCoordinate toCartesianCoordinate() { CartesianCoordinate cartesianCoordinate = new CartesianCoordinate(); cartesianCoordinate.setX(getRadius() * Math.sin(Math.PI/2 - getLatitude()*(Math.PI/180)) * Math.cos(getLongitude()*(Math.PI/180))); cartesianCoordinate.setY(getRadius() * Math.sin(Math.PI/2 - getLatitude()*(Math.PI/180)) * Math.sin(getLongitude()*(Math.PI/180))); cartesianCoordinate.setZ(getRadius() * Math.cos(Math.PI/2 - getLatitude()*(Math.PI/180))); return cartesianCoordinate; } public double distanceTo(EarthCoordinate earthCoordinate) { return toCartesianCoordinate().distanceTo(earthCoordinate.toCartesianCoordinate()); } public String toString() { return ""[longitude: "" + getLongitude() + "", latitude: "" + getLatitude() + "", altitude: "" + getAltitude() + ""]""; } public EarthCoordinate toEarthCoordinate(EarthCoordinate earthCoordinate, Double rotation, CartesianCoordinate localReferenceCoordinate, CartesianCoordinate scale) { return this; } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/coordinates/Coordinate.java",".java","231","10","package kmlframework.coordinates; public interface Coordinate { EarthCoordinate toEarthCoordinate(EarthCoordinate earthCoordinate, Double rotation, CartesianCoordinate localReferenceCoordinate, CartesianCoordinate scale); } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/coordinates/TimeAndPlace.java",".java","505","32","package kmlframework.coordinates; import java.util.Date; public class TimeAndPlace { private EarthCoordinate place; private Date time; public TimeAndPlace() {} public TimeAndPlace(EarthCoordinate place, Date time) { this.place = place; this.time = time; } public EarthCoordinate getPlace() { return place; } public void setPlace(EarthCoordinate place) { this.place = place; } public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ColorStyle.java",".java","774","39","package kmlframework.kml; public abstract class ColorStyle extends KmlObject { private String color; private ColorModeEnum colorMode; public ColorStyle() {} public ColorStyle(String color, ColorModeEnum colorMode) { this.color = color; this.colorMode = colorMode; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public ColorModeEnum getColorMode() { return colorMode; } public void setColorMode(ColorModeEnum colorMode) { this.colorMode = colorMode; } public void writeInner(Kml kml) throws KmlException { if (color != null) { kml.println("""" + color + """"); } if (colorMode != null) { kml.println("""" + colorMode + """"); } } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Change.java",".java","310","17","package kmlframework.kml; public class Change extends UpdateElement { public Change() {} public Change(KmlObject kmlObject) { setKmlObject(kmlObject); } public void write(Kml kml) throws KmlException { kml.println("""", 1); getKmlObject().write(kml); kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/NetworkLinkControl.java",".java","3893","156","package kmlframework.kml; public class NetworkLinkControl extends KmlObject { private Double minRefreshPeriod; private Double maxSessionLength; private String cookie; private String message; private String linkName; private String linkDescription; private String linkSnippet; private Integer linkSnippetMaxLines; private String expires; private Update update; private AbstractView abstractView; public NetworkLinkControl() {} public NetworkLinkControl(Double minRefreshPeriod, Double maxSessionLength, String cookie, String message, String linkName, String linkDescription, String linkSnippet, Integer linkSnippetMaxLines, String expires, Update update, AbstractView abstractView) { this.minRefreshPeriod = minRefreshPeriod; this.maxSessionLength = maxSessionLength; this.cookie = cookie; this.message = message; this.linkName = linkName; this.linkDescription = linkDescription; this.linkSnippet = linkSnippet; this.linkSnippetMaxLines = linkSnippetMaxLines; this.expires = expires; this.update = update; this.abstractView = abstractView; } public Double getMinRefreshPeriod() { return minRefreshPeriod; } public void setMinRefreshPeriod(Double minRefreshPeriod) { this.minRefreshPeriod = minRefreshPeriod; } public Double getMaxSessionLength() { return maxSessionLength; } public void setMaxSessionLength(Double maxSessionLength) { this.maxSessionLength = maxSessionLength; } public String getCookie() { return cookie; } public void setCookie(String cookie) { this.cookie = cookie; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getLinkName() { return linkName; } public void setLinkName(String linkName) { this.linkName = linkName; } public String getLinkDescription() { return linkDescription; } public void setLinkDescription(String linkDescription) { this.linkDescription = linkDescription; } public String getLinkSnippet() { return linkSnippet; } public void setLinkSnippet(String linkSnippet) { this.linkSnippet = linkSnippet; } public Integer getLinkSnippetMaxLines() { return linkSnippetMaxLines; } public void setLinkSnippetMaxLines(Integer linkSnippetMaxLines) { this.linkSnippetMaxLines = linkSnippetMaxLines; } public String getExpires() { return expires; } public void setExpires(String expires) { this.expires = expires; } public Update getUpdate() { return update; } public void setUpdate(Update update) { this.update = update; } public AbstractView getAbstractView() { return abstractView; } public void setAbstractView(AbstractView abstractView) { this.abstractView = abstractView; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (minRefreshPeriod != null) { kml.println("""" + minRefreshPeriod + """"); } if (maxSessionLength != null) { kml.println("""" + maxSessionLength + """"); } if (cookie != null) { kml.println("""" + cookie + """"); } if (message != null) { kml.println("""" + message + """"); } if (linkName != null) { kml.println("""" + linkName + """"); } if (linkDescription != null) { kml.println("""" + linkDescription + """"); } if (linkSnippet != null) { kml.println("""" + linkSnippet + """"); } if (expires != null) { kml.println("""" + expires + """"); } if (update != null) { update.write(kml); } if (abstractView != null) { abstractView.write(kml); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ViewFormat.java",".java","1008","36","package kmlframework.kml; public class ViewFormat extends KmlObject { private boolean includeBBox = true; private boolean includeCamera = true; private boolean includeView = true; public ViewFormat() {} public ViewFormat(boolean includeBBox, boolean includeCamera, boolean includeView) { this.includeBBox = includeBBox; this.includeCamera = includeCamera; this.includeView = includeView; } public void write(Kml kml) throws KmlException { kml.print(""""); if (includeBBox) { kml.print(""BBOX=[bboxWest],[bboxSouth],[bboxEast],[bboxNorth]""); } if (includeBBox && includeCamera) { kml.print("";""); } if (includeCamera) { kml.print(""CAMERA=[lookatLon],[lookatLat],[lookatRange],[lookatTilt],[lookatHeading]""); } if (includeCamera && includeView) { kml.print("";""); } if (includeView) { kml.print(""VIEW=[horizFov],[vertFov],[horizPixels],[vertPixels],[terrainEnabled]""); } kml.println(""""); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Alias.java",".java","895","41","package kmlframework.kml; public class Alias extends KmlObject { private String targetHref; private String sourceHref; public Alias() {} public Alias(String targetHref, String sourceHref) { this.targetHref = targetHref; this.sourceHref = sourceHref; } public String getTargetHref() { return targetHref; } public void setTargetHref(String targetHref) { this.targetHref = targetHref; } public String getSourceHref() { return sourceHref; } public void setSourceHref(String sourceHref) { this.sourceHref = sourceHref; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (targetHref != null) { kml.println("""" + targetHref + """"); } if (sourceHref != null) { kml.println("""" + sourceHref + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Camera.java",".java","708","31","package kmlframework.kml; public class Camera extends AbstractView { private Double roll; public Camera() {} public Camera(Double longitude, Double latitude, Double altitude, Double heading, Double tilt, AltitudeModeEnum altitudeMode, Double roll) { super(longitude, latitude, altitude, heading,tilt, altitudeMode); this.roll = roll; } public Double getRoll() { return roll; } public void setRoll(Double roll) { this.roll = roll; } public void write(Kml kml) throws KmlException { kml.println("""", 1); super.writeInner(kml); if (roll != null) { kml.println("""" + roll + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Style.java",".java","1992","93","package kmlframework.kml; public class Style extends StyleSelector { private IconStyle iconStyle; private LabelStyle labelStyle; private LineStyle lineStyle; private PolyStyle polyStyle; private BalloonStyle ballonStyle; private ListStyle listStyle; public Style() {} public Style(IconStyle iconStyle, LabelStyle labelStyle, LineStyle lineStyle, PolyStyle polyStyle, BalloonStyle ballonStyle, ListStyle listStyle) { this.iconStyle = iconStyle; this.labelStyle = labelStyle; this.lineStyle = lineStyle; this.polyStyle = polyStyle; this.ballonStyle = ballonStyle; this.listStyle = listStyle; } public IconStyle getIconStyle() { return iconStyle; } public void setIconStyle(IconStyle iconStyle) { this.iconStyle = iconStyle; } public LabelStyle getLabelStyle() { return labelStyle; } public void setLabelStyle(LabelStyle labelStyle) { this.labelStyle = labelStyle; } public LineStyle getLineStyle() { return lineStyle; } public void setLineStyle(LineStyle lineStyle) { this.lineStyle = lineStyle; } public PolyStyle getPolyStyle() { return polyStyle; } public void setPolyStyle(PolyStyle polyStyle) { this.polyStyle = polyStyle; } public BalloonStyle getBallonStyle() { return ballonStyle; } public void setBallonStyle(BalloonStyle ballonStyle) { this.ballonStyle = ballonStyle; } public ListStyle getListStyle() { return listStyle; } public void setListStyle(ListStyle listStyle) { this.listStyle = listStyle; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (iconStyle != null) { iconStyle.write(kml); } if (labelStyle != null) { labelStyle.write(kml); } if (lineStyle != null) { lineStyle.write(kml); } if (polyStyle != null) { polyStyle.write(kml); } if (ballonStyle != null) { ballonStyle.write(kml); } if (listStyle != null) { listStyle.write(kml); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/RefreshModeEnum.java",".java","91","6","package kmlframework.kml; public enum RefreshModeEnum { onChange, onInterval, onExpire } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/LineString.java",".java","2061","84","package kmlframework.kml; import java.util.List; public class LineString extends Geometry { private Boolean extrude; private Boolean tessellate; private AltitudeModeEnum altitudeMode; private List coordinates; public LineString() {} public LineString(Boolean extrude, Boolean tessellate, AltitudeModeEnum altitudeMode, List coordinates) { this.extrude = extrude; this.tessellate = tessellate; this.altitudeMode = altitudeMode; this.coordinates = coordinates; } public Boolean getExtrude() { return extrude; } public void setExtrude(Boolean extrude) { this.extrude = extrude; } public Boolean getTessellate() { return tessellate; } public void setTessellate(Boolean tessellate) { this.tessellate = tessellate; } public AltitudeModeEnum getAltitudeMode() { return altitudeMode; } public void setAltitudeMode(AltitudeModeEnum altitudeMode) { this.altitudeMode = altitudeMode; } public List getCoordinates() { return coordinates; } public void setCoordinates(List coordinates) { this.coordinates = coordinates; } public void write(Kml kml) throws KmlException { // We validate the data if (coordinates == null || coordinates.size() < 2) { throw new KmlException(""LineString must contain at least 2 points""); } kml.println("""", 1); if (extrude != null) { kml.println("""" + booleanToInt(extrude) + """"); } if (tessellate != null) { kml.println("""" + booleanToInt(tessellate) + """"); } if (altitudeMode != null) { kml.println("""" + altitudeMode + """"); } if (coordinates != null) { kml.print(""""); boolean firstLoop = true; for (Point point : coordinates) { if (firstLoop) { firstLoop = false; } else { kml.printNoIndent("" ""); } kml.printNoIndent(point.getLongitudeLatitudeAltitudeString()); } kml.println(""""); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/UnitEnum.java",".java","83","6","package kmlframework.kml; public enum UnitEnum { pixels, fraction, insetPixels } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Location.java",".java","1071","50","/* * Location.java Created Oct 13, 2010 by Andrew Butler, PSL */ package kmlframework.kml; public class Location extends KmlObject { private Double latitude; private Double longitude; private Double altitude; public Location() { } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getAltitude() { return altitude; } public void setAltitude(Double altitude) { this.altitude = altitude; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if(latitude!=null) kml.println(""""+latitude+""""); if(longitude!=null) kml.println(""""+longitude+""""); if(altitude!=null) kml.println(""""+altitude+""""); kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/SimpleField.java",".java","1241","48","package kmlframework.kml; public class SimpleField extends KmlObject { private SimpleFieldTypeEnum simpleFieldType; private String name; private String displayName; public SimpleField() {} public SimpleField(SimpleFieldTypeEnum simpleFieldType, String name, String displayName) { this.simpleFieldType = simpleFieldType; this.name = name; this.displayName = displayName; } public SimpleFieldTypeEnum getSimpleFieldType() { return simpleFieldType; } public void setSimpleFieldType(SimpleFieldTypeEnum simpleFieldType) { this.simpleFieldType = simpleFieldType; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (displayName != null) { kml.println("""" + displayName + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Pair.java",".java","928","44","package kmlframework.kml; public class Pair extends KmlObject { private StyleStateEnum key; private String styleUrl; public Pair() {} public Pair(StyleStateEnum key, String styleUrl) { this.key = key; this.styleUrl = styleUrl; } public StyleStateEnum getKey() { return key; } public void setKey(StyleStateEnum key) { this.key = key; } public String getStyleUrl() { return styleUrl; } public void setStyleUrl(String styleUrl) { this.styleUrl = styleUrl; } public void write(Kml kml) throws KmlException { // We validate the data if (key == null) { throw new KmlException(""Key missing for Pair""); } if (styleUrl == null) { throw new KmlException(""StyleUrl missing for Pair""); } kml.println("""", 1); kml.println("""" + key + """"); kml.println("""" + styleUrl + """"); kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/TimeSpan.java",".java","746","41","package kmlframework.kml; public class TimeSpan extends TimePrimitive { private String begin; private String end; public TimeSpan() {} public TimeSpan(String begin, String end) { this.begin = begin; this.end = end; } public String getBegin() { return begin; } public void setBegin(String begin) { this.begin = begin; } public String getEnd() { return end; } public void setEnd(String end) { this.end = end; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (begin != null) { kml.println("""" + begin + """"); } if (end != null) { kml.println("""" + end + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/KmlException.java",".java","356","23","package kmlframework.kml; public class KmlException extends Exception { private static final long serialVersionUID = 1L; public KmlException() { super(); } public KmlException(String arg0) { super(arg0); } public KmlException(String arg0, Throwable arg1) { super(arg0, arg1); } public KmlException(Throwable arg0) { super(arg0); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Orientation.java",".java","973","50","/* * Location.java Created Oct 13, 2010 by Andrew Butler, PSL */ package kmlframework.kml; public class Orientation extends KmlObject { private Double heading; private Double tilt; private Double roll; public Orientation() { } public Double getHeading() { return heading; } public void setHeading(Double heading) { this.heading = heading; } public Double getTilt() { return tilt; } public void setTilt(Double tilt) { this.tilt = tilt; } public Double getRoll() { return roll; } public void setRoll(Double roll) { this.roll = roll; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if(heading!=null) kml.println(""""+heading+""""); if(tilt!=null) kml.println(""""+tilt+""""); if(roll!=null) kml.println(""""+roll+""""); kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Update.java",".java","969","41","package kmlframework.kml; import java.util.List; public class Update extends KmlObject { private String targetHref; private List updateElements; public String getTargetHref() { return targetHref; } public void setTargetHref(String targetHref) { this.targetHref = targetHref; } public List getUpdateElements() { return updateElements; } public void setUpdateElements(List updateElements) { this.updateElements = updateElements; } public void write(Kml kml) throws KmlException { // We validate the data if (targetHref == null) { throw new KmlException(""targetHref cannot be null in Update""); } kml.println("""", 1); kml.println("""" + targetHref + """"); if (updateElements != null) { for (UpdateElement updateElement : updateElements) { updateElement.write(kml); } } kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Schema.java",".java","694","32","package kmlframework.kml; import java.util.List; public class Schema extends KmlObject { private List simpleFields; public Schema() {} public Schema(List simpleFields) { this.simpleFields = simpleFields; } public List getSimpleFields() { return simpleFields; } public void setSimpleFields(List simpleFields) { this.simpleFields = simpleFields; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (simpleFields != null) { for (SimpleField simpleField : simpleFields) { simpleField.write(kml); } } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Delete.java",".java","548","25","package kmlframework.kml; public class Delete extends UpdateElement { public Delete() {} public Delete(KmlObject kmlObject) { setKmlObject(kmlObject); } @Override public void setKmlObject(KmlObject kmlObject) { if(!(kmlObject instanceof Deletable)) throw new IllegalArgumentException(""Only deletable objects can be deleted""); super.setKmlObject(kmlObject); } public void write(Kml kml) throws KmlException { kml.println("""", 1); ((Deletable) getKmlObject()).writeDelete(kml); kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/NetworkLink.java",".java","1935","62","package kmlframework.kml; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public class NetworkLink extends Feature { private Boolean refreshVisibility; private Boolean flyToView; private Link link; public NetworkLink() {} public NetworkLink(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines,String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData, Boolean refreshVisibility, Boolean flyToView, Link link) { super(name, visibility, open, atomAuthor, atomLink, address, xalAddressDetails, phoneNumber, snippet, snippetMaxLines, description, abstractView, timePrimitive, styleUrl, styleSelectors, region, extendedData); this.refreshVisibility = refreshVisibility; this.flyToView = flyToView; this.link = link; } public boolean isRefreshVisibility() { return refreshVisibility; } public void setRefreshVisibility(boolean refreshVisibility) { this.refreshVisibility = refreshVisibility; } public Boolean isFlyToView() { return flyToView; } public void setFlyToView(Boolean flyToView) { this.flyToView = flyToView; } public Link getLink() { return link; } public void setLink(Link link) { this.link = link; } public void write(Kml kml) throws KmlException { kml.println("""", 1); writeInner(kml); if (refreshVisibility != null) { kml.println("""" + booleanToInt(refreshVisibility) + """"); } if (flyToView != null) { kml.println("""" + booleanToInt(flyToView) + """"); } if (link != null) { link.write(kml); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/LabelStyle.java",".java","626","30","package kmlframework.kml; public class LabelStyle extends ColorStyle { private Double scale; public LabelStyle() {} public LabelStyle(String color, ColorModeEnum colorMode, Double scale) { super(color, colorMode); this.scale = scale; } public Double getScale() { return scale; } public void setScale(Double scale) { this.scale = scale; } public void write(Kml kml) throws KmlException { kml.println("""", 1); super.writeInner(kml); if (scale != null) { kml.println("""" + scale + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Polygon.java",".java","2344","93","package kmlframework.kml; import java.util.List; public class Polygon extends Geometry { private Boolean extrude; private Boolean tessellate; private AltitudeModeEnum altitudeMode; private LinearRing outerBoundary; private List innerBoundaries; public Polygon() {} public Polygon(Boolean extrude, Boolean tessellate, AltitudeModeEnum altitudeMode, LinearRing outerBoundary, List innerBoundaries) { this.extrude = extrude; this.tessellate = tessellate; this.altitudeMode = altitudeMode; this.outerBoundary = outerBoundary; this.innerBoundaries = innerBoundaries; } public Boolean getExtrude() { return extrude; } public void setExtrude(Boolean extrude) { this.extrude = extrude; } public Boolean getTessellate() { return tessellate; } public void setTessellate(Boolean tessellate) { this.tessellate = tessellate; } public AltitudeModeEnum getAltitudeMode() { return altitudeMode; } public void setAltitudeMode(AltitudeModeEnum altitudeMode) { this.altitudeMode = altitudeMode; } public LinearRing getOuterBoundary() { return outerBoundary; } public void setOuterBoundary(LinearRing outerBoundary) { this.outerBoundary = outerBoundary; } public List getInnerBoundaries() { return innerBoundaries; } public void setInnerBoundaries(List innerBoundaries) { this.innerBoundaries = innerBoundaries; } public void write(Kml kml) throws KmlException { // We validate the data if (outerBoundary == null) { throw new KmlException(""An outerBoundary is required in a Polygon""); } kml.println("""", 1); if (extrude != null) { kml.println("""" + booleanToInt(extrude) + """"); } if (tessellate != null) { kml.println("""" + booleanToInt(tessellate) + """"); } if (altitudeMode != null) { kml.println("""" + altitudeMode + """"); } kml.println("""", 1); outerBoundary.write(kml); kml.println(-1, """"); if (innerBoundaries != null) { for (LinearRing innerBounadry : innerBoundaries) { kml.println("""", 1); innerBounadry.write(kml); kml.println(-1, """"); } } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ListStyle.java",".java","1643","71","package kmlframework.kml; public class ListStyle extends KmlObject { private ListItemTypeEnum listItemType; private String bgColor; private String itemIconState; private String href; public ListStyle() {} public ListStyle(ListItemTypeEnum listItemType, String bgColor, String itemIconState, String href) { this.listItemType = listItemType; this.bgColor = bgColor; this.itemIconState = itemIconState; this.href = href; } public ListItemTypeEnum getListItemType() { return listItemType; } public void setListItemType(ListItemTypeEnum listItemType) { this.listItemType = listItemType; } public String getBgColor() { return bgColor; } public void setBgColor(String bgColor) { this.bgColor = bgColor; } public String getItemIconState() { return itemIconState; } public void setItemIconState(String itemIconState) { this.itemIconState = itemIconState; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (listItemType != null) { kml.println("""" + listItemType + """"); } if (bgColor != null) { kml.println("""" + bgColor + """"); } if (itemIconState != null || href != null) { kml.println("""", 1); if (itemIconState != null) { kml.println("""" + itemIconState + """"); } if (href != null) { kml.println("""" + href + """"); } kml.println(-1, """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ScreenOverlay.java",".java","6578","212","package kmlframework.kml; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public class ScreenOverlay extends Overlay implements Deletable { private Double overlayX; private Double overlayY; private UnitEnum overlayXunits; private UnitEnum overlayYunits; private Double screenX; private Double screenY; private UnitEnum screenXunits; private UnitEnum screenYunits; private Double rotationX; private Double rotationY; private UnitEnum rotationXunits; private UnitEnum rotationYunits; private Double sizeX; private Double sizeY; private UnitEnum sizeXunits; private UnitEnum sizeYunits; private Double rotation; public ScreenOverlay() {} public ScreenOverlay(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines,String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData, String color, Integer drawOrder, Icon icon, Double overlayX, Double overlayY, UnitEnum overlayXunits, UnitEnum overlayYunits, Double screenX, Double screenY, UnitEnum screenXunits, UnitEnum screenYunits, Double rotationX, Double rotationY, UnitEnum rotationXunits, UnitEnum rotationYunits, Double sizeX, Double sizeY, UnitEnum sizeXunits, UnitEnum sizeYunits, Double rotation) { super(name, visibility, open, atomAuthor, atomLink, address, xalAddressDetails, phoneNumber, snippet, snippetMaxLines, description, abstractView, timePrimitive, styleUrl, styleSelectors, region, extendedData, color, drawOrder, icon); this.overlayX = overlayX; this.overlayY = overlayY; this.overlayXunits = overlayXunits; this.overlayYunits = overlayYunits; this.screenX = screenX; this.screenY = screenY; this.screenXunits = screenXunits; this.screenYunits = screenYunits; this.rotationX = rotationX; this.rotationY = rotationY; this.rotationXunits = rotationXunits; this.rotationYunits = rotationYunits; this.sizeX = sizeX; this.sizeY = sizeY; this.sizeXunits = sizeXunits; this.sizeYunits = sizeYunits; this.rotation = rotation; } public Double getOverlayX() { return overlayX; } public void setOverlayX(Double overlayX) { this.overlayX = overlayX; } public Double getOverlayY() { return overlayY; } public void setOverlayY(Double overlayY) { this.overlayY = overlayY; } public UnitEnum getOverlayXunits() { return overlayXunits; } public void setOverlayXunits(UnitEnum overlayXunits) { this.overlayXunits = overlayXunits; } public UnitEnum getOverlayYunits() { return overlayYunits; } public void setOverlayYunits(UnitEnum overlayYunits) { this.overlayYunits = overlayYunits; } public Double getScreenX() { return screenX; } public void setScreenX(Double screenX) { this.screenX = screenX; } public Double getScreenY() { return screenY; } public void setScreenY(Double screenY) { this.screenY = screenY; } public UnitEnum getScreenXunits() { return screenXunits; } public void setScreenXunits(UnitEnum screenXunits) { this.screenXunits = screenXunits; } public UnitEnum getScreenYunits() { return screenYunits; } public void setScreenYunits(UnitEnum screenYunits) { this.screenYunits = screenYunits; } public Double getRotationX() { return rotationX; } public void setRotationX(Double rotationX) { this.rotationX = rotationX; } public Double getRotationY() { return rotationY; } public void setRotationY(Double rotationY) { this.rotationY = rotationY; } public UnitEnum getRotationXunits() { return rotationXunits; } public void setRotationXunits(UnitEnum rotationXunits) { this.rotationXunits = rotationXunits; } public UnitEnum getRotationYunits() { return rotationYunits; } public void setRotationYunits(UnitEnum rotationYunits) { this.rotationYunits = rotationYunits; } public Double getSizeX() { return sizeX; } public void setSizeX(Double sizeX) { this.sizeX = sizeX; } public Double getSizeY() { return sizeY; } public void setSizeY(Double sizeY) { this.sizeY = sizeY; } public UnitEnum getSizeXunits() { return sizeXunits; } public void setSizeXunits(UnitEnum sizeXunits) { this.sizeXunits = sizeXunits; } public UnitEnum getSizeYunits() { return sizeYunits; } public void setSizeYunits(UnitEnum sizeYunits) { this.sizeYunits = sizeYunits; } public Double getRotation() { return rotation; } public void setRotation(Double rotation) { this.rotation = rotation; } public void write(Kml kml) throws KmlException { kml.println("""", 1); super.writeInner(kml); if (overlayX != null || overlayY != null || overlayXunits != null || overlayYunits != null) { kml.println(""""); } if (screenX != null || screenY != null || screenXunits != null || screenYunits != null) { kml.println(""""); } if (rotationX != null || rotationY != null || rotationXunits != null || rotationYunits != null) { kml.println(""""); } if (sizeX != null || sizeY != null || sizeXunits != null || sizeYunits != null) { kml.println(""""); } if (rotation != null) { kml.println("""" + rotation + """"); } kml.println(-1, """"); } public void writeDelete(Kml kml) throws KmlException { kml.println(""""); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/AbstractView.java",".java","1970","93","package kmlframework.kml; public abstract class AbstractView extends KmlObject { private Double longitude; private Double latitude; private Double altitude; private Double heading; private Double tilt; private AltitudeModeEnum altitudeMode; public AbstractView() {} public AbstractView(Double longitude, Double latitude, Double altitude, Double heading, Double tilt, AltitudeModeEnum altitudeMode) { this.longitude = longitude; this.latitude = latitude; this.altitude = altitude; this.heading = heading; this.tilt = tilt; this.altitudeMode = altitudeMode; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getAltitude() { return altitude; } public void setAltitude(Double altitude) { this.altitude = altitude; } public Double getHeading() { return heading; } public void setHeading(Double heading) { this.heading = heading; } public Double getTilt() { return tilt; } public void setTilt(Double tilt) { this.tilt = tilt; } public AltitudeModeEnum getAltitudeMode() { return altitudeMode; } public void setAltitudeMode(AltitudeModeEnum altitudeMode) { this.altitudeMode = altitudeMode; } public void writeInner(Kml kml) throws KmlException { if (longitude != null) { kml.println("""" + longitude + """"); } if (latitude != null) { kml.println("""" + latitude + """"); } if (altitude != null) { kml.println("""" + altitude + """"); } if (heading != null) { kml.println("""" + heading + """"); } if (tilt != null) { kml.println("""" + tilt + """"); } if (altitudeMode != null) { kml.println("""" + altitudeMode + """"); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Document.java",".java","1626","50","package kmlframework.kml; import java.util.ArrayList; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public class Document extends Container implements Deletable { private List schemas; public Document() {} public Document(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines,String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData, List feauters, List schemas) { super(name, visibility, open, atomAuthor, atomLink, address, xalAddressDetails, phoneNumber, snippet, snippetMaxLines, description, abstractView, timePrimitive, styleUrl, styleSelectors, region, extendedData, feauters); this.schemas = schemas; } public List getSchemas() { return schemas; } public void setSchemas(List schemas) { this.schemas = schemas; } public void addSchema(Schema schema) { if (schemas == null) { schemas = new ArrayList(); } schemas.add(schema); } public void write(Kml kml) throws KmlException { kml.println("""", 1); writeInner(kml); if (schemas != null) { for (Schema schema: schemas) schema.write(kml); } kml.println(-1, """"); } public void writeDelete(Kml kml) throws KmlException { kml.println(""""); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Region.java",".java","4354","175","package kmlframework.kml; public class Region extends KmlObject { private Double north; private Double south; private Double east; private Double west; private Double minAltitude; private Double maxAltitude; private AltitudeModeEnum altitudeMode; private Double minLodPixels; private Double maxLodPixels; private Double minFadeExtent; private Double maxFadeExtent; public Region() {} public Region(Double north, Double south, Double east, Double west, Double minAltitude, Double maxAltitude, AltitudeModeEnum altitudeMode, Double minLodPixels, Double maxLodPixels, Double minFadeExtent, Double maxFadeExtent) { this.north = north; this.south = south; this.east = east; this.west = west; this.minAltitude = minAltitude; this.maxAltitude = maxAltitude; this.altitudeMode = altitudeMode; this.minLodPixels = minLodPixels; this.maxLodPixels = maxLodPixels; this.minFadeExtent = minFadeExtent; this.maxFadeExtent = maxFadeExtent; } public Double getNorth() { return north; } public void setNorth(Double north) { this.north = north; } public Double getSouth() { return south; } public void setSouth(Double south) { this.south = south; } public Double getEast() { return east; } public void setEast(Double east) { this.east = east; } public Double getWest() { return west; } public void setWest(Double west) { this.west = west; } public Double getMinAltitude() { return minAltitude; } public void setMinAltitude(Double minAltitude) { this.minAltitude = minAltitude; } public Double getMaxAltitude() { return maxAltitude; } public void setMaxAltitude(Double maxAltitude) { this.maxAltitude = maxAltitude; } public AltitudeModeEnum getAltitudeMode() { return altitudeMode; } public void setAltitudeMode(AltitudeModeEnum altitudeMode) { this.altitudeMode = altitudeMode; } public Double getMinLodPixels() { return minLodPixels; } public void setMinLodPixels(Double minLodPixels) { this.minLodPixels = minLodPixels; } public Double getMaxLodPixels() { return maxLodPixels; } public void setMaxLodPixels(Double maxLodPixels) { this.maxLodPixels = maxLodPixels; } public Double getMinFadeExtent() { return minFadeExtent; } public void setMinFadeExtent(Double minFadeExtent) { this.minFadeExtent = minFadeExtent; } public Double getMaxFadeExtent() { return maxFadeExtent; } public void setMaxFadeExtent(Double maxFadeExtent) { this.maxFadeExtent = maxFadeExtent; } public void write(Kml kml) throws KmlException { // We validate the data if (north == null) { throw new KmlException(""north is required in Region""); } if (south == null) { throw new KmlException(""south is required in Region""); } if (east == null) { throw new KmlException(""east is required in Region""); } if (west == null) { throw new KmlException(""west is required in Region""); } kml.println("""", 1); kml.println("""", 1); kml.println("""" + north + """"); kml.println("""" + south + """"); kml.println("""" + east + """"); kml.println("""" + west + """"); kml.println(-1, """"); kml.println(-1, """"); if (minAltitude != null) { kml.println("""" + minAltitude + """"); } if (maxAltitude != null) { kml.println("""" + maxAltitude + """"); } if (altitudeMode!= null) { kml.println("""" + altitudeMode + """"); } if (minLodPixels != null || maxLodPixels != null || minFadeExtent != null || maxFadeExtent != null) { kml.println("""", 1); if (minLodPixels != null) { kml.println("""" + minLodPixels + """"); } if (maxLodPixels != null) { kml.println("""" + maxLodPixels + """"); } if (minFadeExtent != null) { kml.println("""" + minFadeExtent + """"); } if (minFadeExtent != null) { kml.println("""" + minFadeExtent + """"); } if (maxFadeExtent != null) { kml.println("""" + maxFadeExtent + """"); } kml.println(-1, """"); kml.println(-1, """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Icon.java",".java","580","17","package kmlframework.kml; public class Icon extends Link { public Icon() {} public Icon(String href, RefreshModeEnum refreshMode, Double refreshInterval, ViewRefreshModeEnum viewRefreshMode, Double viewRefreshTime, Double viewBoundScale, ViewFormat viewFormat, String httpQuery) { super(href, refreshMode, refreshInterval, viewRefreshMode, viewRefreshTime, viewBoundScale, viewFormat, httpQuery); } public void write(Kml kml) throws KmlException { kml.println("""", 1); writeInner(kml); kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Create.java",".java","310","17","package kmlframework.kml; public class Create extends UpdateElement { public Create() {} public Create(KmlObject kmlObject) { setKmlObject(kmlObject); } public void write(Kml kml) throws KmlException { kml.println("""", 1); getKmlObject().write(kml); kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/PolyStyle.java",".java","917","43","package kmlframework.kml; public class PolyStyle extends ColorStyle { private Boolean fill; private Boolean outline; public PolyStyle() {} public PolyStyle(String color, ColorModeEnum colorMode, Boolean fill, Boolean outline) { super(color, colorMode); this.fill = fill; this.outline = outline; } public Boolean getFill() { return fill; } public void setFill(Boolean fill) { this.fill = fill; } public Boolean getOutline() { return outline; } public void setOutline(Boolean outline) { this.outline = outline; } public void write(Kml kml) throws KmlException { kml.println("""", 1); super.writeInner(kml); if (fill != null) { kml.println("""" + booleanToInt(fill) + """"); } if (outline != null) { kml.println("""" + booleanToInt(outline) + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Model.java",".java","4741","222","package kmlframework.kml; import java.util.List; public class Model extends Geometry { private AltitudeModeEnum altitudeMode; private Double longitude; private Double latitude; private Double altitude; private Double heading; private Double tilt; private Double roll; private Double scaleX; private Double scaleY; private Double scaleZ; private Link link; private List resourceMap; private String locationID; private String orientationID; private String scaleID; public Model() {} public Model(AltitudeModeEnum altitudeMode, Double longitude, Double latitude, Double altitude, Double heading, Double tilt, Double roll, Double scaleX, Double scaleY, Double scaleZ, Link link, List resourceMap) { this.altitudeMode = altitudeMode; this.longitude = longitude; this.latitude = latitude; this.altitude = altitude; this.heading = heading; this.tilt = tilt; this.roll = roll; this.scaleX = scaleX; this.scaleY = scaleY; this.scaleZ = scaleZ; this.link = link; this.resourceMap = resourceMap; } public AltitudeModeEnum getAltitudeMode() { return altitudeMode; } public void setAltitudeMode(AltitudeModeEnum altitudeMode) { this.altitudeMode = altitudeMode; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getAltitude() { return altitude; } public void setAltitude(Double altitude) { this.altitude = altitude; } public Double getHeading() { return heading; } public void setHeading(Double heading) { this.heading = heading; } public Double getTilt() { return tilt; } public void setTilt(Double tilt) { this.tilt = tilt; } public Double getRoll() { return roll; } public void setRoll(Double roll) { this.roll = roll; } public Double getScaleX() { return scaleX; } public void setScaleX(Double scaleX) { this.scaleX = scaleX; } public Double getScaleY() { return scaleY; } public void setScaleY(Double scaleY) { this.scaleY = scaleY; } public Double getScaleZ() { return scaleZ; } public void setScaleZ(Double scaleZ) { this.scaleZ = scaleZ; } public Link getLink() { return link; } public void setLink(Link link) { this.link = link; } public List getResourceMap() { return resourceMap; } public void setResourceMap(List resourceMap) { this.resourceMap = resourceMap; } public String getLocationID() { return locationID; } public void setLocationID(String id) { locationID=id; } public String getOrientationID() { return orientationID; } public void setOrientationID(String id) { orientationID=id; } public String getScaleID() { return scaleID; } public void setScaleID(String id) { scaleID=id; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (altitudeMode != null) { kml.println("""" + altitudeMode + """"); } if (longitude != null || latitude != null || altitude != null) { kml.println("""", 1); if (longitude != null) { kml.println("""" + longitude + """"); } if (latitude != null) { kml.println("""" + latitude + """"); } if (altitude != null) { kml.println("""" + altitude + """"); } kml.println(-1, """"); } if (heading != null || tilt != null || roll != null) { kml.println("""", 1); if (heading != null) { kml.println("""" + heading + """"); } if (tilt != null) { kml.println("""" + tilt + """"); } if (roll != null) { kml.println("""" + roll + """"); } kml.println(-1, """"); } if (scaleX != null || scaleY != null || scaleZ != null) { kml.println("""", 1); if (scaleX != null) { kml.println("""" + scaleX + """"); } if (scaleY != null) { kml.println("""" + scaleY+ """"); } if (scaleZ != null) { kml.println("""" + scaleZ + """"); } kml.println(-1, """"); } if (link != null) { link.write(kml); } if (resourceMap != null) { kml.println("""", -1); for (Alias alias : resourceMap) { alias.write(kml); } kml.println(-1, """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/BalloonStyle.java",".java","1528","67","package kmlframework.kml; public class BalloonStyle extends KmlObject { private String bgColor; private String textColor; private String text; private DisplayModeEnum displayMode; public BalloonStyle() {} public BalloonStyle(String bgColor, String textColor, String text, DisplayModeEnum displayMode) { this.bgColor = bgColor; this.textColor = textColor; this.text = text; this.displayMode = displayMode; } public String getBgColor() { return bgColor; } public void setBgColor(String bgColor) { this.bgColor = bgColor; } public String getTextColor() { return textColor; } public void setTextColor(String textColor) { this.textColor = textColor; } public String getText() { return text; } public void setText(String text) { this.text = text; } public DisplayModeEnum getDisplayMode() { return displayMode; } public void setDisplayMode(DisplayModeEnum displayMode) { this.displayMode = displayMode; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (bgColor != null) { kml.println("""" + bgColor + """"); } if (textColor != null) { kml.println("""" + textColor + """"); } if (text != null) { kml.println("""" + text + """"); } if (displayMode != null) { kml.println("""" + (displayMode == DisplayModeEnum._default ? ""default"" : displayMode) + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/DisplayModeEnum.java",".java","75","6","package kmlframework.kml; public enum DisplayModeEnum { _default, hide } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/GridOriginEnum.java",".java","80","6","package kmlframework.kml; public enum GridOriginEnum { lowerLeft, upperLeft } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/StyleSelector.java",".java","85","4","package kmlframework.kml; public abstract class StyleSelector extends KmlObject { }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/TimeStamp.java",".java","520","28","package kmlframework.kml; public class TimeStamp extends TimePrimitive { private String when; public TimeStamp() {} public TimeStamp(String when) { this.when = when; } public String getWhen() { return when; } public void setWhen(String when) { this.when = when; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (when != null) { kml.println("""" + when + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/StyleMap.java",".java","456","25","package kmlframework.kml; import java.util.List; public class StyleMap extends StyleSelector { private List pairs; public StyleMap() {} public StyleMap(List pairs) { this.pairs = pairs; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (pairs != null) { for (Pair pair : pairs) { pair.write(kml); } } kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/GroundOverlay.java",".java","3335","122","package kmlframework.kml; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public class GroundOverlay extends Overlay implements Deletable { private Double altitude; private AltitudeModeEnum altitudeMode; private Double north; private Double south; private Double east; private Double west; private Double rotation; public GroundOverlay() {} public GroundOverlay(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines,String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData, String color, Integer drawOrder, Icon icon, Double alititude, AltitudeModeEnum altitudeMode, Double north, Double south, Double east, Double west, Double rotation) { super(name, visibility, open, atomAuthor, atomLink, address, xalAddressDetails, phoneNumber, snippet, snippetMaxLines, description, abstractView, timePrimitive, styleUrl, styleSelectors, region, extendedData, color, drawOrder, icon); this.altitude = alititude; this.altitudeMode = altitudeMode; this.north = north; this.south = south; this.east = east; this.west = west; this.rotation = rotation; } public Double getAltitude() { return altitude; } public void setAltitude(Double altitude) { this.altitude = altitude; } public AltitudeModeEnum getAltitudeMode() { return altitudeMode; } public void setAltitudeMode(AltitudeModeEnum altitudeMode) { this.altitudeMode = altitudeMode; } public Double getNorth() { return north; } public void setNorth(Double north) { this.north = north; } public Double getSouth() { return south; } public void setSouth(Double south) { this.south = south; } public Double getEast() { return east; } public void setEast(Double east) { this.east = east; } public Double getWest() { return west; } public void setWest(Double west) { this.west = west; } public Double getRotation() { return rotation; } public void setRotation(Double rotation) { this.rotation = rotation; } public void write(Kml kml) throws KmlException { kml.println("""", 1); super.writeInner(kml); if (altitude != null) { kml.println("""" + altitude + """"); } if (altitudeMode != null) { kml.println("""" + altitudeMode + """"); } if (north != null || south != null || east != null || west != null || rotation != null) { kml.println("""", 1); if (north != null) { kml.println("""" + north + """"); } if (south != null) { kml.println("""" + south + """"); } if (east != null) { kml.println("""" + east + """"); } if (west != null) { kml.println("""" + west + """"); } if (rotation != null) { kml.println("""" + rotation + """"); } kml.println(-1, """"); } kml.println(-1, """"); } public void writeDelete(Kml kml) throws KmlException { kml.println(""""); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/MultiGeometry.java",".java","683","32","package kmlframework.kml; import java.util.List; public class MultiGeometry extends Geometry { private List geometries; public MultiGeometry() {} public MultiGeometry(List geometries) { this.geometries = geometries; } public List getGeometries() { return geometries; } public void setGeometries(List geometries) { this.geometries = geometries; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (geometries != null) { for (Geometry geometry : geometries) { geometry.write(kml); } } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Overlay.java",".java","1636","60","package kmlframework.kml; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public abstract class Overlay extends Feature { private String color; private Integer drawOrder; private Icon icon; public Overlay() {} public Overlay(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines,String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData, String color, Integer drawOrder, Icon icon) { super(name, visibility, open, atomAuthor, atomLink, address, xalAddressDetails, phoneNumber, snippet, snippetMaxLines, description, abstractView, timePrimitive, styleUrl, styleSelectors, region, extendedData); this.color = color; this.drawOrder = drawOrder; this.icon = icon; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public Integer getDrawOrder() { return drawOrder; } public void setDrawOrder(Integer drawOrder) { this.drawOrder = drawOrder; } public Icon getIcon() { return icon; } public void setIcon(Icon icon) { this.icon = icon; } public void writeInner(Kml kml) throws KmlException { super.writeInner(kml); if (color != null) { kml.println("""" + color + """"); } if (drawOrder != null) { kml.println("""" + drawOrder + """"); } if (icon != null) { icon.write(kml); } } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Link.java",".java","3076","122","package kmlframework.kml; public class Link extends KmlObject { private String href; private RefreshModeEnum refreshMode; private Double refreshInterval; private ViewRefreshModeEnum viewRefreshMode; private Double viewRefreshTime; private Double viewBoundScale; private ViewFormat viewFormat; private String httpQuery; public Link() {} public Link(String href, RefreshModeEnum refreshMode, Double refreshInterval, ViewRefreshModeEnum viewRefreshMode, Double viewRefreshTime, Double viewBoundScale, ViewFormat viewFormat, String httpQuery) { this.href = href; this.refreshMode = refreshMode; this.refreshInterval = refreshInterval; this.viewRefreshMode = viewRefreshMode; this.viewRefreshTime = viewRefreshTime; this.viewFormat = viewFormat; this.httpQuery = httpQuery; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public RefreshModeEnum getRefreshMode() { return refreshMode; } public void setRefreshMode(RefreshModeEnum refreshMode) { this.refreshMode = refreshMode; } public Double getRefreshInterval() { return refreshInterval; } public void setRefreshInterval(Double refreshInterval) { this.refreshInterval = refreshInterval; } public ViewRefreshModeEnum getViewRefreshMode() { return viewRefreshMode; } public void setViewRefreshMode(ViewRefreshModeEnum viewRefreshMode) { this.viewRefreshMode = viewRefreshMode; } public Double getViewRefreshTime() { return viewRefreshTime; } public void setViewRefreshTime(Double viewRefreshTime) { this.viewRefreshTime = viewRefreshTime; } public Double getViewBoundScale() { return viewBoundScale; } public void setViewBoundScale(Double viewBoundScale) { this.viewBoundScale = viewBoundScale; } public ViewFormat getViewFormat() { return viewFormat; } public void setViewFormat(ViewFormat viewFormat) { this.viewFormat = viewFormat; } public String getHttpQuery() { return httpQuery; } public void setHttpQuery(String httpQuery) { this.httpQuery = httpQuery; } public void write(Kml kml) throws KmlException { kml.println("""", 1); writeInner(kml); kml.println(-1, """"); } protected void writeInner(Kml kml) throws KmlException { if (href != null) { kml.println("""" + href + """"); } if (refreshMode != null) { kml.println("""" + refreshMode + """"); } if (refreshInterval != null) { kml.println("""" + refreshInterval + """"); } if (viewRefreshMode != null) { kml.println("""" + viewRefreshMode + """"); } if (viewRefreshTime != null) { kml.println("""" + viewRefreshTime + """"); } if (viewBoundScale != null) { kml.println("""" + viewBoundScale + """"); } if (viewFormat != null) { viewFormat.write(kml); } if (httpQuery != null) { kml.println("""" + httpQuery + """"); } } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Feature.java",".java","5821","248","package kmlframework.kml; import java.util.ArrayList; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public abstract class Feature extends KmlObject { private String name; private Boolean visibility; private Boolean open; private AtomAuthor atomAuthor; private AtomLink atomLink; private String address; private String xalAddressDeatails; private String phoneNumber; private String snippet; private Integer snippetMaxLines; private String description; private AbstractView abstractView; private TimePrimitive timePrimitive; private String styleUrl; private List styleSelectors; private Region region; private ExtendedData extendedData; public Feature() {} public Feature(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines,String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData) { this.name = name; this.visibility = visibility; this.open = open; this.atomAuthor = atomAuthor; this.atomLink = atomLink; this.address = address; this.xalAddressDeatails = xalAddressDetails; this.phoneNumber = phoneNumber; this.snippet = snippet; this.snippetMaxLines = snippetMaxLines; this.description = description; this.abstractView = abstractView; this.timePrimitive = timePrimitive; this.styleUrl = styleUrl; this.styleSelectors = styleSelectors; this.region = region; this.extendedData = extendedData; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean isVisibility() { return visibility; } public void setVisibility(Boolean visibility) { this.visibility = visibility; } public boolean isOpen() { return open; } public void setOpen(boolean open) { this.open = open; } public AtomAuthor getAtomAuthor() { return atomAuthor; } public void setAtomAuthor(AtomAuthor atomAuthor) { this.atomAuthor = atomAuthor; } public AtomLink getAtomLink() { return atomLink; } public void setAtomLink(AtomLink link) { this.atomLink = link; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getXalAddressDeatails() { return xalAddressDeatails; } public void setXalAddressDeatails(String xalAddressDeatails) { this.xalAddressDeatails = xalAddressDeatails; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getSnippet() { return snippet; } public void setSnippet(String snippet) { this.snippet = snippet; } public Integer getSnippetMaxLines() { return snippetMaxLines; } public void setSnippetMaxLines(Integer snippetMaxLines) { this.snippetMaxLines = snippetMaxLines; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public AbstractView getAbstractView() { return abstractView; } public void setAbstractView(AbstractView abstractView) { this.abstractView = abstractView; } public String getStyleUrl() { return styleUrl; } public void setStyleUrl(String styleUrl) { this.styleUrl = styleUrl; } public List getStyleSelectors() { return styleSelectors; } public void setStyleSelectors(List styleSelectors) { this.styleSelectors = styleSelectors; } public void addStyleSelector(StyleSelector styleSelector) { if (styleSelectors == null) { styleSelectors = new ArrayList(); } styleSelectors.add(styleSelector); } public TimePrimitive getTimePrimitive() { return timePrimitive; } public void setTimePrimitive(TimePrimitive timePrimitive) { this.timePrimitive = timePrimitive; } public Region getRegion() { return region; } public void setRegion(Region region) { this.region = region; } public ExtendedData getExtendedData() { return extendedData; } public void setExtendedData(ExtendedData extendedData) { this.extendedData = extendedData; } public void writeInner(Kml kml) throws KmlException { if (name != null) { kml.println("""" + name + """"); } if (visibility != null) { kml.println("""" + booleanToInt(visibility) + """"); } if (open != null) { kml.println("""" + booleanToInt(open) + """"); } if (atomAuthor != null) { atomAuthor.write(kml); } if (atomLink != null) { atomLink.write(kml); } if (address != null) { kml.println(""
    "" + address + ""
    ""); } if (xalAddressDeatails != null) { kml.println("""" + xalAddressDeatails + """"); } if (phoneNumber != null) { kml.println("""" + phoneNumber + """"); } if (snippet != null) { kml.println("""" + snippet + """"); } if (description != null) { kml.println("""" + description + """"); } if (abstractView != null) { abstractView.write(kml); } if (timePrimitive != null) { timePrimitive.write(kml); } if (styleUrl!= null) { kml.println("""" + styleUrl + """"); } if (styleSelectors != null) { for (StyleSelector styleSelector : styleSelectors) { styleSelector.write(kml); } } if (region != null) { region.write(kml); } if (extendedData != null) { extendedData.write(kml); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Geometry.java",".java","80","5","package kmlframework.kml; public abstract class Geometry extends KmlObject { } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/StyleStateEnum.java",".java","77","6","package kmlframework.kml; public enum StyleStateEnum { normal, highlight } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/TimePrimitive.java",".java","85","5","package kmlframework.kml; public abstract class TimePrimitive extends KmlObject { } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Folder.java",".java","1148","27","package kmlframework.kml; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public class Folder extends Container implements Deletable { public Folder() {} public Folder(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines,String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData, List feauters) { super(name, visibility, open, atomAuthor, atomLink, address, xalAddressDetails, phoneNumber, snippet, snippetMaxLines, description, abstractView, timePrimitive, styleUrl, styleSelectors, region, extendedData, feauters); } public void write(Kml kml) throws KmlException { kml.println("""", 1); writeInner(kml); kml.println(-1, """"); } public void writeDelete(Kml kml) throws KmlException { kml.println(""""); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ListItemTypeEnum.java",".java","113","6","package kmlframework.kml; public enum ListItemTypeEnum { check, checkOffOnly, checkHideChildren, radioFolder } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ExtendedData.java",".java","2151","85","package kmlframework.kml; import java.util.List; public class ExtendedData extends KmlObject { private List dataElements; private String schemaUrl; private List simpleDataElements; private String nameSpace; private String customContent; public ExtendedData() {} public ExtendedData(List dataElements, String schemaUrl, List simpleDataElements, String nameSpace, String customContent) { this.dataElements = dataElements; this.schemaUrl = schemaUrl; this.simpleDataElements = simpleDataElements; this.nameSpace = nameSpace; this.customContent = customContent; } public List getDataElements() { return dataElements; } public void setDataElements(List dataElements) { this.dataElements = dataElements; } public String getSchemaUrl() { return schemaUrl; } public void setSchemaUrl(String schemaUrl) { this.schemaUrl = schemaUrl; } public List getSimpleDataElements() { return simpleDataElements; } public void setSimpleDataElements(List simpleDataElements) { this.simpleDataElements = simpleDataElements; } public String getNameSpace() { return nameSpace; } public void setNameSpace(String nameSpace) { this.nameSpace = nameSpace; } public String getCustomContent() { return customContent; } public void setCustomContent(String customContent) { this.customContent = customContent; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (dataElements != null) { for (Data data : dataElements) { data.write(kml); } } if (schemaUrl != null || simpleDataElements != null) { kml.println("""", 1); if (simpleDataElements != null) { for (SimpleData simpleData : simpleDataElements) { simpleData.write(kml); } } kml.println(""""); } if (customContent != null) { kml.println(customContent); } kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ColorModeEnum.java",".java","73","6","package kmlframework.kml; public enum ColorModeEnum { normal, random } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/LinearRing.java",".java","2202","86","package kmlframework.kml; import java.util.List; public class LinearRing extends Geometry { private Boolean extrude; private Boolean tessellate; private AltitudeModeEnum altitudeMode; private List coordinates; public LinearRing() {} public LinearRing(Boolean extrude, Boolean tessellate, AltitudeModeEnum altitudeMode, List coordinates) { this.extrude = extrude; this.tessellate = tessellate; this.altitudeMode = altitudeMode; this.coordinates = coordinates; } public Boolean getExtrude() { return extrude; } public void setExtrude(Boolean extrude) { this.extrude = extrude; } public Boolean getTessellate() { return tessellate; } public void setTessellate(Boolean tessellate) { this.tessellate = tessellate; } public AltitudeModeEnum getAltitudeMode() { return altitudeMode; } public void setAltitudeMode(AltitudeModeEnum altitudeMode) { this.altitudeMode = altitudeMode; } public List getCoordinates() { return coordinates; } public void setCoordinates(List coordinates) { this.coordinates = coordinates; } public void write(Kml kml) throws KmlException { // We validate the data if (coordinates == null || coordinates.size() < 3) { throw new KmlException(""LineString must contain at least 3 points""); } kml.println("""", 1); if (extrude != null) { kml.println("""" + booleanToInt(extrude) + """"); } if (tessellate != null) { kml.println("""" + booleanToInt(tessellate) + """"); } if (altitudeMode != null) { kml.println("""" + altitudeMode + """"); } kml.print(""""); boolean firstLoop = true; for (Point point : coordinates) { if (firstLoop) { firstLoop = false; } else { kml.printNoIndent("" ""); } kml.printNoIndent(point.getLongitudeLatitudeAltitudeString()); } // We add the first coordinate to the end, as KML require the first coordinate to be equal to the last kml.print("" "" + coordinates.get(0).getLongitudeLatitudeAltitudeString()); kml.println(""""); kml.println(-1, ""
    ""); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/SimpleData.java",".java","592","35","package kmlframework.kml; public class SimpleData extends KmlObject { private String name; private String value; public SimpleData() {} public SimpleData(String name, String value) { this.name = name; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public void write(Kml kml) throws KmlException { kml.println("""" + value + """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Container.java",".java","1376","45","package kmlframework.kml; import java.util.ArrayList; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public abstract class Container extends Feature { List features; public Container() { } public Container(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines,String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData, List feauters) { super(name, visibility, open, atomAuthor, atomLink, address, xalAddressDetails, phoneNumber, snippet, snippetMaxLines, description, abstractView, timePrimitive, styleUrl, styleSelectors, region, extendedData); this.features = feauters; } public List getFeatures() { return features; } public void setFeatures(List features) { this.features = features; } public void addFeature(Feature feature) { if (features == null) { features = new ArrayList(); } features.add(feature); } public void writeInner(Kml kml) throws KmlException { super.writeInner(kml); if (features != null) { for (Feature feature: features) { feature.write(kml); } } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/UpdateElement.java",".java","409","23","package kmlframework.kml; public abstract class UpdateElement { private KmlObject kmlObject; public UpdateElement() {} public UpdateElement(KmlObject kmlObject) { this.kmlObject = kmlObject; } public KmlObject getKmlObject() { return kmlObject; } public void setKmlObject(KmlObject kmlObject) { this.kmlObject = kmlObject; } public abstract void write(Kml kml) throws KmlException; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Point.java",".java","2106","91","package kmlframework.kml; public class Point extends Geometry { private Boolean extrude; private AltitudeModeEnum altitudeMode; private Double longitude; private Double latitude; private Double altitude; public Point() {} public Point(Double longitude, Double latitude) { this.longitude = longitude; this.latitude = latitude; } public Point(Double longitude, Double latitude, Double altitude) { this.longitude = longitude; this.latitude = latitude; this.altitude = altitude; } public Point(Boolean extrude, AltitudeModeEnum altitudeMode, Double longitude, Double latitude, Double altitude) { this.extrude = extrude; this.altitudeMode = altitudeMode; this.longitude = longitude; this.latitude = latitude; this.altitude = altitude; } public Boolean getExtrude() { return extrude; } public void setExtrude(Boolean extrude) { this.extrude = extrude; } public AltitudeModeEnum getAltitudeMode() { return altitudeMode; } public void setAltitudeMode(AltitudeModeEnum altitudeMode) { this.altitudeMode = altitudeMode; } public Double getLongitude() { return longitude; } public void setLongitude(Double longitude) { this.longitude = longitude; } public Double getLatitude() { return latitude; } public void setLatitude(Double latitude) { this.latitude = latitude; } public Double getAltitude() { return altitude; } public void setAltitude(Double altitude) { this.altitude = altitude; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (extrude != null) { kml.println("""" + booleanToInt(extrude) + """"); } if (altitudeMode != null) { kml.println("""" + altitudeMode + """"); } if (longitude != null && latitude != null) { kml.println("""" + getLongitudeLatitudeAltitudeString() + """"); } kml.println(-1, ""
    ""); } public String getLongitudeLatitudeAltitudeString() { return longitude +"","" + latitude + (altitude != null? "","" + altitude : """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/SimpleFieldTypeEnum.java",".java","122","6","package kmlframework.kml; public enum SimpleFieldTypeEnum { string, _int, uint, _short, ushort, _float, _double, bool } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Deletable.java",".java","767","22","/* * Deletable.java Created Oct 14, 2010 by Andrew Butler, PSL */ package kmlframework.kml; /** * Only items that implement this interface can be deleted dynamically from a KML document using * {@link Delete}. As of KML 2.2, the only items that may be deleted are {@link Document}, * {@link Folder}, {@link Placemark}, {@link GroundOverlay}, and {@link ScreenOverlay}. */ public interface Deletable { /** * Writes an abbreviated version of the KML element--an empty element with a single attribute, * the targetId of the object to delete * * @param kml The KML document to write the element to * @throws KmlException If an error occurs writing the element */ public abstract void writeDelete(Kml kml) throws KmlException; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/IconStyle.java",".java","2536","101","package kmlframework.kml; public class IconStyle extends ColorStyle { private Double scale; private Double heading; private String iconHref; private Double hotSpotX; private Double hotSpotY; private UnitEnum hotSpotXunits; private UnitEnum hotSpotYunits; public IconStyle() {} public IconStyle(String color, ColorModeEnum colorMode, Double scale, Double heading, String iconHref, Double hotSpotX, Double hotSpotY, UnitEnum hotSpotXunits, UnitEnum hotSpotYunits) { super(color, colorMode); this.scale = scale; this.heading = heading; this.iconHref = iconHref; this.hotSpotX = hotSpotX; this.hotSpotY = hotSpotY; this.hotSpotXunits = hotSpotXunits; this.hotSpotYunits = hotSpotYunits; } public Double getScale() { return scale; } public void setScale(Double scale) { this.scale = scale; } public Double getHeading() { return heading; } public void setHeading(Double heading) { this.heading = heading; } public String getIconHref() { return iconHref; } public void setIconHref(String iconHref) { this.iconHref = iconHref; } public Double getHotSpotX() { return hotSpotX; } public void setHotSpotX(Double hotSpotX) { this.hotSpotX = hotSpotX; } public Double getHotSpotY() { return hotSpotY; } public void setHotSpotY(Double hotSpotY) { this.hotSpotY = hotSpotY; } public UnitEnum getHotSpotXunits() { return hotSpotXunits; } public void setHotSpotXunits(UnitEnum hotSpotXunits) { this.hotSpotXunits = hotSpotXunits; } public UnitEnum getHotSpotYunits() { return hotSpotYunits; } public void setHotSpotYunits(UnitEnum hotSpotYunits) { this.hotSpotYunits = hotSpotYunits; } public void write(Kml kml) throws KmlException { kml.println("""", 1); super.writeInner(kml); if (scale != null) { kml.println("""" + scale + """"); } if (heading != null) { kml.println("""" + heading + """"); } if (iconHref != null) { kml.println("""", 1); kml.println("""" + iconHref + """"); kml.println(-1, """"); } if (hotSpotX != null || hotSpotY != null || hotSpotXunits != null || hotSpotYunits != null) { kml.println(""""); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/LookAt.java",".java","722","31","package kmlframework.kml; public class LookAt extends AbstractView { private Double range; public LookAt() {} public LookAt(Double longitude, Double latitude, Double altitude, Double heading, Double tilt, AltitudeModeEnum altitudeMode, Double range) { super(longitude, latitude, altitude, heading,tilt, altitudeMode); this.range = range; } public Double getRange() { return range; } public void setRange(Double range) { this.range = range; } public void write(Kml kml) throws KmlException { kml.println("""", 1); super.writeInner(kml); if (range != null) { kml.println("""" + range + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Data.java",".java","979","52","package kmlframework.kml; public class Data extends KmlObject { private String name; private String displayName; private String value; public Data() {} public Data(String name, String displayName, String value) { this.name = name; this.displayName = displayName; this.value = value; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (displayName != null) { kml.println("""" + displayName + """"); } if (value != null) { kml.println("""" + value + """"); } kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/KmlObject.java",".java","1029","54","package kmlframework.kml; import java.util.UUID; public abstract class KmlObject { private String id; private String targetId; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTargetId() { return targetId; } public void setTargetId(String targetId) { this.targetId = targetId; } public abstract void write(Kml kml) throws KmlException; protected String getIdAndTargetIdFormatted(Kml kml) { if (kml.isGenerateObjectIds() && id == null) { setId(""id""+UUID.randomUUID().toString()); } String result = """"; if (id != null) { result += "" id=\"""" + id + ""\""""; } if (targetId != null) { result += "" targetId=\"""" + targetId + ""\""""; } return result; } public static int booleanToInt(boolean booleanValue) { return (booleanValue? 1 : 0); } public static String enumToString(Enum _enum) { if (_enum.toString().startsWith(""_"")) { return _enum.toString().substring(1); } else { return _enum.toString(); } } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ShapeEnum.java",".java","82","6","package kmlframework.kml; public enum ShapeEnum { rectangle, cylinder, sphere } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Placemark.java",".java","1568","49","package kmlframework.kml; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public class Placemark extends Feature implements Deletable { private Geometry geometry; public Placemark() {} public Placemark(String name) { setName(name); } public Placemark(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines,String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData, Geometry geometry) { super(name, visibility, open, atomAuthor, atomLink, address, xalAddressDetails, phoneNumber, snippet, snippetMaxLines, description, abstractView, timePrimitive, styleUrl, styleSelectors, region, extendedData); this.geometry = geometry; } public Geometry getGeometry() { return geometry; } public void setGeometry(Geometry geometry) { this.geometry = geometry; } public void setLocation(double longitude, double latitude) { setGeometry(new Point(longitude, latitude)); } public void write(Kml kml) throws KmlException { kml.println("""", 1); writeInner(kml); if (geometry != null) { geometry.write(kml); } kml.println(-1, """"); } public void writeDelete(Kml kml) throws KmlException { kml.println(""""); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/AltitudeModeEnum.java",".java","103","6","package kmlframework.kml; public enum AltitudeModeEnum { relativeToGround, absolute, clampToGround } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/PhotoOverlay.java",".java","4881","252","package kmlframework.kml; import java.util.List; import kmlframework.atom.AtomAuthor; import kmlframework.atom.AtomLink; public class PhotoOverlay extends Overlay { private Double rotation; private Double leftFov; private Double rightFov; private Double bottomFov; private Double topFov; private Double near; private Integer tileSize; private Integer maxWidth; private Integer maxHeight; private GridOriginEnum gridOrigin; private Point point; private ShapeEnum shape; public PhotoOverlay() { } public PhotoOverlay(String name, Boolean visibility, Boolean open, AtomAuthor atomAuthor, AtomLink atomLink, String address, String xalAddressDetails, String phoneNumber, String snippet, Integer snippetMaxLines, String description, AbstractView abstractView, TimePrimitive timePrimitive, String styleUrl, List styleSelectors, Region region, ExtendedData extendedData, String color, Integer drawOrder, Icon icon, Double rotation, Double leftFov, Double rightFov, Double bottomFov, Double topFov, Double near, Integer tileSize, Integer maxWidth, Integer maxHeight, GridOriginEnum gridOrigin, Point point, ShapeEnum shape) { super(name, visibility, open, atomAuthor, atomLink, address, xalAddressDetails, phoneNumber, snippet, snippetMaxLines, description, abstractView, timePrimitive, styleUrl, styleSelectors, region, extendedData, color, drawOrder, icon); this.rotation = rotation; this.leftFov = leftFov; this.rightFov = rightFov; this.bottomFov = bottomFov; this.topFov = topFov; this.near = near; this.tileSize = tileSize; this.maxWidth = maxWidth; this.maxHeight = maxHeight; this.gridOrigin = gridOrigin; this.point = point; this.shape = shape; } public Double getRotation() { return rotation; } public void setRotation(Double rotation) { this.rotation = rotation; } public Double getLeftFov() { return leftFov; } public void setLeftFov(Double leftFov) { this.leftFov = leftFov; } public Double getRightFov() { return rightFov; } public void setRightFov(Double rightFov) { this.rightFov = rightFov; } public Double getBottomFov() { return bottomFov; } public void setBottomFov(Double bottomFov) { this.bottomFov = bottomFov; } public Double getTopFov() { return topFov; } public void setTopFov(Double topFov) { this.topFov = topFov; } public Double getNear() { return near; } public void setNear(Double near) { this.near = near; } public Integer getTileSize() { return tileSize; } public void setTileSize(Integer tileSize) { this.tileSize = tileSize; } public Integer getMaxWidth() { return maxWidth; } public void setMaxWidth(Integer maxWidth) { this.maxWidth = maxWidth; } public Integer getMaxHeight() { return maxHeight; } public void setMaxHeight(Integer maxHeight) { this.maxHeight = maxHeight; } public GridOriginEnum getGridOrigin() { return gridOrigin; } public void setGridOrigin(GridOriginEnum gridOrigin) { this.gridOrigin = gridOrigin; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } public ShapeEnum getShape() { return shape; } public void setShape(ShapeEnum shape) { this.shape = shape; } public void write(Kml kml) throws KmlException { kml.println("""", 1); super.writeInner(kml); if(rotation != null) { kml.println("""" + rotation + """"); } if(leftFov != null || rightFov != null || bottomFov != null || topFov != null || near != null) { kml.println("""", 1); if(leftFov != null) { kml.println("""" + leftFov + """"); } if(rightFov != null) { kml.println("""" + rightFov + """"); } if(bottomFov != null) { kml.println("""" + bottomFov + """"); } if(topFov != null) { kml.println("""" + topFov + """"); } if(near != null) { kml.println("""" + near + """"); } kml.println(-1, """"); } if(tileSize != null || maxWidth != null || maxHeight != null || gridOrigin != null) { kml.println("""", 1); if(tileSize != null) { kml.println("""" + tileSize + """"); } if(maxWidth != null) { kml.println("""" + maxWidth + """"); } if(maxHeight != null) { kml.println("""" + maxHeight + """"); } if(gridOrigin != null) { kml.println("""" + gridOrigin + """"); } kml.println(-1, """"); if(point != null) { point.write(kml); } if(shape != null) { kml.println("""" + shape + """"); } } kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/Kml.java",".java","3788","154","package kmlframework.kml; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.io.PrintWriter; public class Kml { protected NetworkLinkControl networkLinkControl; protected Feature feature; protected boolean celestialData = false; protected boolean atomElementsIncluded = false; protected boolean extensionElementsIncluded = false; protected boolean generateObjectIds = true; private PrintWriter printWriter; private int indentLevel = 0; private boolean xmlIndent = false; public Kml() {} public Kml(NetworkLinkControl networkLinkControl, Feature feature) { this.networkLinkControl = networkLinkControl; this.feature = feature; } public void setXmlIndent(boolean xmlIndent) { this.xmlIndent = xmlIndent; } public boolean getXmlIndent() { return xmlIndent; } public NetworkLinkControl getNetworkLinkControl() { return networkLinkControl; } public void setNetworkLinkControl(NetworkLinkControl networkLinkControl) { this.networkLinkControl = networkLinkControl; } public Feature getFeature() { return feature; } public void setFeature(Feature feature) { this.feature = feature; } public boolean isCelestialData() { return celestialData; } public void setCelestialData(boolean celestialData) { this.celestialData = celestialData; } public boolean isAtomElementsIncluded() { return atomElementsIncluded; } public void setAtomElementsIncluded(boolean atomElementsIncluded) { this.atomElementsIncluded = atomElementsIncluded; } public boolean isExtensionElementsIncluded() { return extensionElementsIncluded; } public void setExtensionElementsIncluded(boolean extensionElementsIncluded) { this.extensionElementsIncluded = extensionElementsIncluded; } public boolean isGenerateObjectIds() { return generateObjectIds; } public void setGenerateObjectIds(boolean generateObjectIds) { this.generateObjectIds = generateObjectIds; } public void printNoIndent(String string) { printWriter.print(string); } public void print(String string) { print(string, 0); } public void println(String string) { println(string, 0); } public void print(String string, int indentChangeAfter) { printIndents(); indentLevel += indentChangeAfter; printWriter.print(string); } public void println(String string, int indentChangeAfter) { printIndents(); indentLevel += indentChangeAfter; printWriter.println(string); } public void print(int indentChangeBefore, String string) { indentLevel += indentChangeBefore; printIndents(); printWriter.print(string); } public void println(int indentChangeBefore, String string) { indentLevel += indentChangeBefore; printIndents(); printWriter.println(string); } private void printIndents() { if (xmlIndent) { for (int i = 0; i < indentLevel; i++) { printWriter.print(""\t""); } } } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (networkLinkControl != null) { networkLinkControl.write(kml); } if (feature != null) { feature.write(kml); } kml.println(-1, """"); } public void createKml(String fileName) throws KmlException, IOException { createKml(new PrintWriter(new BufferedWriter(new FileWriter(fileName)))); } public void createKml(PrintWriter printWriter) throws KmlException, IOException { this.printWriter = printWriter; println(""""); write(this); this.printWriter.close(); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ViewRefreshModeEnum.java",".java","99","6","package kmlframework.kml; public enum ViewRefreshModeEnum { never, onStop, onRequest, onRegion } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/LineStyle.java",".java","621","30","package kmlframework.kml; public class LineStyle extends ColorStyle { private Double width; public LineStyle() {} public LineStyle(String color, ColorModeEnum colorMode, Double width) { super(color, colorMode); this.width = width; } public Double getWidth() { return width; } public void setWidth(Double width) { this.width = width; } public void write(Kml kml) throws KmlException { kml.println("""", 1); super.writeInner(kml); if (width != null) { kml.println("""" + width + """"); } kml.println(-1, """"); } }","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ext/Wait.java",".java","827","39","/* * Wait.java Created Oct 12, 2010 by Andrew Butler, PSL */ package kmlframework.kml.ext; public class Wait extends TourPrimitive { private double duration; public Wait(double duration) { this.duration = duration; } public double getDuration() { return duration; } public void setDuration(double duration) { this.duration = duration; } public void write(kmlframework.kml.Kml kml) throws kmlframework.kml.KmlException { kml.println("""", 1); kml.println("""" + duration + """"); kml.println(-1, """"); } public void writeDelete(kmlframework.kml.Kml kml) throws kmlframework.kml.KmlException { kml.println(""""); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ext/SoundCue.java",".java","622","34","/* * SoundCue.java Created Oct 12, 2010 by Andrew Butler, PSL */ package kmlframework.kml.ext; public class SoundCue extends TourPrimitive { private String href; public SoundCue(String href) { this.href = href; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } @Override public void write(kmlframework.kml.Kml kml) throws kmlframework.kml.KmlException { kml.println("""", 1); kml.println("""" + href + """"); kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ext/Playlist.java",".java","857","35","/* * Playlist.java Created Oct 12, 2010 by Andrew Butler, PSL */ package kmlframework.kml.ext; public class Playlist extends kmlframework.kml.KmlObject { private final java.util.ArrayList elements; public Playlist() { elements = new java.util.ArrayList(); } public java.util.List getElements() { return elements; } public void write(kmlframework.kml.Kml kml) throws kmlframework.kml.KmlException { kml.println("""", 1); for(TourPrimitive element : elements) element.write(kml); kml.println(-1, """"); } public void writeDelete(kmlframework.kml.Kml kml) throws kmlframework.kml.KmlException { kml.println(""""); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ext/TourControl.java",".java","829","42","/* * TourControl.java Created Oct 12, 2010 by Andrew Butler, PSL */ package kmlframework.kml.ext; public class TourControl extends TourPrimitive { public static enum PlayModeEnum { PAUSE(""pause""); public final String kml; PlayModeEnum(String kml) { this.kml = kml; } } private PlayModeEnum playMode; /** Shortened form for creating a pause */ public TourControl() { this(PlayModeEnum.PAUSE); } public TourControl(PlayModeEnum playMode) { this.playMode = playMode; } @Override public void write(kmlframework.kml.Kml kml) throws kmlframework.kml.KmlException { kml.println("""", 1); kml.println("""" + playMode.kml + """"); kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ext/AnimatedUpdate.java",".java","1054","50","/* * AnimatedUpdate.java Created Oct 12, 2010 by Andrew Butler, PSL */ package kmlframework.kml.ext; public class AnimatedUpdate extends TourPrimitive { private Double duration; private kmlframework.kml.Update update; public AnimatedUpdate(kmlframework.kml.Update update) { this.update = update; if(this.update.getTargetHref() == null) this.update.setTargetHref(""""); } public Double getDuration() { return duration; } public void setDuration(Double duration) { this.duration = duration; } public kmlframework.kml.Update getUpdate() { return update; } public void setUpdate(kmlframework.kml.Update update) { this.update = update; } @Override public void write(kmlframework.kml.Kml kml) throws kmlframework.kml.KmlException { kml.println("""", 1); if(duration != null) kml.println("""" + duration + """"); update.write(kml); kml.println(-1, """"); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ext/FlyTo.java",".java","1585","80","/* * FlyTo.java Created Oct 12, 2010 by Andrew Butler, PSL */ package kmlframework.kml.ext; public class FlyTo extends TourPrimitive { public static enum FlyToMode { BOUNCE(""bounce""), SMOOTH(""smooth""); public final String kml; FlyToMode(String kml) { this.kml = kml; } } private Double duration; private FlyToMode flyToMode; private kmlframework.kml.AbstractView view; public FlyTo(kmlframework.kml.AbstractView view) { this.view = view; flyToMode = FlyToMode.BOUNCE; } public Double getDuration() { return duration; } public void setDuration(Double duration) { this.duration = duration; } public FlyToMode getFlyToMode() { return flyToMode; } public void setFlyToMode(FlyToMode flyToMode) { this.flyToMode = flyToMode; } public kmlframework.kml.AbstractView getView() { return view; } public void setView(kmlframework.kml.AbstractView view) { this.view = view; } public void write(kmlframework.kml.Kml kml) throws kmlframework.kml.KmlException { kml.println("""", 1); if(duration != null) kml.println("""" + duration + """"); if(flyToMode != null) kml.println("""" + flyToMode.kml + """"); view.write(kml); kml.println(-1, """"); } public void writeDelete(kmlframework.kml.Kml kml) throws kmlframework.kml.KmlException { kml.println(""""); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ext/Tour.java",".java","932","39","/* * Tour.java Created Oct 12, 2010 by Andrew Butler, PSL */ package kmlframework.kml.ext; import kmlframework.kml.Kml; public class Tour extends kmlframework.kml.Feature { private Playlist playlist; public Playlist getPlaylist() { return playlist; } public void setPlaylist(Playlist playlist) { this.playlist = playlist; } public void write(Kml kml) throws kmlframework.kml.KmlException { kml.println("""", 1); if(getName() != null) kml.println("""" + getName() + """"); if(getDescription() != null) kml.println("""" + getDescription() + """"); if(playlist != null) playlist.write(kml); kml.println(-1, """"); } public void writeDelete(Kml kml) throws kmlframework.kml.KmlException { kml.println(""""); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/kml/ext/TourPrimitive.java",".java","186","9","/* * TourPrimitive.java Created Oct 12, 2010 by Andrew Butler, PSL */ package kmlframework.kml.ext; public abstract class TourPrimitive extends kmlframework.kml.KmlObject { } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/atom/AtomAuthor.java",".java","1126","63","package kmlframework.atom; import kmlframework.kml.Kml; import kmlframework.kml.KmlException; public class AtomAuthor { private String name; private String uri; private String email; public AtomAuthor() {} public AtomAuthor(String name, String uri, String email) { this.name = name; this.uri = uri; this.email = email; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public AtomAuthor(String name) { this.name = name; } public void write(Kml kml) throws KmlException { kml.println("""", 1); if (name != null) { kml.println("""" + name + """"); } if (uri != null) { kml.println("""" + uri + """"); } if (email != null) { kml.println("""" + email + """"); } kml.println(-1, """"); kml.setAtomElementsIncluded(true); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/kmlframework/atom/AtomLink.java",".java","563","33","package kmlframework.atom; import kmlframework.kml.Kml; import kmlframework.kml.KmlException; public class AtomLink { private String href; public AtomLink() {} public AtomLink(String href) { this.href = href; } public String getHref() { return href; } public void setHref(String href) { this.href = href; } public void write(Kml kml) throws KmlException { if (href == null) { throw new KmlException(""href not set for atom:Link""); } kml.println(""""); kml.setAtomElementsIncluded(true); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/Item.java",".java","166","15","package structure; /** * @author Andrew Rambaut * @version $Id$ */ public interface Item { boolean isContainer(); boolean isVisible(); String getName(); } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/Style.java",".java","1585","70","package structure; import java.awt.Color; /** * @author Andrew Rambaut * @version $Id$ */ public class Style extends kmlframework.kml.Style { public Style(final Color strokeColor, final double strokeWidth) { this(strokeColor, strokeWidth, null); } public Style(final Color strokeColor, final double strokeWidth, final Color fillColor) { this.strokeColor = strokeColor; this.strokeWidth = strokeWidth; this.fillColor = fillColor; } public Color getStrokeColor() { return strokeColor; } public double getStrokeWidth() { return strokeWidth; } public Color getFillColor() { return fillColor; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; final Style style = (Style) o; if (Double.compare(style.strokeWidth, strokeWidth) != 0) return false; if (fillColor != null ? !fillColor.equals(style.fillColor) : style.fillColor != null) return false; if (strokeColor != null ? !strokeColor.equals(style.strokeColor) : style.strokeColor != null) return false; return true; } @Override public int hashCode() { int result; long temp; result = strokeColor != null ? strokeColor.hashCode() : 0; temp = strokeWidth != +0.0d ? Double.doubleToLongBits(strokeWidth) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + (fillColor != null ? fillColor.hashCode() : 0); return result; } private final Color strokeColor; private final double strokeWidth; private final Color fillColor; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/Layer.java",".java","341","20","package structure; /** * @author Andrew Rambaut * @version $Id$ */ public class Layer extends Container { public Layer(final String name, final String description) { super(name, description, true); } public Layer(final String name, final String description, final boolean visible) { super(name, description, visible); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/TimeLine.java",".java","836","45","package structure; import java.util.Calendar; import java.util.Date; /** * @author Andrew Rambaut * @version $Id$ */ public class TimeLine { public TimeLine(final double startTime, final double endTime, final int sliceCount) { this.startTime = startTime; this.endTime = endTime; this.sliceCount = sliceCount; } public double getStartTime() { return startTime; } public double getEndTime() { return endTime; } public int getSliceCount() { return sliceCount; } public boolean isInstantaneous() { return sliceCount == 0 || startTime == endTime; } public Date getDate(final double startTime) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis((long) startTime); return cal.getTime(); } private final double startTime; private final double endTime; private final int sliceCount; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/Polygon.java",".java","819","38","package structure; import java.util.List; /** * @author Andrew Rambaut * @version $Id$ */ public class Polygon extends GeoItem { public Polygon(final List vertices, final Style style) { this(null, vertices, style, -1.0, -1.0); } public Polygon(final List vertices, final Style style, final double startime) { this(null, vertices, style, startime, -1.0); } public Polygon(String name, final List vertices, final Style style, final double startime, final double duration) { super(name, startime, duration); this.vertices = vertices; this.style = style; } public Style getPolyStyle() { return style; } public List getPolyCoordinates() { return vertices; } private final List vertices; private final Style style; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/Group.java",".java","339","18","package structure; /** * @author Andrew Rambaut * @version $Id$ */ public class Group extends Container { public Group(final String name, final String description) { super(name, description, true); } public Group(final String name, final String description, final boolean visible) { super(name, description, visible); } } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/Container.java",".java","950","53","package structure; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * @author Andrew Rambaut * @version $Id$ */ public abstract class Container implements Item { protected Container(final String name, final String description, final boolean visible) { this.name = name; this.description = description; isVisible = visible; } public boolean isContainer() { return true; } public boolean isVisible() { return isVisible; } public String getName() { return name; } public String getDescription() { return description; } public void addItem(Item item) { items.add(item); } public void addItems(Collection items) { items.addAll(items); } public List getItems() { return new ArrayList(items); } private final List items = new ArrayList(); private final String name; private final String description; private final boolean isVisible; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/Place.java",".java","564","28","package structure; /** * @author Andrew Rambaut * @version $Id$ */ public class Place extends GeoItem { public Place(final String name, final String description, final Coordinates coordinates, final double startTime, final double duration) { super(name, startTime, duration); this.description = description; this.coordinates = coordinates; } public String getDescription() { return description; } public Coordinates getCoordinates() { return coordinates; } private final String description; private final Coordinates coordinates; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/Line.java",".java","1718","67","package structure; /** * @author Andrew Rambaut * @version $Id$ */ public class Line extends GeoItem { public Line(final Coordinates startCoordinates, final Style startStyle, final Coordinates endCoordinates, final Style endStyle) { this(null, startCoordinates, -1.0, startStyle, endCoordinates, -1.0, endStyle, 0.0, -1.0); } public Line(final Coordinates startCoordinates, final double startTime, final Style startStyle, final Coordinates endCoordinates, final Style endStyle, final double endTime) { this(null, startCoordinates, startTime, startStyle, endCoordinates, endTime, endStyle, 0.0, -1.0); } public Line(final String name, final Coordinates startCoordinates, final double startTime, final Style startStyle, final Coordinates endCoordinates, final double endTime, final Style endStyle, final double maxAltitude, final double duration) { super(name, startTime, duration); this.startCoordinates = startCoordinates; this.startStyle = startStyle; this.endCoordinates = endCoordinates; this.endStyle = endStyle; this.endTime = endTime; this.maxAltitude = maxAltitude; } public Coordinates getStartLocation() { return startCoordinates; } public Coordinates getEndLocation() { return endCoordinates; } public double getEndTime() { return endTime; } public Style getStartStyle() { return startStyle; } public Style getEndStyle() { return endStyle; } public double getMaxAltitude() { return maxAltitude; } private final Coordinates startCoordinates; private final Style startStyle; private final Coordinates endCoordinates; private final Style endStyle; private final double endTime; private final double maxAltitude; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/GeoItem.java",".java","645","41","package structure; /** * @author Andrew Rambaut * @version $Id$ */ public abstract class GeoItem implements Item { protected GeoItem(final String name, final double startTime, final double duration) { this.name = name; this.startTime = startTime; this.duration = duration; } public String getName() { return name; } public double getStartTime() { return startTime; } public double getDuration() { return duration; } public boolean isContainer() { return false; } public boolean isVisible() { return true; } private final String name; private final double startTime; private final double duration; } ","Java" "Bio foundation model","phylogeography/SPREADv1","src/structure/Coordinates.java",".java","701","38","package structure; /** * @author Andrew Rambaut * @version $Id$ */ public class Coordinates { public Coordinates(final double longitude, final double latitude) { this.longitude = longitude; this.latitude = latitude; this.altitude = 0.0; } public Coordinates(final double longitude, final double latitude, final double altitude) { this.longitude = longitude; this.latitude = latitude; this.altitude = altitude; } public double getLongitude() { return longitude; } public double getLatitude() { return latitude; } public double getAltitude() { return altitude; } private final double longitude; private final double latitude; private final double altitude; } ","Java"