text:
import org.apache.hadoop.hdfs.*;
import junit.framework.TestCase;
import java.io.*;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.fs.permission.*;
import java.net.*;

/**
 * This class tests that the Fuse module for DFS can mount properly
 * and does a few simple commands:
 * mkdir
 * rmdir
 * ls
 * cat
 *
 * cp and touch are purposely not tested because they won't work with the current module

 *
 */
public class TestFuseDFS extends TestCase {

  /**
   * mount the fuse file system using assumed fuse module library installed in /usr/local/lib or somewhere else on your
   * pre-existing LD_LIBRARY_PATH
   *
   */

  static Process fuse_process;
  static String fuse_cmd;
  static private void mount(String mountpoint, URI dfs) throws IOException, InterruptedException  {

    String cp = System.getProperty("java.class.path");
    Runtime r = Runtime.getRuntime();
    fuse_cmd = System.getProperty("build.test") + "/../fuse_dfs";
    String libhdfs = System.getProperty("build.test") + "/../../../libhdfs/";
    String arch = System.getProperty("os.arch");
    String jvm = System.getProperty("java.home") + "/lib/" + arch + "/server";
    String lp = System.getProperty("LD_LIBRARY_PATH") + ":" + "/usr/local/lib:" + libhdfs + ":" + jvm;
    System.err.println("LD_LIBRARY_PATH=" + lp);
    String cmd[] =  {  fuse_cmd, "dfs://" + dfs.getHost() + ":" + String.valueOf(dfs.getPort()),
                       mountpoint, "-obig_writes", "-odebug", "-oentry_timeout=0.1",  "-oattribute_timeout=0.1", "-ousetrash", "rw", "-oinitchecks",
                       "-ordbuffer=32768"};
    final String [] envp = {
      "CLASSPATH="+  cp,
      "LD_LIBRARY_PATH=" + lp,
      "PATH=" + "/usr/bin:/bin"

    };

    // ensure the mount point is not currently mounted
    Process p = r.exec("fusermount -u " + mountpoint);
    p.waitFor();

    // clean up the mount point
    p = r.exec("rm -rf " + mountpoint);
    assertTrue(p.waitFor() == 0);

    // make the mount point if needed
    p = r.exec("mkdir -p " + mountpoint);
    assertTrue(p.waitFor() == 0);

    // mount fuse to the mount point
    fuse_process = r.exec(cmd, envp);

    // give DFS a chance to come up
    try { Thread.sleep(3000); } catch(Exception e) { }
  }

  /**
   * unmounts fuse for before shutting down.
   */
  static private void umount(String mpoint) throws IOException, InterruptedException {
    Runtime r= Runtime.getRuntime();
    Process p = r.exec("fusermount -u " + mpoint);
    p.waitFor();
  }

  /**
   * Set things up - create mini dfs cluster and mount the fuse filesystem.
   */
  public TestFuseDFS() throws IOException,InterruptedException  {
  }

  static private MiniDFSCluster cluster;
  static private DistributedFileSystem fileSys;
  final static private String mpoint;

  static {
    mpoint = System.getProperty("build.test") + "/mnt";
    System.runFinalizersOnExit(true);
    startStuff();
  }

  static public void startStuff() {
    try {
      Configuration conf = new HdfsConfiguration();
      conf.setBoolean(DFSConfigKeys.DFS_PERMISSIONS_ENABLED_KEY,false);
      cluster = new MiniDFSCluster(conf, 1, true, null);
      fileSys = (DistributedFileSystem)cluster.getFileSystem();
      assertTrue(fileSys.getFileStatus(new Path("/")).isDir());
      mount(mpoint, fileSys.getUri());
    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  public void setUp() {
  }

  /**
   * use shell to create a dir and then use filesys to see it exists.
   */
  public void testMkdir() throws IOException,InterruptedException, Exception  {
    try {
      // First create a new directory with mkdirs
      Path path = new Path("/foo");
      Runtime r = Runtime.getRuntime();
      String cmd = "mkdir -p " + mpoint + path.toString();
      Process p = r.exec(cmd);
      assertTrue(p.waitFor() == 0);

      // check it is there
      assertTrue(fileSys.getFileStatus(path).isDir());

      // check again through the shell
      String lsCmd = "ls " + mpoint + path.toString();
      p = r.exec(lsCmd);
      assertTrue(p.waitFor() == 0);
    } catch(Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

  /**
   * use shell to create a dir and then use filesys to see it exists.
   */
  public void testWrites() throws IOException,InterruptedException  {
    try {

      // write a hello file
      File file = new File(mpoint, "hello.txt");
      FileOutputStream f = new FileOutputStream(file);
      String s = "hello ";
      f.write(s.getBytes());
      s = "world";
      f.write(s.getBytes());
      f.flush();
      f.close();

      try {
        Thread.sleep(1000);
      } catch(Exception e) {
      }

      // check the file exists.
      Path myPath = new Path("/hello.txt");
      assertTrue(fileSys.exists(myPath));

      // check the data is ok
      FileInputStream fi = new FileInputStream(new File(mpoint, "hello.txt"));
      byte b[] = new byte[12];
      int length = fi.read(b,0,12);
      assertTrue(length > 0);
      String s2 = new String( b, 0, length);
      assertEquals("hello world", s2);
    } catch(Exception e) {
      e.printStackTrace();
    } finally {
    }
  }

  /**
   * Test ls for dir already created in testMkdDir also tests bad ls
   */
  public void testLs() throws IOException,InterruptedException  {
    try {
      // First create a new directory with mkdirs
      Runtime r = Runtime.getRuntime();

      // mkdir
      Process p = r.exec("mkdir -p " + mpoint + "/test/mkdirs");
      assertTrue(p.waitFor() == 0);

      // ls
      p = r.exec("ls " + mpoint + "/test/mkdirs");
      assertTrue(p.waitFor() == 0);

      // ls non-existant directory
      p = r.exec("ls " + mpoint + "/test/mkdirsNotThere");
      int res = p.waitFor();
      assertFalse(res == 0);
    } catch(Exception e) {
      e.printStackTrace();
    }

  }

  /**
   * Remove a dir using the shell and use filesys to see it no longer exists.
   */
  public void testRmdir() throws IOException,InterruptedException  {
    try {
      // First create a new directory with mkdirs

      Runtime r = Runtime.getRuntime();
      Process p = r.exec("mkdir -p " + mpoint + "/test/rmdir");
      assertTrue(p.waitFor() == 0);

      Path myPath = new Path("/test/rmdir");
      assertTrue(fileSys.exists(myPath));

      // remove it
      p = r.exec("rmdir " + mpoint + "/test/rmdir");
      assertTrue(p.waitFor() == 0);

      // check it is not there
      assertFalse(fileSys.exists(myPath));

      Path trashPath = new Path("/user/root/.Trash/Current/test/rmdir");
      assertTrue(fileSys.exists(trashPath));

      // make it again to test trashing same thing twice
      p = r.exec("mkdir -p " + mpoint + "/test/rmdir");
      assertTrue(p.waitFor() == 0);

      assertTrue(fileSys.exists(myPath));

      // remove it
      p = r.exec("rmdir " + mpoint + "/test/rmdir");
      assertTrue(p.waitFor() == 0);

      // check it is not there
      assertFalse(fileSys.exists(myPath));

      trashPath = new Path("/user/root/.Trash/Current/test/rmdir.1");
      assertTrue(fileSys.exists(trashPath));

    } catch(Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * use shell to create a dir and then use filesys to see it exists.
   */
  public void testDF() throws IOException,InterruptedException, Exception  {
    try {
      // First create a new directory with mkdirs
      Path path = new Path("/foo");
      Runtime r = Runtime.getRuntime();
      String cmd = "mkdir -p " + mpoint + path.toString();
      Process p = r.exec(cmd);
      assertTrue(p.waitFor() == 0);
      File f = new File(mpoint + "/foo");

      DistributedFileSystem.DiskStatus d = fileSys.getDiskStatus();

      long fileUsedBlocks =  (f.getTotalSpace() - f.getFreeSpace())/(64 * 1024 * 1024);
      long dfsUsedBlocks = (long)Math.ceil((double)d.getDfsUsed()/(64 * 1024 * 1024));

      assertTrue(fileUsedBlocks == dfsUsedBlocks);
      assertTrue(d.getCapacity() == f.getTotalSpace());

    } catch(Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

  /**
   * use shell to create a dir and then use filesys to see it exists.
   */
  public void testChown() throws IOException,InterruptedException, Exception  {
    try {
      // First create a new directory with mkdirs
      Path path = new Path("/foo");
      Runtime r = Runtime.getRuntime();
      String cmd = "mkdir -p " + mpoint + path.toString();
      Process p = r.exec(cmd);
      assertTrue(p.waitFor() == 0);

      // check it is there
      assertTrue(fileSys.getFileStatus(path).isDir());

      FileStatus foo = fileSys.getFileStatus(path);
      System.err.println("DEBUG:owner=" + foo.getOwner());

      cmd = "chown nobody " + mpoint + path.toString();
      p = r.exec(cmd);
      assertTrue(p.waitFor() == 0);

      //      cmd = "chgrp nobody " + mpoint + path.toString();
      //      p = r.exec(cmd);
      //      assertTrue(p.waitFor() == 0);

      foo = fileSys.getFileStatus(path);

      System.err.println("DEBUG:owner=" + foo.getOwner());

      assertTrue(foo.getOwner().equals("nobody"));
      assertTrue(foo.getGroup().equals("nobody"));

    } catch(Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

  /**
   * use shell to create a dir and then use filesys to see it exists.
   */
  public void testChmod() throws IOException,InterruptedException, Exception  {
    try {
      // First create a new directory with mkdirs
      Path path = new Path("/foo");
      Runtime r = Runtime.getRuntime();
      String cmd = "mkdir -p " + mpoint + path.toString();
      Process p = r.exec(cmd);
      assertTrue(p.waitFor() == 0);

      // check it is there
      assertTrue(fileSys.getFileStatus(path).isDir());

      cmd = "chmod 777 " + mpoint + path.toString();
      p = r.exec(cmd);
      assertTrue(p.waitFor() == 0);

      FileStatus foo = fileSys.getFileStatus(path);
      FsPermission perm = foo.getPermission();
      assertTrue(perm.toShort() == 0777);

    } catch(Exception e) {
      e.printStackTrace();
      throw e;
    }
  }

  /**
   * use shell to create a dir and then use filesys to see it exists.
   */
  public void testUtimes() throws IOException,InterruptedException, Exception  {
    try {
      // First create a new directory with mkdirs
      Path path = new Path("/utimetest");
      Runtime r = Runtime.getRuntime();
      String cmd = "touch " + mpoint + path.toString();
      Process p = r.exec(cmd);
      assertTrue(p.waitFor() == 0);

      // check it is there
      assertTrue(fileSys.exists(path));

      FileStatus foo = fileSys.getFileStatus(path);
      long oldTime = foo.getModificationTime();
      try { Thread.sleep(1000); } catch(Exception e) {}

      cmd = "touch " + mpoint + path.toString();
      p = r.exec(cmd);
      assertTrue(p.waitFor() == 0);

      try { Thread.sleep(1000); } catch(Exception e) {}
      foo = fileSys.getFileStatus(path);
      long newTime = foo.getModificationTime();

      assertTrue(newTime > oldTime);

    } catch(Exception e) {
      e.printStackTrace();
      throw e;
    } finally {
    }
  }

  /**
   *
   * Test dfs_read on a file size that will trigger multiple internal reads.
   * First, just check raw size reading is ok and then check with smaller reads
   * including checking the validity of the data read.
   *
   */
  public void testReads() throws IOException,InterruptedException  {
    try {
      // First create a new directory with mkdirs
      Runtime r = Runtime.getRuntime();
      Process p;

      // create the file
      Path myPath = new Path("/test/hello.reads");
      FSDataOutputStream s = fileSys.create(myPath);
      String hello = "hello world!";
      int written = 0;
      int mycount = 0;
      while(written < 1024 * 9) {
        s.writeUTF(hello);
        s.writeInt(mycount++);
        written += hello.length() + 4;
      }
      s.close();

      // check it exists
      assertTrue(fileSys.exists(myPath));
      FileStatus foo = fileSys.getFileStatus(myPath);
      assertTrue(foo.getLen() >= 9 * 1024);

      {
        // cat the file
        DataInputStream is = new DataInputStream(new FileInputStream(mpoint + "/test/hello.reads"));
        byte buf [] = new byte[4096];
        // test reading 0 length
        assertTrue(is.read(buf, 0, 0) == 0);

        // test real reads
        assertTrue(is.read(buf, 0, 1024) == 1024);
        assertTrue(is.read(buf, 0, 4096) == 4096);
        assertTrue(is.read(buf, 0, 4096) == 4096);
        is.close();
      }

      {
        DataInputStream is = new DataInputStream(new FileInputStream(mpoint + "/test/hello.reads"));
        int read = 0;
        int counter = 0;
        try {
          while(true) {
            String s2 = DataInputStream.readUTF(is);
            int s3 = is.readInt();
            assertTrue(s2.equals(hello));
            assertTrue(s3 == counter++);
            read += hello.length() + 4;
          }
        } catch(EOFException e) {
          assertTrue(read >= 9 * 1024);
        }
      }

      // check reading an empty file for EOF
      {
        // create the file
        myPath = new Path("/test/hello.reads2");
        s = fileSys.create(myPath);
        s.close();

        FSDataInputStream fs = fileSys.open(myPath);
        assertEquals(-1,  fs.read());

        FileInputStream f = new FileInputStream(mpoint + "/test/hello.reads2");
        assertEquals(-1, f.read());
      }

    } catch(Exception e) {
      e.printStackTrace();
    } finally {
    }
  }

  /**
   * Use filesys to create the hello world! file and then cat it and see its contents are correct.
   */
  public void testCat() throws IOException,InterruptedException  {
    try {
      // First create a new directory with mkdirs
      Runtime r = Runtime.getRuntime();
      Process p = r.exec("rm -rf " + mpoint + "/test/hello");
      assertTrue(p.waitFor() == 0);

      // create the file
      Path myPath = new Path("/test/hello");
      FSDataOutputStream s = fileSys.create(myPath);
      String hello = "hello world!";
      s.writeUTF(hello);
      s.writeInt(1033);
      s.close();

      // check it exists
      assertTrue(fileSys.exists(myPath));

      // cat the file
      DataInputStream is = new DataInputStream(new FileInputStream(mpoint + "/test/hello"));
      String s2 = DataInputStream.readUTF(is);
      int s3 = is.readInt();
      assertTrue(s2.equals(hello));
      assertTrue(s3 == 1033);

    } catch(Exception e) {
      e.printStackTrace();
    } finally {
    }
  }

  /**
   * Use filesys to create the hello world! file and then cat it and see its contents are correct.
   */
  public void testAppends() throws IOException,InterruptedException  {
    try {
      // First create a new directory with mkdirs
      Runtime r = Runtime.getRuntime();

      {
        FileOutputStream os = new FileOutputStream(mpoint + "/appends");
        String hello = "hello";
        os.write(hello.getBytes());
        os.flush();
        os.close();
      }

      // check it exists
      Path myPath = new Path("/appends");
      assertTrue(fileSys.exists(myPath));

      try {
        Thread.sleep(1000);
      } catch(Exception e) {
      }

      FileStatus foo = fileSys.getFileStatus(myPath);

      File f = new File(mpoint + "/appends");
      assertTrue(f.length() > 0);

      {
        FileOutputStream os = new FileOutputStream(mpoint + "/appends", true);
        String hello = " world!";
        os.write(hello.getBytes());
        os.flush();
        os.close();
      }

      // cat the file
      FileInputStream is = new FileInputStream(mpoint + "/appends");
      byte b[] = new byte[1024];
      int len = is.read(b);
      assertTrue(len > 0);
      String s2 = new String(b,0,len);
      assertTrue(s2.equals("hello world!"));

    } catch(Exception e) {
      e.printStackTrace();
    } finally {
    }
  }

  public void testDone() throws IOException {
      close();
  }

  /**
   * Unmount and close
   */
  protected void tearDown() throws Exception {
  }

  /**
   * Unmount and close
   */
  protected void finalize() throws Throwable {
    close();
  }

  public void close() {
    try {
      int length;

      // print out the fuse debug output
      {
      do {
      InputStream i = fuse_process.getInputStream();
      byte b[] = new byte[i.available()];
      length = i.read(b);
      System.err.println("read x bytes: " + length);
      System.err.write(b,0,b.length);
      } while(length > 0) ;
      }

      do {
      InputStream i = fuse_process.getErrorStream();
      byte b[] = new byte[i.available()];
      length = i.read(b);
      System.err.println("read x bytes: " + length);
      System.err.write(b,0,b.length);
      } while(length > 0) ;

      umount(mpoint);

      fuse_process.destroy();
      fuse_process = null;
        if(fileSys != null) {
        fileSys.close();
        fileSys = null;
      }
      if(cluster != null) {
        cluster.shutdown();
        cluster = null;
      }
    } catch(Exception e) { }
  }
};


text:
namespace content {
class BrowserContext;
}

class Profile;

namespace web_app {

// A container class for temporary migrations, fix ups and clean ups dealing
// historical code that's left its mark on the user's database/prefs.
// Everything in here should have a removal date.
class WebAppAdjustments : public KeyedService {
 public:
  static WebAppAdjustments* Get(Profile* profile);

  explicit WebAppAdjustments(Profile* profile);
  ~WebAppAdjustments() override;

  PreinstalledWebAppDuplicationFixer* preinstalled_web_app_duplication_fixer() {
    return preinstalled_web_app_duplication_fixer_.get();
  }

 private:
  // TODO(crbug.com/1262906): This was added in M97, remove in M107.
  std::unique_ptr<LinkCapturingPrefMigration> link_capturing_pref_migration_;

  // TODO(crbug.com/1290716): This was added in M100, remove in M120.
  std::unique_ptr<PreinstalledWebAppDuplicationFixer>
      preinstalled_web_app_duplication_fixer_;
};

class WebAppAdjustmentsFactory : public BrowserContextKeyedServiceFactory {
 public:
  WebAppAdjustmentsFactory();
  ~WebAppAdjustmentsFactory() override;

  static WebAppAdjustmentsFactory* GetInstance();

 private:
  friend class WebAppAdjustments;

  // BrowserContextKeyedServiceFactory:
  KeyedService* BuildServiceInstanceFor(
      content::BrowserContext* context) const override;
  bool ServiceIsCreatedWithBrowserContext() const override;
  content::BrowserContext* GetBrowserContextToUse(
      content::BrowserContext* context) const override;
};

}  // namespace web_app

#endif  // CHROME_BROWSER_WEB_APPLICATIONS_ADJUSTMENTS_WEB_APP_ADJUSTMENTS_H_

redpajama_set_name: RedPajamaGithub


text:
package confer

import (
	"fmt"
	"path"
	"path/filepath"
	"reflect"
	"strings"
	"time"

	"github.com/kr/pretty"
	"github.com/spf13/cast"
	jww "github.com/spf13/jwalterweatherman"
	"github.com/spf13/pflag"

	"github.com/jacobstr/confer/reader"
	. "github.com/jacobstr/confer/source"

	errors "github.com/jacobstr/confer/errors"
	"github.com/jacobstr/confer/maps"
)

// Manages key/value access and aliasing across multiple configuration sources.
type Config struct {
	pflags     *PFlagSource
	env        *EnvSource
	attributes *ConfigSource

	// The root path for configuration files.
	rootPath string
}

func NewConfig() *Config {
	manager := &Config{}
	manager.pflags = NewPFlagSource()
	manager.attributes = NewConfigSource()
	manager.env = NewEnvSource()
	manager.rootPath = ""

	return manager
}

// Finds a value at a provided key, returning nil if the key does not exist.
// The order of precedence for configuration data is:
// 1. Program arguments.
// 2. Environment variables.
// 3. Config file data, overrides, and defaults.
func (self *Config) Find(key string) interface{} {
	var val interface{}
	var exists bool

	// PFlag Override first
	val, exists = self.pflags.Get(key)
	if exists {
		jww.TRACE.Println(key, "found in override (via pflag):", val)
		return val
	}

	// Periods are not supported. Allow the usage of underscores to specify nested
	// configuration options.
	val, exists = self.env.Get(key)
	if exists {
		jww.TRACE.Println(key, "Found in environment with value:", val)
		return val
	}

	// Attributes entail pretty much everything else.
	val, exists = self.attributes.Get(key)
	if exists {
		jww.TRACE.Println(key, "Found in config:", val)
		return val
	}

	return nil
}

func (manager *Config) GetString(key string) string {
	return cast.ToString(manager.Get(key))
}

func (manager *Config) GetBool(key string) bool {
	return cast.ToBool(manager.Get(key))
}

func (manager *Config) GetInt(key string) int {
	return cast.ToInt(manager.Get(key))
}

func (manager *Config) GetFloat64(key string) float64 {
	return cast.ToFloat64(manager.Get(key))
}

func (manager *Config) GetTime(key string) time.Time {
	return cast.ToTime(manager.Get(key))
}

func (manager *Config) GetStringSlice(key string) []string {
	return cast.ToStringSlice(manager.Get(key))
}

func (manager *Config) GetStringMap(key string) map[string]interface{} {
	return cast.ToStringMap(manager.Get(key))
}

func (manager *Config) GetStringMapString(key string) map[string]string {
	return cast.ToStringMapString(manager.Get(key))
}

// Binds a configuration key to a command line flag:
//	 pflag.Int("port", 8080, "The best alternative port")
//	 confer.BindPFlag("port", pflag.Lookup("port"))
func (manager *Config) BindPFlag(key string, flag *pflag.Flag) (err error) {
	if flag == nil {
		return fmt.Errorf("flag for %q is nil", key)
	}

	manager.pflags.Set(key, flag)

	switch flag.Value.Type() {
	case "int", "int8", "int16", "int32", "int64":
		manager.SetDefault(key, cast.ToInt(flag.Value.String()))
	case "bool":
		manager.SetDefault(key, cast.ToBool(flag.Value.String()))
	default:
		manager.SetDefault(key, flag.Value.String())
	}
	return nil
}

// Binds a confer key to a ENV variable. ENV variables are case sensitive If only
func (manager *Config) BindEnv(input ...string) (err error) {
	return manager.env.Bind(input...)
}

// Get returns an interface..
// Must be typecast or used by something that will typecast
func (manager *Config) Get(key string) interface{} {
	jww.TRACE.Println("Looking for", key)

	v := manager.Find(key)

	if v == nil {
		return nil
	}

	jww.TRACE.Println("Found value", v)
	switch v.(type) {
	case bool:
		return cast.ToBool(v)
	case string:
		return cast.ToString(v)
	case int64, int32, int16, int8, int:
		return cast.ToInt(v)
	case float64, float32:
		return cast.ToFloat64(v)
	case time.Time:
		return cast.ToTime(v)
	case []string:
		return v
	}
	return v
}

// Returns true if the config key exists and is non-nil.
func (manager *Config) IsSet(key string) bool {
	t := manager.Get(key)
	return t != nil
}

// Have confer check ENV variables for all
// keys set in config, default & flags
func (manager *Config) AutomaticEnv() {
	for _, x := range manager.AllKeys() {
		manager.BindEnv(x)
	}
}

// Returns true if the key provided exists in our configuration.
func (manager *Config) InConfig(key string) bool {
	_, exists := manager.attributes.Get(key)
	return exists
}

// Set the default value for this key.
// Default only used when no value is provided by the user via flag, config or ENV.
func (manager *Config) SetDefault(key string, value interface{}) {
	if !manager.IsSet(key) {
		manager.attributes.Set(key, value)
	}
}

// Explicitly sets a value. Will not override command line arguments or
// environment variables, as those sources have higher precedence.
func (manager *Config) Set(key string, value interface{}) {
	manager.attributes.Set(key, value)
}

// Sets an optional root path. This frees you from having to specify a
// redundant prefix when calling ReadPaths() later.
func (manager *Config) SetRootPath(path string) {
	manager.rootPath = path
}

// Loads and sequentially + recursively merges the provided config arguments. Returns
// an error if any of the files fail to load, though this may be expecte
// in the case of search paths.
func (manager *Config) ReadPaths(paths ...string) error {
	var err error
	var loaded interface{}

	merged_config := manager.attributes.ToStringMap()
	errs := []error{}

	for _, base_path := range paths {
		var final_path string

		if !filepath.IsAbs(base_path) {
			final_path = path.Join(manager.rootPath, base_path)
		} else {
			final_path = base_path
		}

		loaded, err = reader.ReadFile(final_path)

		if err != nil {
			errs = append(errs, err)
			continue
		}

		// In-place recursive coercion to stringmap.
		coerced := cast.ToStringMap(loaded)
		maps.ToStringMapRecursive(coerced)

		if merged_config == nil {
			merged_config = coerced
		} else {
			merged_config = maps.Merge(
				merged_config,
				coerced,
			)
		}

		manager.attributes.FromStringMap(merged_config)
	}

	if len(errs) > 0 {
		return &errors.LoadError{Errors: errs}
	} else {
		return nil
	}
}

// Merges data into the our attributes configuration tier from a struct.
func (manager *Config) MergeAttributes(val interface{}) error {
	merged_config := maps.Merge(
		manager.attributes.ToStringMap(),
		cast.ToStringMap(val),
	)

	manager.attributes.FromStringMap(merged_config)
	return nil
}

// Returns all currently set keys, pruning ancestors and only
// showing the leaves.
func (manager *Config) AllKeys() []string {
	keys := manager.attributes.AllKeys()
	keys = append(keys, manager.env.AllKeys()...)
	keys = append(keys, manager.attributes.AllKeys()...)

	leaves := map[string]struct{}{}
	for _, key := range keys {

		// Filter out leaves. This is really ineffecient.
		val := manager.Get(key)
		if val == nil {
			leaves[key] = struct{}{}
		} else if reflect.TypeOf(val).Kind() != reflect.Map {
			leaves[key] = struct{}{}
		}
	}

	unique_keys := []string{}
	for x, _ := range leaves {
		// LowerCase the key for backwards-compatibility.
		unique_keys = append(unique_keys, strings.ToLower(x))
	}

	return unique_keys
}

func (manager *Config) AllSettings() map[string]interface{} {
	m := map[string]interface{}{}
	for _, x := range manager.AllKeys() {
		m[x] = manager.Get(x)
	}

	return m
}

func (manager *Config) Debug() {
	fmt.Println("Flags:")
	pretty.Println(manager.pflags)
	fmt.Println("Env:")
	pretty.Println(manager.env)
	fmt.Println("Config file attributes:")
	pretty.Println(manager.attributes)
}


text:
SpriteSheet::SpriteSheet(sf::Sprite sprite, int tileSize){
	m_tileSize = tileSize;
	m_sprite = sprite;
}

sf::Sprite SpriteSheet::getTile(int row, int col){
	m_sprite.setTextureRect(sf::IntRect(row*m_tileSize, col*m_tileSize, (row+1)*m_tileSize, (col+1)*m_tileSize));

	return m_sprite;
}


text:
package ca.mb.armchair.IDE;

/*
 * IDE.java
 *
 * Created on October 13, 2002, 8:26 PM
 */

/**
 *
 *
 * @author  Dave Voorhis
 */
public class IDE extends javax.swing.JFrame implements IDEInterface {

    // Default IDE display dimensions.
    public final static int InitialWidth = 640;
    public final static int InitialHeight = 480;

    // Fonts
    public final static java.awt.Font MenuFont = new java.awt.Font("Dialog", 0, 10);

    // Root windows
    private Editor theEditor;
    private Explorer theExplorer;
    private Properties theProperties;
    private Log theLog;

    // IDE Logger
    private LogSession IDELogger;

    // Widgets that change state.
    private javax.swing.JMenuItem jMenuItemSave;
    private javax.swing.JMenuItem jMenuItemSaveAs;
    private javax.swing.JMenuItem jMenuItemSaveAll;
    private javax.swing.JMenuItem jMenuItemPrint;
    private javax.swing.JMenuItem jMenuItemUndo;
    private javax.swing.JMenuItem jMenuItemRedo;
    private javax.swing.JMenuItem jMenuItemCut;
    private javax.swing.JMenuItem jMenuItemCopy;
    private javax.swing.JMenuItem jMenuItemPaste;
    private javax.swing.JMenuItem jMenuItemDelete;
    private javax.swing.JMenuItem jMenuItemFind;
    private javax.swing.JMenuItem jMenuItemReplace;
    private javax.swing.JMenuItem jMenuItemUnDock;
    private javax.swing.JMenu jMenuDock;
    private javax.swing.JMenuItem jMenuItemMount;
    private javax.swing.JMenuItem jMenuItemUnMount;
    private javax.swing.JMenuItem jMenuItemImport;

    // Split panes.
    private IDESplitPane jSplitPaneMain;
    private IDESplitPane jSplitPaneLeft;
    private IDESplitPane jSplitPaneRight;

    /** Get the IDE. */
    public static IDE getIDE() {
        return theIDE;
    }

    /** Get the default menu item font. */
    public static java.awt.Font getMenuFont() {
        return MenuFont;
    }

    /** Creates new IDE window. */
    private IDE() {
        theLog = new Log();
        IDELogger = new LogSession(theLog, "IDE");

        // Tell the JVPL logger to use this IDE.
        ca.mb.armchair.JVPL.Log.setIDE(this);

        LogPrintln("Creating new IDE...");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                doExit();
            }
        });

        LogPrintln("Creating display panels.");

        jSplitPaneMain = new IDESplitPane();
        jSplitPaneMain.setOneTouchExpandable(true);
        jSplitPaneMain.setContinuousLayout(true);
        jSplitPaneMain.setResizeWeight(0);

        getContentPane().setLayout(new java.awt.BorderLayout());

        jSplitPaneLeft = new IDESplitPane();
        jSplitPaneLeft.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPaneLeft.setOneTouchExpandable(true);
        jSplitPaneLeft.setContinuousLayout(true);
        jSplitPaneLeft.setResizeWeight(0);

        jSplitPaneMain.setLeftComponent(jSplitPaneLeft);

        jSplitPaneRight = new IDESplitPane();
        jSplitPaneRight.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPaneRight.setOneTouchExpandable(true);
        jSplitPaneRight.setContinuousLayout(true);
        jSplitPaneRight.setResizeWeight(1);

        jSplitPaneMain.setRightComponent(jSplitPaneRight);

        getContentPane().add(jSplitPaneMain, java.awt.BorderLayout.CENTER);

        LogPrintln("Setting IDE display bounds.");

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((int)(screenSize.getWidth() - InitialWidth) / 2, (int)(screenSize.getHeight() - InitialHeight) / 2,
                                    InitialWidth, InitialHeight);
    }

    private javax.swing.JMenuBar jMenuBarMain;

    /** Launch IDE. */
    private void launch() {
        Splash.showSplash();
        Splash.resetProgressBar(15);
        SplashPrintln("IDE Launch begins...");
        SplashPrintln("Creating menu bar.");
        jMenuBarMain = new javax.swing.JMenuBar();
        setJMenuBar(jMenuBarMain);
        SplashPrintln("Building 'File' menu.");
        buildMenuFile();
        SplashPrintln("Building 'Edit' menu.");
        buildMenuEdit();
        SplashPrintln("Setting initial IDE state.");
        setState();
        SplashPrintln("Initializing Explorer.");
        theExplorer = new Explorer();
        SplashPrintln("Initializing Editor.");
        theEditor = new Editor();
        SplashPrintln("Initializing Properties.");
        theProperties = new Properties();
        SplashPrintln("Configuring panel layout.");
        jSplitPaneRight.setTopComponent(theEditor);
        jSplitPaneRight.setBottomComponent(theProperties);
        jSplitPaneLeft.setTopComponent(theExplorer);
        jSplitPaneLeft.setBottomComponent(theLog);
        SplashPrintln("Building 'View' menu.");
        buildMenuView();
        SplashPrintln("Building 'Tools' menu.");
        buildMenuTools();
        SplashPrintln("Building 'Window' menu.");
        buildMenuWindow();
        SplashPrintln("Building 'Help' menu.");
        buildMenuHelp();
        SplashPrintln("Displaying IDE window.");
        show();
        jSplitPaneMain.setDividerLocation(0.5);
        jSplitPaneLeft.setDividerLocation(0.75);
        jSplitPaneRight.setDividerLocation(0.75);
        SplashPrintln("Ready.");
        Splash.hideSplash();
    }

    /** Get Explorer */
    public Explorer getExplorer() {
        return theExplorer;
    }

    /** Get Log */
    public Log getLog() {
        return theLog;
    }

    /** Get Editor */
    public Editor getEditor() {
        return theEditor;
    }

    /** Get Properties */
    public Properties getProperties() {
        return theProperties;
    }

    /** Convenience function to print to Splash log, for startup use. */
    private void SplashPrintln(String s) {
        Splash.println(s);
        Splash.incrementProgressBar();
    }

    /** Convenience function to print to IDE log. */
    public void LogPrintln(String s) {
        IDELogger.println(s);
    }

    /** Send a string to the Log.  */
    public void LogPrint(String s) {
        IDELogger.print(s);
    }

    /** Log a stacktrace.  */
    public void printStackTrace(java.lang.StackTraceElement[] elements) {
        for (int i=0; i<elements.length; i++)
            LogPrintln("\t" + ((i==0) ? "at" : "in") + " " + elements[i].toString());
    }

    /** Get desktop area width */
    public int getDesktopWidth() {
        return getWidth() - (getInsets().right + getInsets().left);
    }

    /** Get desktop area height */
    public int getDesktopHeight() {
        return getHeight() - (getInsets().top + getInsets().bottom);
    }

    private Object ClipBoard = null;

    // Set IDE state on basis of focusPanel
    private void setState() {
        jMenuItemSave.setEnabled(focusPanel!=null && focusPanel.isChanged());
        jMenuItemSaveAs.setEnabled(focusPanel!=null && focusPanel.isChanged());
        jMenuItemSaveAll.setEnabled(focusPanel!=null && focusPanel.isChanged());
        jMenuItemPrint.setEnabled(focusPanel!=null && focusPanel.canPrint());
        jMenuItemUndo.setEnabled(focusPanel!=null && focusPanel.canUndo());
        jMenuItemRedo.setEnabled(focusPanel!=null && focusPanel.canRedo());
        jMenuItemCut.setEnabled(focusPanel!=null && focusPanel.canCut());
        jMenuItemCopy.setEnabled(focusPanel!=null && focusPanel.canCopy());
        jMenuItemPaste.setEnabled(focusPanel!=null && ClipBoard!=null && focusPanel.canPaste(ClipBoard));
        jMenuItemDelete.setEnabled(focusPanel!=null && focusPanel.canDelete());
        jMenuItemFind.setEnabled(focusPanel!=null && focusPanel.canFind());
        jMenuItemReplace.setEnabled(focusPanel!=null && focusPanel.canReplace());
    }

    private RootPanel focusPanel = null;

    /** A given window or panel has taken over the focus.  Adjust appropriately. */
    public void updateIDE(RootPanel p) {
        if (focusPanel != p) {
            focusPanel = p;
            setState();
        }
    }

    // Initialise recently-used project files from list, and
    // place on File menu.
    private void initRecentlyUsedFileMenuEntries() {
    }

    // Add a menu item to a menu.  Return the item.
    private javax.swing.JMenuItem addMenuItem(javax.swing.JMenuItem target, javax.swing.JMenuItem item) {
        item.setFont(getMenuFont());
        target.add(item);
        return item;
    }

    // Add a menu item to a menu.  Return the item.
    private javax.swing.JMenuItem addMenuItem(javax.swing.JMenuItem target, String item) {
        return addMenuItem(target, new javax.swing.JMenuItem(item));
    }

    // Add a menu item to a menu.  Return the item.
    private javax.swing.JMenuItem addMenuItem(javax.swing.JMenuItem target, String item, char mnemonic) {
        javax.swing.JMenuItem j = addMenuItem(target, item);
        j.setMnemonic(mnemonic);
        return j;
    }

    // Add a menu item to a menu.  Return the item.
    private javax.swing.JMenuItem addMenuItem(javax.swing.JMenuItem target, String item, javax.swing.KeyStroke accel) {
        javax.swing.JMenuItem j = addMenuItem(target, item);
        j.setAccelerator(accel);
        return j;
    }

    // Add a menu item to a menu.  Return the item.
    private javax.swing.JMenuItem addMenuItem(javax.swing.JMenuItem target, String item, char mnemonic, javax.swing.KeyStroke accel) {
        javax.swing.JMenuItem j = addMenuItem(target, item, mnemonic);
        j.setAccelerator(accel);
        return j;
    }

    // Add an array of menu items to a menu.
    private void addMenuItems(javax.swing.JMenuItem target, javax.swing.JMenuItem items[]) {
        for (int i=0; i<items.length; i++)
            addMenuItem(target, items[i]);
    }

    // Add an entry to the main menu.
    private javax.swing.JMenu addMainMenuItem(String s, char mnemonic) {
        javax.swing.JMenu j = new javax.swing.JMenu(s);
        j.setMnemonic(mnemonic);
        j.setFont(MenuFont);
        jMenuBarMain.add(j);
        return j;
    }

    private javax.swing.JMenu jMenuFile;

    // Build a new 'File' menu
    private void buildMenuFile() {
        jMenuFile = addMainMenuItem("File", 'F');
        addMenuItem(jMenuFile, "New Project");
        jMenuFile.add(new javax.swing.JSeparator());
        addMenuItem(jMenuFile, "Open File...");
        jMenuItemMount = addMenuItem(jMenuFile, "Mount Directory...");
        jMenuItemUnMount = addMenuItem(jMenuFile, "Unmount Directory...");
        jMenuItemImport = addMenuItem(jMenuFile, "Import into Project...");
        jMenuItemSave = addMenuItem(jMenuFile, "Save");
        jMenuItemSaveAs = addMenuItem(jMenuFile, "Save As...");
        jMenuItemSaveAll = addMenuItem(jMenuFile, "Save All");
        jMenuFile.add(new javax.swing.JSeparator());
        jMenuItemPrint = addMenuItem(jMenuFile, "Print...");
        addMenuItem(jMenuFile, "Page setup...");
        jMenuFile.add(new javax.swing.JSeparator());
        addMenuItem(jMenuFile, "Exit").addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                doExit();
            }
        });
        jMenuFile.add(new javax.swing.JSeparator());
        initRecentlyUsedFileMenuEntries();
    }

    private javax.swing.JMenu jMenuEdit;

    // Build a new 'Edit' menu
    private void buildMenuEdit() {
        jMenuEdit = addMainMenuItem("Edit", 'E');
        jMenuItemUndo = addMenuItem(jMenuEdit, "Undo", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_UNDO, 0));
        jMenuItemRedo = addMenuItem(jMenuEdit, "Redo", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_Y, java.awt.event.InputEvent.CTRL_MASK));
        jMenuEdit.add(new javax.swing.JSeparator());
        jMenuItemCut = addMenuItem(jMenuEdit, "Cut", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_CUT, 0));
        jMenuItemCopy = addMenuItem(jMenuEdit, "Copy", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_COPY, 0));
        jMenuItemPaste = addMenuItem(jMenuEdit, "Paste", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_PASTE, 0));
        jMenuItemDelete = addMenuItem(jMenuEdit, "Delete", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_DELETE, 0));
        jMenuEdit.add(new javax.swing.JSeparator());
        jMenuItemFind = addMenuItem(jMenuEdit, "Find", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_FIND, 0));
        jMenuItemReplace = addMenuItem(jMenuEdit, "Replace", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_R, java.awt.event.InputEvent.CTRL_MASK));
    }

    private javax.swing.JMenu jMenuView;

    private static int viewCount = 0;

    // Add a new 'View' menu item.
    private javax.swing.JMenuItem addViewItem(String description, final RootPanel w) {
        return addMenuItem(jMenuView, description,
            javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_1 + viewCount++,
                java.awt.event.InputEvent.CTRL_MASK));
    }

    // Build a new 'View' menu
    private void buildMenuView() {
        jMenuView = addMainMenuItem("View", 'V');

        addViewItem("Explorer", theExplorer).addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                switch (theExplorer.getPaneState()) {
                    case RootPanel.PANEL_NORMALIZED:            // normalized to maximized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_LEFT);
                        jSplitPaneLeft.setZoom(IDESplitPane.ZOOM_TOP);
                        theExplorer.setPaneState(theExplorer.PANEL_MAXIMIZED);
                        break;
                    case RootPanel.PANEL_MAXIMIZED:             // maximized to minimized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_RIGHT);
                        jSplitPaneLeft.setZoom(IDESplitPane.ZOOM_BOTTOM);
                        theExplorer.setPaneState(theExplorer.PANEL_MINIMIZED);
                    case RootPanel.PANEL_MINIMIZED:             // minimized to normalized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_NORMALIZED);
                        jSplitPaneLeft.setZoom(IDESplitPane.ZOOM_NORMALIZED);
                        theExplorer.setPaneState(theExplorer.PANEL_NORMALIZED);
                }
            }
        });

        addViewItem("Editor", theEditor).addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                switch (theEditor.getPaneState()) {
                    case RootPanel.PANEL_NORMALIZED:            // normalized to maximized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_RIGHT);
                        jSplitPaneRight.setZoom(IDESplitPane.ZOOM_TOP);
                        theEditor.setPaneState(theEditor.PANEL_MAXIMIZED);
                        break;
                    case RootPanel.PANEL_MAXIMIZED:             // maximized to minimized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_LEFT);
                        jSplitPaneRight.setZoom(IDESplitPane.ZOOM_BOTTOM);
                        theEditor.setPaneState(theEditor.PANEL_MINIMIZED);
                    case RootPanel.PANEL_MINIMIZED:             // minimized to normalized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_NORMALIZED);
                        jSplitPaneRight.setZoom(IDESplitPane.ZOOM_NORMALIZED);
                        theEditor.setPaneState(theEditor.PANEL_NORMALIZED);
                }
            }
        });

        addViewItem("Log", theLog).addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                switch (theLog.getPaneState()) {
                    case RootPanel.PANEL_NORMALIZED:            // normalized to maximized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_LEFT);
                        jSplitPaneLeft.setZoom(IDESplitPane.ZOOM_BOTTOM);
                        theLog.setPaneState(theLog.PANEL_MAXIMIZED);
                        break;
                    case RootPanel.PANEL_MAXIMIZED:             // maximized to minimized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_RIGHT);
                        jSplitPaneLeft.setZoom(IDESplitPane.ZOOM_TOP);
                        theLog.setPaneState(theLog.PANEL_MINIMIZED);
                    case RootPanel.PANEL_MINIMIZED:             // minimized to normalized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_NORMALIZED);
                        jSplitPaneLeft.setZoom(IDESplitPane.ZOOM_NORMALIZED);
                        theLog.setPaneState(theLog.PANEL_NORMALIZED);
                }
            }
        });

        addViewItem("Properties", theProperties).addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                switch (theProperties.getPaneState()) {
                    case RootPanel.PANEL_NORMALIZED:            // normalized to maximized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_RIGHT);
                        jSplitPaneRight.setZoom(IDESplitPane.ZOOM_BOTTOM);
                        theProperties.setPaneState(theProperties.PANEL_MAXIMIZED);
                        break;
                    case RootPanel.PANEL_MAXIMIZED:             // maximized to minimized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_LEFT);
                        jSplitPaneRight.setZoom(IDESplitPane.ZOOM_TOP);
                        theProperties.setPaneState(theProperties.PANEL_MINIMIZED);
                    case RootPanel.PANEL_MINIMIZED:             // minimized to normalized
                        jSplitPaneMain.setZoom(IDESplitPane.ZOOM_NORMALIZED);
                        jSplitPaneRight.setZoom(IDESplitPane.ZOOM_NORMALIZED);
                        theProperties.setPaneState(theProperties.PANEL_NORMALIZED);
                }
            }
        });
    }

    private javax.swing.JMenu jMenuTools;

    // Build a new 'Tools' menu
    private void buildMenuTools() {
        jMenuTools = addMainMenuItem("Tools", 'T');
        addMenuItem(jMenuTools, "Add Plug-In...");
    }

    private javax.swing.JMenu jMenuWindow;

    // Build a new 'Window' menu
    private void buildMenuWindow() {
        jMenuWindow = addMainMenuItem("Window", 'W');

        addMenuItem(jMenuWindow, "Vertical Split", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_I, java.awt.event.InputEvent.CTRL_MASK))
        .addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                jSplitPaneMain.nextZoom();
            }
        });

        addMenuItem(jMenuWindow, "Left Split", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_J, java.awt.event.InputEvent.CTRL_MASK))
        .addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                jSplitPaneLeft.nextZoom();
            }
        });

        addMenuItem(jMenuWindow, "Right Split", javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_K, java.awt.event.InputEvent.CTRL_MASK))
        .addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent e) {
                jSplitPaneRight.nextZoom();
            }
        });
    }

    private javax.swing.JMenu jMenuHelp;

    // Build a new 'Help' menu
    private void buildMenuHelp() {
        jMenuHelp = addMainMenuItem("Help", 'H');
        addMenuItem(jMenuHelp, "Contents");
        addMenuItem(jMenuHelp, "Index");
        jMenuHelp.add(new javax.swing.JSeparator());
        addMenuItem(jMenuHelp, "About");
    }

    /** True if we're run as an application. */
    private static boolean Application = false;

    // Timer used for exit poll of running daemons.
    private javax.swing.Timer ShutdownTimer = null;

    /** Exit the Application */
    public void doExit() {
        // Save and close editor sessions.
        for (int i=0; i<theEditor.getTabCount(); i++) {
            ca.mb.armchair.JVPL.Shell s = (ca.mb.armchair.JVPL.Shell)theEditor.getTab(i);
            s.promptForSaveModelUrgent();
        }
        // Save library
        theExplorer.promptForSaveLibraryUrgent();
        // outta here...
        if (Application) {
            LogPrintln("Waiting for tasks to finish.");
            ShutdownTimer = new javax.swing.Timer(1000, new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    // Anybody still busy?
                    int RegisteredDaemonCount = getRegisteredDaemonCount();
                    if (RegisteredDaemonCount > 0) {
                        LogPrintln("Waiting for " + RegisteredDaemonCount + " tasks to finish.");
                        return;
                    }
                    ShutdownTimer.stop();
                    LogPrintln("Application exiting.");
                    System.exit(0);
                }
            });
            ShutdownTimer.setRepeats(true);
            ShutdownTimer.start();
        }
    }

    /** Run without System.exit(0) when window closes. */
    public static void run() {
        theIDE.launch();
    }

    /** The IDE instance. */
    private static IDE theIDE = new IDE();

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        Application = true;
        theIDE.launch();
    }

    /** Display a control panel (typically a Properties display) with a given title.  */
    public void displayControlPanel(javax.swing.JPanel controlPanel, String title) {
        if (theProperties != null)
            theProperties.addContentPanel(controlPanel);
    }

    // Count of registered daemons.
    private int RegisteredDaemons = 0;

    /** Register the fact that a background process has begun.  */
    public void registerDaemon() {
        RegisteredDaemons++;
    }

    /** Return number of running background processes.  */
    public int getRegisteredDaemonCount() {
        return RegisteredDaemons;
    }

    /** Register the fact that a background process has ended.  */
    public void unregisterDaemon() {
        RegisteredDaemons--;
    }

    /** Tell the IDE to update the Explorer, because we've modified something the Explorer displays.  */
    public void updateExplorer() {
        theExplorer.refresh();
    }

}


text:
package ca.uhn.fhir.parser;

import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.dstu3.model.Identifier;
import org.hl7.fhir.dstu3.model.MessageHeader;

import ca.uhn.fhir.model.api.annotation.Block;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.Extension;
import ca.uhn.fhir.model.api.annotation.ResourceDef;

@ResourceDef(name = "MessageHeader")
public class FooMessageHeader extends MessageHeader {

	private static final long serialVersionUID = 1L;

	@Block()
	public static class FooMessageSourceComponent extends MessageHeader.MessageSourceComponent {

		private static final long serialVersionUID = 1L;
		@Child(name = "ext-messageheader-application-id", type = Identifier.class, modifier = true)
		@Description(shortDefinition = "Message Header Application ID")
		@Extension(url = "http://foo", definedLocally = false, isModifier = false)
		private Identifier messageHeaderApplicationId;

		/*
		 * Get messageHeaderApplicationId
		 */
		public Identifier getMessageHeaderApplicationId() throws FHIRException {

			if (messageHeaderApplicationId == null) {
				messageHeaderApplicationId = new Identifier();
			}
			return messageHeaderApplicationId;
		}

		/*
		 * Set messageHeaderApplicationId
		 */
		public void setmessageHeaderApplicationId(Identifier messageHeaderApplicationId) {
			this.messageHeaderApplicationId = messageHeaderApplicationId;
		}

	}

}


text:
FROM registry.ng.bluemix.net/ibmliberty

# Install the application
ADD . /mc
ENV MC_PORT 25565
EXPOSE 25565 4715
RUN apt-get update && apt-get install -y \
  python \
  git
WORKDIR /mc
RUN git clone https://github.com/paulolc/mcpi-scratch
# Define command to run the application when the container starts
RUN chmod 755 start-mcscratch.sh
CMD ./start-mcscratch.sh


text:
BlackBerry WebWorks CLI
=======================

webworks-cli is a command line tool which wraps the Apache Cordova CLI for BB10 WebWorks development

Usage
-----

    webworks [--verbose] command [options]

    These commands may be used globally:
       create     create a new project
       target     manage devices and simulators
       help       view usage for all commands

    These commands may be used from within a project directory:
       build      package app into a BAR file
       run        build and deploy to a device
       emulate    build and deploy to a simulator
       plugin     add or remove plugins
       serve      start a webserver to host project assets

    See 'webworks help <command>' for more information on a specific command.


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syst. veg. 1:637. 1824 ("1825")

#### Original name
null

### Remarks
null


text:
import random
import numpy as np
import itertools, copy

def split_data_with_overlap(data_grouped_by_hour, valid_size, overlap_size, window_size,
                            overlap_interictal=True, overlap_preictal=True, random_state=42):
    random.seed(random_state)

    number_of_test_interictal_hours = max(1, int(len(data_grouped_by_hour['interictal']) * valid_size))
    number_of_test_preictal_hours = max(1, int(len(data_grouped_by_hour['preictal']) * valid_size))

    interictal_hours_indexes = range(len(data_grouped_by_hour['interictal']))
    preictal_hours_indexes = range(len(data_grouped_by_hour['preictal']))

    valid_interictal_hours_indexes = random.sample(interictal_hours_indexes, number_of_test_interictal_hours)
    valid_preictal_hours_indexes = random.sample(preictal_hours_indexes, number_of_test_preictal_hours)

    train_interictal_hours_indexes = [idx for idx in interictal_hours_indexes if
                                      idx not in set(valid_interictal_hours_indexes)]
    train_preictal_hours_indexes = [idx for idx in preictal_hours_indexes if
                                    idx not in set(valid_preictal_hours_indexes)]

    def fill_data_list(class_label, indexes):
        overlap = overlap_preictal if class_label == 'preictal' else overlap_interictal
        x = []
        for idx in indexes:
            data_hour = data_grouped_by_hour[class_label][idx]
            if overlap:
                data = np.concatenate(data_hour, axis=2)
                for i in xrange(divmod(data.shape[-1] - overlap_size, window_size - overlap_size)[0]):
                    i *= window_size - overlap_size
                    x.append(data[..., i:i + window_size])
            else:
                x.extend(data_hour)
        return x

    x_valid_interictal = fill_data_list('interictal', valid_interictal_hours_indexes)
    x_valid_preictal = fill_data_list('preictal', valid_preictal_hours_indexes)
    x_train_interictal = fill_data_list('interictal', train_interictal_hours_indexes)
    x_train_preictal = fill_data_list('preictal', train_preictal_hours_indexes)

    x_valid = x_valid_interictal + x_valid_preictal
    y_valid = len(x_valid_interictal) * [0] + len(x_valid_preictal) * [1]
    combined = zip(x_valid, y_valid)
    random.shuffle(combined)
    x_valid[:], y_valid[:] = zip(*combined)

    x_train = x_train_interictal + x_train_preictal
    y_train = len(x_train_interictal) * [0] + len(x_train_preictal) * [1]
    combined = zip(x_train, y_train)
    random.shuffle(combined)
    x_train[:], y_train[:] = zip(*combined)

    return np.array(x_train, dtype='float32'), np.array(y_train, dtype='int8'), \
           np.array(x_valid, dtype='float32'), np.array(y_valid, dtype='int8')

def generate_overlapped_data(data_grouped_by_hour, overlap_size, window_size,
                                       overlap_interictal=True, overlap_preictal=True, random_state=42):
    random.seed(random_state)

    interictal_hours_indexes = range(len(data_grouped_by_hour['interictal']))
    preictal_hours_indexes = range(len(data_grouped_by_hour['preictal']))

    def fill_data_list(class_label, indexes):
        overlap = overlap_preictal if class_label == 'preictal' else overlap_interictal
        x = []
        for idx in indexes:
            data_hour = data_grouped_by_hour[class_label][idx]
            if overlap:
                data = np.concatenate(data_hour, axis=2)
                for i in xrange(divmod(data.shape[-1] - overlap_size, window_size - overlap_size)[0]):
                    i *= window_size - overlap_size
                    x.append(data[..., i:i + window_size])
            else:
                x.extend(data_hour)
        return x

    x_interictal = fill_data_list('interictal', interictal_hours_indexes)
    x_preictal = fill_data_list('preictal', preictal_hours_indexes)

    x = x_interictal + x_preictal
    y = len(x_interictal) * [0] + len(x_preictal) * [1]
    combined = zip(x, y)
    random.shuffle(combined)
    x[:], y[:] = zip(*combined)

    return np.array(x, dtype='float32'), np.array(y, dtype='int8')

def split_train_valid_filenames(subject, filenames_grouped_by_hour, random_state=42):
    rng = np.random.RandomState(random_state)

    preictal = copy.deepcopy(filenames_grouped_by_hour[subject]['preictal'])
    rng.shuffle(preictal)
    interictal = copy.deepcopy(filenames_grouped_by_hour[subject]['interictal'])
    rng.shuffle(interictal)

    n_preictal = len(preictal)
    n_interictal = len(interictal)

    n_valid_preictal = int(max(1, np.round(0.25 * n_preictal)))
    n_valid_interictal = int(max(1, np.round(0.25 * n_interictal)))

    valid = preictal[:n_valid_preictal] + interictal[:n_valid_interictal]
    valid = list(itertools.chain.from_iterable(valid))

    train = preictal[n_valid_preictal:] + interictal[n_valid_interictal:]
    train = list(itertools.chain.from_iterable(train))

    return {'train_filenames': train, 'valid_filnames': valid}


text:
/* Generated by Snowball 2.2.0 - https://snowballstem.org/ */

#ifdef __cplusplus
extern "C" {
#endif

extern struct SN_env * romanian_ISO_8859_2_create_env(void);
extern void romanian_ISO_8859_2_close_env(struct SN_env * z);

extern int romanian_ISO_8859_2_stem(struct SN_env * z);

#ifdef __cplusplus
}
#endif


text:
module.exports = function(RED) {
    "use strict";
    var settings = RED.settings;
    var events = require("events");
    var serialp = require("serialport");
    var bufMaxSize = 32768;  // Max serial buffer size, for inputs...

    // TODO: 'serialPool' should be encapsulated in SerialPortNode

    function SerialPortNode(n) {
        RED.nodes.createNode(this,n);
        this.serialport = n.serialport;
        this.newline = n.newline;
        this.addchar = n.addchar || "false";
        this.serialbaud = parseInt(n.serialbaud) || 57600;
        this.databits = parseInt(n.databits) || 8;
        this.parity = n.parity || "none";
        this.stopbits = parseInt(n.stopbits) || 1;
        this.bin = n.bin || "false";
        this.out = n.out || "char";
    }
    RED.nodes.registerType("serial-port",SerialPortNode);

    function SerialOutNode(n) {
        RED.nodes.createNode(this,n);
        this.serial = n.serial;
        this.serialConfig = RED.nodes.getNode(this.serial);

        if (this.serialConfig) {
            var node = this;
            node.port = serialPool.get(this.serialConfig.serialport,
                this.serialConfig.serialbaud,
                this.serialConfig.databits,
                this.serialConfig.parity,
                this.serialConfig.stopbits,
                this.serialConfig.newline);
            node.addCh = "";
            if (node.serialConfig.addchar == "true" || node.serialConfig.addchar === true) {
                node.addCh = this.serialConfig.newline.replace("\\n","\n").replace("\\r","\r").replace("\\t","\t").replace("\\e","\e").replace("\\f","\f").replace("\\0","\0");
            }
            node.on("input",function(msg) {
                if (msg.hasOwnProperty("payload")) {
                    var payload = msg.payload;
                    if (!Buffer.isBuffer(payload)) {
                        if (typeof payload === "object") {
                            payload = JSON.stringify(payload);
                        } else {
                            payload = payload.toString();
                        }
                        payload += node.addCh;
                    } else if (node.addCh !== "") {
                        payload = Buffer.concat([payload,new Buffer(node.addCh)]);
                    }
                    node.port.write(payload,function(err,res) {
                        if (err) {
                            var errmsg = err.toString().replace("Serialport","Serialport "+node.port.serial.path);
                            node.error(errmsg,msg);
                        }
                    });
                }
            });
            node.port.on('ready', function() {
                node.status({fill:"green",shape:"dot",text:"connected"});
            });
            node.port.on('closed', function() {
                node.status({fill:"red",shape:"ring",text:"not connected"});
            });
        } else {
            this.error("missing serial config");
        }

        this.on("close", function(done) {
            if (this.serialConfig) {
                serialPool.close(this.serialConfig.serialport,done);
            } else {
                done();
            }
        });
    }
    RED.nodes.registerType("serial out",SerialOutNode);

    function SerialInNode(n) {
        RED.nodes.createNode(this,n);
        this.serial = n.serial;
        this.serialConfig = RED.nodes.getNode(this.serial);

        if (this.serialConfig) {
            var node = this;
            node.tout = null;
            var buf;
            if (node.serialConfig.out != "count") { buf = new Buffer(bufMaxSize); }
            else { buf = new Buffer(Number(node.serialConfig.newline)); }
            var i = 0;
            node.status({fill:"grey",shape:"dot",text:"unknown"});
            node.port = serialPool.get(this.serialConfig.serialport,
                this.serialConfig.serialbaud,
                this.serialConfig.databits,
                this.serialConfig.parity,
                this.serialConfig.stopbits,
                this.serialConfig.newline
            );

            var splitc;
            if (node.serialConfig.newline.substr(0,2) == "0x") {
                splitc = new Buffer([parseInt(node.serialConfig.newline)]);
            } else {
                splitc = new Buffer(node.serialConfig.newline.replace("\\n","\n").replace("\\r","\r").replace("\\t","\t").replace("\\e","\e").replace("\\f","\f").replace("\\0","\0"));
            }

            this.port.on('data', function(msg) {
                // single char buffer
                if ((node.serialConfig.newline === 0)||(node.serialConfig.newline === "")) {
                    if (node.serialConfig.bin !== "bin") { node.send({"payload": String.fromCharCode(msg)}); }
                    else { node.send({"payload": new Buffer([msg])}); }
                }
                else {
                    // do the timer thing
                    if (node.serialConfig.out === "time")  {
                        if (node.tout) {
                            i += 1;
                            buf[i] = msg;
                        }
                        else {
                            node.tout = setTimeout(function () {
                                node.tout = null;
                                var m = new Buffer(i+1);
                                buf.copy(m,0,0,i+1);
                                if (node.serialConfig.bin !== "bin") { m = m.toString(); }
                                node.send({"payload": m});
                                m = null;
                            }, node.serialConfig.newline);
                            i = 0;
                            buf[0] = msg;
                        }
                    }
                    // count bytes into a buffer...
                    else if (node.serialConfig.out === "count") {
                        buf[i] = msg;
                        i += 1;
                        if ( i >= parseInt(node.serialConfig.newline)) {
                            var m = new Buffer(i);
                            buf.copy(m,0,0,i);
                            if (node.serialConfig.bin !== "bin") { m = m.toString(); }
                            node.send({"payload":m});
                            m = null;
                            i = 0;
                        }
                    }
                    // look to match char...
                    else if (node.serialConfig.out === "char") {
                        buf[i] = msg;
                        i += 1;
                        if ((msg === splitc[0]) || (i === bufMaxSize)) {
                            var m = new Buffer(i);
                            buf.copy(m,0,0,i);
                            if (node.serialConfig.bin !== "bin") { m = m.toString(); }
                            node.send({"payload":m});
                            m = null;
                            i = 0;
                        }
                    }
                    else { node.log("should never get here"); }
                }
            });
            this.port.on('ready', function() {
                node.status({fill:"green",shape:"dot",text:"connected"});
            });
            this.port.on('closed', function() {
                node.status({fill:"red",shape:"ring",text:"not connected"});
            });
        } else {
            this.error("missing serial config");
        }

        this.on("close", function(done) {
            if (this.serialConfig) {
                serialPool.close(this.serialConfig.serialport,done);
            } else {
                done();
            }
        });
    }
    RED.nodes.registerType("serial in",SerialInNode);

    var serialPool = function() {
        var connections = {};
        return {
            get:function(port,baud,databits,parity,stopbits,newline,callback) {
                var id = port;
                if (!connections[id]) {
                    connections[id] = function() {
                        var obj = {
                            _emitter: new events.EventEmitter(),
                            serial: null,
                            _closing: false,
                            tout: null,
                            on: function(a,b) { this._emitter.on(a,b); },
                            close: function(cb) { this.serial.close(cb); },
                            write: function(m,cb) { this.serial.write(m,cb); },
                        }
                        //newline = newline.replace("\\n","\n").replace("\\r","\r");
                        var setupSerial = function() {
                            //if (newline == "") {
                                obj.serial = new serialp.SerialPort(port,{
                                    baudrate: baud,
                                    databits: databits,
                                    parity: parity,
                                    stopbits: stopbits,
                                    parser: serialp.parsers.raw
                                },true, function(err, results) { if (err) { obj.serial.emit('error',err); } });
                            //}
                            //else {
                            //    obj.serial = new serialp.SerialPort(port,{
                            //        baudrate: baud,
                            //        databits: databits,
                            //        parity: parity,
                            //        stopbits: stopbits,
                            //        parser: serialp.parsers.readline(newline)
                            //    },true, function(err, results) { if (err) obj.serial.emit('error',err); });
                            //}
                            obj.serial.on('error', function(err) {
                                RED.log.error("serial port "+port+" error "+err);
                                obj._emitter.emit('closed');
                                obj.tout = setTimeout(function() {
                                    setupSerial();
                                }, settings.serialReconnectTime);
                            });
                            obj.serial.on('close', function() {
                                if (!obj._closing) {
                                    RED.log.error("serial port "+port+" closed unexpectedly");
                                    obj._emitter.emit('closed');
                                    obj.tout = setTimeout(function() {
                                        setupSerial();
                                    }, settings.serialReconnectTime);
                                }
                            });
                            obj.serial.on('open',function() {
                                RED.log.info("serial port "+port+" opened at "+baud+" baud "+databits+""+parity.charAt(0).toUpperCase()+stopbits);
                                if (obj.tout) { clearTimeout(obj.tout); }
                                //obj.serial.flush();
                                obj._emitter.emit('ready');
                            });
                            obj.serial.on('data',function(d) {
                                //console.log(Buffer.isBuffer(d),d.length,d);
                                //if (typeof d !== "string") {
                                //    //d = d.toString();
                                    for (var z=0; z<d.length; z++) {
                                        obj._emitter.emit('data',d[z]);
                                    }
                                //}
                                //else {
                                //    obj._emitter.emit('data',d);
                                //}
                            });
                            obj.serial.on("disconnect",function() {
                                RED.log.error("serial port "+port+" gone away");
                            });
                        }
                        setupSerial();
                        return obj;
                    }();
                }
                return connections[id];
            },
            close: function(port,done) {
                if (connections[port]) {
                    if (connections[port].tout != null) {
                        clearTimeout(connections[port].tout);
                    }
                    connections[port]._closing = true;
                    try {
                        connections[port].close(function() {
                            RED.log.info("serial port closed");
                            done();
                        });
                    }
                    catch(err) { }
                    delete connections[port];
                } else {
                    done();
                }
            }
        }
    }();

    RED.httpAdmin.get("/serialports", RED.auth.needsPermission('serial.read'), function(req,res) {
        serialp.list(function (err, ports) {
            res.json(ports);
        });
    });
}