text:
#include <linux/module.h>
#include "minix.h"
#include <linux/buffer_head.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/highuid.h>
#include <linux/vfs.h>

static void minix_read_inode(struct inode * inode);
static int minix_write_inode(struct inode * inode, int wait);
static int minix_statfs(struct super_block *sb, struct kstatfs *buf);
static int minix_remount (struct super_block * sb, int * flags, char * data);

static void minix_delete_inode(struct inode *inode)
{
	truncate_inode_pages(&inode->i_data, 0);
	inode->i_size = 0;
	minix_truncate(inode);
	minix_free_inode(inode);
}

static void minix_put_super(struct super_block *sb)
{
	int i;
	struct minix_sb_info *sbi = minix_sb(sb);

	if (!(sb->s_flags & MS_RDONLY)) {
		sbi->s_ms->s_state = sbi->s_mount_state;
		mark_buffer_dirty(sbi->s_sbh);
	}
	for (i = 0; i < sbi->s_imap_blocks; i++)
		brelse(sbi->s_imap[i]);
	for (i = 0; i < sbi->s_zmap_blocks; i++)
		brelse(sbi->s_zmap[i]);
	brelse (sbi->s_sbh);
	kfree(sbi->s_imap);
	sb->s_fs_info = NULL;
	kfree(sbi);

	return;
}

static kmem_cache_t * minix_inode_cachep;

static struct inode *minix_alloc_inode(struct super_block *sb)
{
	struct minix_inode_info *ei;
	ei = (struct minix_inode_info *)kmem_cache_alloc(minix_inode_cachep, SLAB_KERNEL);
	if (!ei)
		return NULL;
	return &ei->vfs_inode;
}

static void minix_destroy_inode(struct inode *inode)
{
	kmem_cache_free(minix_inode_cachep, minix_i(inode));
}

static void init_once(void * foo, kmem_cache_t * cachep, unsigned long flags)
{
	struct minix_inode_info *ei = (struct minix_inode_info *) foo;

	if ((flags & (SLAB_CTOR_VERIFY|SLAB_CTOR_CONSTRUCTOR)) ==
	    SLAB_CTOR_CONSTRUCTOR)
		inode_init_once(&ei->vfs_inode);
}

static int init_inodecache(void)
{
	minix_inode_cachep = kmem_cache_create("minix_inode_cache",
					     sizeof(struct minix_inode_info),
					     0, SLAB_RECLAIM_ACCOUNT,
					     init_once, NULL);
	if (minix_inode_cachep == NULL)
		return -ENOMEM;
	return 0;
}

static void destroy_inodecache(void)
{
	if (kmem_cache_destroy(minix_inode_cachep))
		printk(KERN_INFO "minix_inode_cache: not all structures were freed\n");
}

static struct super_operations minix_sops = {
	.alloc_inode	= minix_alloc_inode,
	.destroy_inode	= minix_destroy_inode,
	.read_inode	= minix_read_inode,
	.write_inode	= minix_write_inode,
	.delete_inode	= minix_delete_inode,
	.put_super	= minix_put_super,
	.statfs		= minix_statfs,
	.remount_fs	= minix_remount,
};

static int minix_remount (struct super_block * sb, int * flags, char * data)
{
	struct minix_sb_info * sbi = minix_sb(sb);
	struct minix_super_block * ms;

	ms = sbi->s_ms;
	if ((*flags & MS_RDONLY) == (sb->s_flags & MS_RDONLY))
		return 0;
	if (*flags & MS_RDONLY) {
		if (ms->s_state & MINIX_VALID_FS ||
		    !(sbi->s_mount_state & MINIX_VALID_FS))
			return 0;
		/* Mounting a rw partition read-only. */
		ms->s_state = sbi->s_mount_state;
		mark_buffer_dirty(sbi->s_sbh);
	} else {
	  	/* Mount a partition which is read-only, read-write. */
		sbi->s_mount_state = ms->s_state;
		ms->s_state &= ~MINIX_VALID_FS;
		mark_buffer_dirty(sbi->s_sbh);

		if (!(sbi->s_mount_state & MINIX_VALID_FS))
			printk ("MINIX-fs warning: remounting unchecked fs, "
				"running fsck is recommended.\n");
		else if ((sbi->s_mount_state & MINIX_ERROR_FS))
			printk ("MINIX-fs warning: remounting fs with errors, "
				"running fsck is recommended.\n");
	}
	return 0;
}

static int minix_fill_super(struct super_block *s, void *data, int silent)
{
	struct buffer_head *bh;
	struct buffer_head **map;
	struct minix_super_block *ms;
	int i, block;
	struct inode *root_inode;
	struct minix_sb_info *sbi;

	sbi = kmalloc(sizeof(struct minix_sb_info), GFP_KERNEL);
	if (!sbi)
		return -ENOMEM;
	s->s_fs_info = sbi;
	memset(sbi, 0, sizeof(struct minix_sb_info));

	/* N.B. These should be compile-time tests.
	   Unfortunately that is impossible. */
	if (32 != sizeof (struct minix_inode))
		panic("bad V1 i-node size");
	if (64 != sizeof(struct minix2_inode))
		panic("bad V2 i-node size");

	if (!sb_set_blocksize(s, BLOCK_SIZE))
		goto out_bad_hblock;

	if (!(bh = sb_bread(s, 1)))
		goto out_bad_sb;

	ms = (struct minix_super_block *) bh->b_data;
	sbi->s_ms = ms;
	sbi->s_sbh = bh;
	sbi->s_mount_state = ms->s_state;
	sbi->s_ninodes = ms->s_ninodes;
	sbi->s_nzones = ms->s_nzones;
	sbi->s_imap_blocks = ms->s_imap_blocks;
	sbi->s_zmap_blocks = ms->s_zmap_blocks;
	sbi->s_firstdatazone = ms->s_firstdatazone;
	sbi->s_log_zone_size = ms->s_log_zone_size;
	sbi->s_max_size = ms->s_max_size;
	s->s_magic = ms->s_magic;
	if (s->s_magic == MINIX_SUPER_MAGIC) {
		sbi->s_version = MINIX_V1;
		sbi->s_dirsize = 16;
		sbi->s_namelen = 14;
		sbi->s_link_max = MINIX_LINK_MAX;
	} else if (s->s_magic == MINIX_SUPER_MAGIC2) {
		sbi->s_version = MINIX_V1;
		sbi->s_dirsize = 32;
		sbi->s_namelen = 30;
		sbi->s_link_max = MINIX_LINK_MAX;
	} else if (s->s_magic == MINIX2_SUPER_MAGIC) {
		sbi->s_version = MINIX_V2;
		sbi->s_nzones = ms->s_zones;
		sbi->s_dirsize = 16;
		sbi->s_namelen = 14;
		sbi->s_link_max = MINIX2_LINK_MAX;
	} else if (s->s_magic == MINIX2_SUPER_MAGIC2) {
		sbi->s_version = MINIX_V2;
		sbi->s_nzones = ms->s_zones;
		sbi->s_dirsize = 32;
		sbi->s_namelen = 30;
		sbi->s_link_max = MINIX2_LINK_MAX;
	} else
		goto out_no_fs;

	/*
	 * Allocate the buffer map to keep the superblock small.
	 */
	i = (sbi->s_imap_blocks + sbi->s_zmap_blocks) * sizeof(bh);
	map = kmalloc(i, GFP_KERNEL);
	if (!map)
		goto out_no_map;
	memset(map, 0, i);
	sbi->s_imap = &map[0];
	sbi->s_zmap = &map[sbi->s_imap_blocks];

	block=2;
	for (i=0 ; i < sbi->s_imap_blocks ; i++) {
		if (!(sbi->s_imap[i]=sb_bread(s, block)))
			goto out_no_bitmap;
		block++;
	}
	for (i=0 ; i < sbi->s_zmap_blocks ; i++) {
		if (!(sbi->s_zmap[i]=sb_bread(s, block)))
			goto out_no_bitmap;
		block++;
	}

	minix_set_bit(0,sbi->s_imap[0]->b_data);
	minix_set_bit(0,sbi->s_zmap[0]->b_data);

	/* set up enough so that it can read an inode */
	s->s_op = &minix_sops;
	root_inode = iget(s, MINIX_ROOT_INO);
	if (!root_inode || is_bad_inode(root_inode))
		goto out_no_root;

	s->s_root = d_alloc_root(root_inode);
	if (!s->s_root)
		goto out_iput;

	if (!NO_TRUNCATE)
		s->s_root->d_op = &minix_dentry_operations;

	if (!(s->s_flags & MS_RDONLY)) {
		ms->s_state &= ~MINIX_VALID_FS;
		mark_buffer_dirty(bh);
	}
	if (!(sbi->s_mount_state & MINIX_VALID_FS))
		printk ("MINIX-fs: mounting unchecked file system, "
			"running fsck is recommended.\n");
 	else if (sbi->s_mount_state & MINIX_ERROR_FS)
		printk ("MINIX-fs: mounting file system with errors, "
			"running fsck is recommended.\n");
	return 0;

out_iput:
	iput(root_inode);
	goto out_freemap;

out_no_root:
	if (!silent)
		printk("MINIX-fs: get root inode failed\n");
	goto out_freemap;

out_no_bitmap:
	printk("MINIX-fs: bad superblock or unable to read bitmaps\n");
    out_freemap:
	for (i = 0; i < sbi->s_imap_blocks; i++)
		brelse(sbi->s_imap[i]);
	for (i = 0; i < sbi->s_zmap_blocks; i++)
		brelse(sbi->s_zmap[i]);
	kfree(sbi->s_imap);
	goto out_release;

out_no_map:
	if (!silent)
		printk ("MINIX-fs: can't allocate map\n");
	goto out_release;

out_no_fs:
	if (!silent)
		printk("VFS: Can't find a Minix or Minix V2 filesystem on device "
		       "%s.\n", s->s_id);
    out_release:
	brelse(bh);
	goto out;

out_bad_hblock:
	printk("MINIX-fs: blocksize too small for device.\n");
	goto out;

out_bad_sb:
	printk("MINIX-fs: unable to read superblock\n");
 out:
	s->s_fs_info = NULL;
	kfree(sbi);
	return -EINVAL;
}

static int minix_statfs(struct super_block *sb, struct kstatfs *buf)
{
	struct minix_sb_info *sbi = minix_sb(sb);
	buf->f_type = sb->s_magic;
	buf->f_bsize = sb->s_blocksize;
	buf->f_blocks = (sbi->s_nzones - sbi->s_firstdatazone) << sbi->s_log_zone_size;
	buf->f_bfree = minix_count_free_blocks(sbi);
	buf->f_bavail = buf->f_bfree;
	buf->f_files = sbi->s_ninodes;
	buf->f_ffree = minix_count_free_inodes(sbi);
	buf->f_namelen = sbi->s_namelen;
	return 0;
}

static int minix_get_block(struct inode *inode, sector_t block,
		    struct buffer_head *bh_result, int create)
{
	if (INODE_VERSION(inode) == MINIX_V1)
		return V1_minix_get_block(inode, block, bh_result, create);
	else
		return V2_minix_get_block(inode, block, bh_result, create);
}

static int minix_writepage(struct page *page, struct writeback_control *wbc)
{
	return block_write_full_page(page, minix_get_block, wbc);
}
static int minix_readpage(struct file *file, struct page *page)
{
	return block_read_full_page(page,minix_get_block);
}
static int minix_prepare_write(struct file *file, struct page *page, unsigned from, unsigned to)
{
	return block_prepare_write(page,from,to,minix_get_block);
}
static sector_t minix_bmap(struct address_space *mapping, sector_t block)
{
	return generic_block_bmap(mapping,block,minix_get_block);
}
static struct address_space_operations minix_aops = {
	.readpage = minix_readpage,
	.writepage = minix_writepage,
	.sync_page = block_sync_page,
	.prepare_write = minix_prepare_write,
	.commit_write = generic_commit_write,
	.bmap = minix_bmap
};

static struct inode_operations minix_symlink_inode_operations = {
	.readlink	= generic_readlink,
	.follow_link	= page_follow_link_light,
	.put_link	= page_put_link,
	.getattr	= minix_getattr,
};

void minix_set_inode(struct inode *inode, dev_t rdev)
{
	if (S_ISREG(inode->i_mode)) {
		inode->i_op = &minix_file_inode_operations;
		inode->i_fop = &minix_file_operations;
		inode->i_mapping->a_ops = &minix_aops;
	} else if (S_ISDIR(inode->i_mode)) {
		inode->i_op = &minix_dir_inode_operations;
		inode->i_fop = &minix_dir_operations;
		inode->i_mapping->a_ops = &minix_aops;
	} else if (S_ISLNK(inode->i_mode)) {
		inode->i_op = &minix_symlink_inode_operations;
		inode->i_mapping->a_ops = &minix_aops;
	} else
		init_special_inode(inode, inode->i_mode, rdev);
}

/*
 * The minix V1 function to read an inode.
 */
static void V1_minix_read_inode(struct inode * inode)
{
	struct buffer_head * bh;
	struct minix_inode * raw_inode;
	struct minix_inode_info *minix_inode = minix_i(inode);
	int i;

	raw_inode = minix_V1_raw_inode(inode->i_sb, inode->i_ino, &bh);
	if (!raw_inode) {
		make_bad_inode(inode);
		return;
	}
	inode->i_mode = raw_inode->i_mode;
	inode->i_uid = (uid_t)raw_inode->i_uid;
	inode->i_gid = (gid_t)raw_inode->i_gid;
	inode->i_nlink = raw_inode->i_nlinks;
	inode->i_size = raw_inode->i_size;
	inode->i_mtime.tv_sec = inode->i_atime.tv_sec = inode->i_ctime.tv_sec = raw_inode->i_time;
	inode->i_mtime.tv_nsec = 0;
	inode->i_atime.tv_nsec = 0;
	inode->i_ctime.tv_nsec = 0;
	inode->i_blocks = inode->i_blksize = 0;
	for (i = 0; i < 9; i++)
		minix_inode->u.i1_data[i] = raw_inode->i_zone[i];
	minix_set_inode(inode, old_decode_dev(raw_inode->i_zone[0]));
	brelse(bh);
}

/*
 * The minix V2 function to read an inode.
 */
static void V2_minix_read_inode(struct inode * inode)
{
	struct buffer_head * bh;
	struct minix2_inode * raw_inode;
	struct minix_inode_info *minix_inode = minix_i(inode);
	int i;

	raw_inode = minix_V2_raw_inode(inode->i_sb, inode->i_ino, &bh);
	if (!raw_inode) {
		make_bad_inode(inode);
		return;
	}
	inode->i_mode = raw_inode->i_mode;
	inode->i_uid = (uid_t)raw_inode->i_uid;
	inode->i_gid = (gid_t)raw_inode->i_gid;
	inode->i_nlink = raw_inode->i_nlinks;
	inode->i_size = raw_inode->i_size;
	inode->i_mtime.tv_sec = raw_inode->i_mtime;
	inode->i_atime.tv_sec = raw_inode->i_atime;
	inode->i_ctime.tv_sec = raw_inode->i_ctime;
	inode->i_mtime.tv_nsec = 0;
	inode->i_atime.tv_nsec = 0;
	inode->i_ctime.tv_nsec = 0;
	inode->i_blocks = inode->i_blksize = 0;
	for (i = 0; i < 10; i++)
		minix_inode->u.i2_data[i] = raw_inode->i_zone[i];
	minix_set_inode(inode, old_decode_dev(raw_inode->i_zone[0]));
	brelse(bh);
}

/*
 * The global function to read an inode.
 */
static void minix_read_inode(struct inode * inode)
{
	if (INODE_VERSION(inode) == MINIX_V1)
		V1_minix_read_inode(inode);
	else
		V2_minix_read_inode(inode);
}

/*
 * The minix V1 function to synchronize an inode.
 */
static struct buffer_head * V1_minix_update_inode(struct inode * inode)
{
	struct buffer_head * bh;
	struct minix_inode * raw_inode;
	struct minix_inode_info *minix_inode = minix_i(inode);
	int i;

	raw_inode = minix_V1_raw_inode(inode->i_sb, inode->i_ino, &bh);
	if (!raw_inode)
		return NULL;
	raw_inode->i_mode = inode->i_mode;
	raw_inode->i_uid = fs_high2lowuid(inode->i_uid);
	raw_inode->i_gid = fs_high2lowgid(inode->i_gid);
	raw_inode->i_nlinks = inode->i_nlink;
	raw_inode->i_size = inode->i_size;
	raw_inode->i_time = inode->i_mtime.tv_sec;
	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
		raw_inode->i_zone[0] = old_encode_dev(inode->i_rdev);
	else for (i = 0; i < 9; i++)
		raw_inode->i_zone[i] = minix_inode->u.i1_data[i];
	mark_buffer_dirty(bh);
	return bh;
}

/*
 * The minix V2 function to synchronize an inode.
 */
static struct buffer_head * V2_minix_update_inode(struct inode * inode)
{
	struct buffer_head * bh;
	struct minix2_inode * raw_inode;
	struct minix_inode_info *minix_inode = minix_i(inode);
	int i;

	raw_inode = minix_V2_raw_inode(inode->i_sb, inode->i_ino, &bh);
	if (!raw_inode)
		return NULL;
	raw_inode->i_mode = inode->i_mode;
	raw_inode->i_uid = fs_high2lowuid(inode->i_uid);
	raw_inode->i_gid = fs_high2lowgid(inode->i_gid);
	raw_inode->i_nlinks = inode->i_nlink;
	raw_inode->i_size = inode->i_size;
	raw_inode->i_mtime = inode->i_mtime.tv_sec;
	raw_inode->i_atime = inode->i_atime.tv_sec;
	raw_inode->i_ctime = inode->i_ctime.tv_sec;
	if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode))
		raw_inode->i_zone[0] = old_encode_dev(inode->i_rdev);
	else for (i = 0; i < 10; i++)
		raw_inode->i_zone[i] = minix_inode->u.i2_data[i];
	mark_buffer_dirty(bh);
	return bh;
}

static struct buffer_head *minix_update_inode(struct inode *inode)
{
	if (INODE_VERSION(inode) == MINIX_V1)
		return V1_minix_update_inode(inode);
	else
		return V2_minix_update_inode(inode);
}

static int minix_write_inode(struct inode * inode, int wait)
{
	brelse(minix_update_inode(inode));
	return 0;
}

int minix_sync_inode(struct inode * inode)
{
	int err = 0;
	struct buffer_head *bh;

	bh = minix_update_inode(inode);
	if (bh && buffer_dirty(bh))
	{
		sync_dirty_buffer(bh);
		if (buffer_req(bh) && !buffer_uptodate(bh))
		{
			printk ("IO error syncing minix inode [%s:%08lx]\n",
				inode->i_sb->s_id, inode->i_ino);
			err = -1;
		}
	}
	else if (!bh)
		err = -1;
	brelse (bh);
	return err;
}

int minix_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat)
{
	generic_fillattr(dentry->d_inode, stat);
	if (INODE_VERSION(dentry->d_inode) == MINIX_V1)
		stat->blocks = (BLOCK_SIZE / 512) * V1_minix_blocks(stat->size);
	else
		stat->blocks = (BLOCK_SIZE / 512) * V2_minix_blocks(stat->size);
	stat->blksize = BLOCK_SIZE;
	return 0;
}

/*
 * The function that is called for file truncation.
 */
void minix_truncate(struct inode * inode)
{
	if (!(S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || S_ISLNK(inode->i_mode)))
		return;
	if (INODE_VERSION(inode) == MINIX_V1)
		V1_minix_truncate(inode);
	else
		V2_minix_truncate(inode);
}

static struct super_block *minix_get_sb(struct file_system_type *fs_type,
	int flags, const char *dev_name, void *data)
{
	return get_sb_bdev(fs_type, flags, dev_name, data, minix_fill_super);
}

static struct file_system_type minix_fs_type = {
	.owner		= THIS_MODULE,
	.name		= "minix",
	.get_sb		= minix_get_sb,
	.kill_sb	= kill_block_super,
	.fs_flags	= FS_REQUIRES_DEV,
};

static int __init init_minix_fs(void)
{
	int err = init_inodecache();
	if (err)
		goto out1;
	err = register_filesystem(&minix_fs_type);
	if (err)
		goto out;
	return 0;
out:
	destroy_inodecache();
out1:
	return err;
}

static void __exit exit_minix_fs(void)
{
        unregister_filesystem(&minix_fs_type);
	destroy_inodecache();
}

module_init(init_minix_fs)
module_exit(exit_minix_fs)
MODULE_LICENSE("GPL");


text:
.. include:: includes/big_toc_css.rst

.. _unsupervised-learning:

Unsupervised learning
-----------------------

.. toctree::

    modules/mixture
    modules/manifold
    modules/clustering
    modules/biclustering
    modules/decomposition
    modules/covariance
    modules/outlier_detection
    modules/hmm
    modules/density
    modules/neural_networks

redpajama_set_name: RedPajamaGithub


text:
//
//  ========================================================================
//  Copyright (c) 1995-2015 Mort Bay Consulting Pty. Ltd.
//  ------------------------------------------------------------------------
//  All rights reserved. This program and the accompanying materials
//  are made available under the terms of the Eclipse Public License v1.0
//  and Apache License v2.0 which accompanies this distribution.
//
//      The Eclipse Public License is available at
//      http://www.eclipse.org/legal/epl-v10.html
//
//      The Apache License v2.0 is available at
//      http://www.opensource.org/licenses/apache2.0.php
//
//  You may elect to redistribute this code under either of these licenses.
//  ========================================================================
//

package org.eclipse.jetty.util.resource;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.security.Permission;

import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.URIUtil;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.log.Logger;

/* ------------------------------------------------------------ */
/** File Resource.
 *
 * Handle resources of implied or explicit file type.
 * This class can check for aliasing in the filesystem (eg case
 * insensitivity).  By default this is turned on, or it can be controlled
 * by calling the static method @see FileResource#setCheckAliases(boolean)
 *
 */
public class FileResource extends URLResource
{
    private static final Logger LOG = Log.getLogger(FileResource.class);
    private static boolean __checkAliases = true;

    /* ------------------------------------------------------------ */
    private File _file;
    private transient URL _alias=null;
    private transient boolean _aliasChecked=false;

    /* ------------------------------------------------------------------------------- */
    /** setCheckAliases.
     * @param checkAliases True of resource aliases are to be checked for (eg case insensitivity or 8.3 short names) and treated as not found.
     */
    public static void setCheckAliases(boolean checkAliases)
    {
        __checkAliases=checkAliases;
    }

    /* ------------------------------------------------------------------------------- */
    /** getCheckAliases.
     * @return True of resource aliases are to be checked for (eg case insensitivity or 8.3 short names) and treated as not found.
     */
    public static boolean getCheckAliases()
    {
        return __checkAliases;
    }

    /* -------------------------------------------------------- */
    public FileResource(URL url)
        throws IOException, URISyntaxException
    {
        super(url,null);

        try
        {
            // Try standard API to convert URL to file.
            _file =new File(new URI(url.toString()));
        }
        catch (URISyntaxException e)
        {
            throw e;
        }
        catch (Exception e)
        {
            LOG.ignore(e);
            try
            {
                // Assume that File.toURL produced unencoded chars. So try
                // encoding them.
                String file_url="file:"+URIUtil.encodePath(url.toString().substring(5));
                URI uri = new URI(file_url);
                if (uri.getAuthority()==null)
                    _file = new File(uri);
                else
                    _file = new File("//"+uri.getAuthority()+URIUtil.decodePath(url.getFile()));
            }
            catch (Exception e2)
            {
                LOG.ignore(e2);

                // Still can't get the file.  Doh! try good old hack!
                checkConnection();
                Permission perm = _connection.getPermission();
                _file = new File(perm==null?url.getFile():perm.getName());
            }
        }
        if (_file.isDirectory())
        {
            if (!_urlString.endsWith("/"))
                _urlString=_urlString+"/";
        }
        else
        {
            if (_urlString.endsWith("/"))
                _urlString=_urlString.substring(0,_urlString.length()-1);
        }

    }

    /* -------------------------------------------------------- */
    FileResource(URL url, URLConnection connection, File file)
    {
        super(url,connection);
        _file=file;
        if (_file.isDirectory() && !_urlString.endsWith("/"))
            _urlString=_urlString+"/";
    }

    /* -------------------------------------------------------- */
    @Override
    public Resource addPath(String path)
        throws IOException,MalformedURLException
    {
        URLResource r=null;
        String url=null;

        path = org.eclipse.jetty.util.URIUtil.canonicalPath(path);

        if ("/".equals(path))
            return this;
        else if (!isDirectory())
        {
            r=(FileResource)super.addPath(path);
            url=r._urlString;
        }
        else
        {
            if (path==null)
                throw new MalformedURLException();

            // treat all paths being added as relative
            String rel=path;
            if (path.startsWith("/"))
                rel = path.substring(1);

            url=URIUtil.addPaths(_urlString,URIUtil.encodePath(rel));
            r=(URLResource)Resource.newResource(url);
        }

        // Check for encoding aliases
        // The encoded path should be a suffix of the resource (give or take a directory / )
        String encoded=URIUtil.encodePath(path);
        int expected=r.toString().length()-encoded.length();
        int index = r._urlString.lastIndexOf(encoded, expected);
        if (expected!=index && ((expected-1)!=index || path.endsWith("/") || !r.isDirectory()))
        {
            if (r instanceof FileResource)
            {
                ((FileResource)r)._alias=((FileResource)r)._file.getCanonicalFile().toURI().toURL();
                ((FileResource)r)._aliasChecked=true;
            }
        }
        return r;
    }

    /* ------------------------------------------------------------ */
    @Override
    public URL getAlias()
    {
        if (__checkAliases && !_aliasChecked)
        {
            try
            {
                String abs=_file.getAbsolutePath();
                String can=_file.getCanonicalPath();

                if (abs.length()!=can.length() || !abs.equals(can))
                    _alias=Resource.toURL(new File(can));

                _aliasChecked=true;

                if (_alias!=null && LOG.isDebugEnabled())
                {
                    LOG.debug("ALIAS abs="+abs);
                    LOG.debug("ALIAS can="+can);
                }
            }
            catch(Exception e)
            {
                LOG.warn(Log.EXCEPTION,e);
                return getURL();
            }
        }
        return _alias;
    }

    /* -------------------------------------------------------- */
    /**
     * Returns true if the resource exists.
     */
    @Override
    public boolean exists()
    {
        return _file.exists();
    }

    /* -------------------------------------------------------- */
    /**
     * Returns the last modified time
     */
    @Override
    public long lastModified()
    {
        return _file.lastModified();
    }

    /* -------------------------------------------------------- */
    /**
     * Returns true if the respresenetd resource is a container/directory.
     */
    @Override
    public boolean isDirectory()
    {
        return _file.isDirectory();
    }

    /* --------------------------------------------------------- */
    /**
     * Return the length of the resource
     */
    @Override
    public long length()
    {
        return _file.length();
    }

    /* --------------------------------------------------------- */
    /**
     * Returns the name of the resource
     */
    @Override
    public String getName()
    {
        return _file.getAbsolutePath();
    }

    /* ------------------------------------------------------------ */
    /**
     * Returns an File representing the given resource or NULL if this
     * is not possible.
     */
    @Override
    public File getFile()
    {
        return _file;
    }

    /* --------------------------------------------------------- */
    /**
     * Returns an input stream to the resource
     */
    @Override
    public InputStream getInputStream() throws IOException
    {
        return new FileInputStream(_file);
    }

    /* --------------------------------------------------------- */
    /**
     * Returns an output stream to the resource
     */
    @Override
    public OutputStream getOutputStream()
        throws java.io.IOException, SecurityException
    {
        return new FileOutputStream(_file);
    }

    /* --------------------------------------------------------- */
    /**
     * Deletes the given resource
     */
    @Override
    public boolean delete()
        throws SecurityException
    {
        return _file.delete();
    }

    /* --------------------------------------------------------- */
    /**
     * Rename the given resource
     */
    @Override
    public boolean renameTo( Resource dest)
        throws SecurityException
    {
        if( dest instanceof FileResource)
            return _file.renameTo( ((FileResource)dest)._file);
        else
            return false;
    }

    /* --------------------------------------------------------- */
    /**
     * Returns a list of resources contained in the given resource
     */
    @Override
    public String[] list()
    {
        String[] list =_file.list();
        if (list==null)
            return null;
        for (int i=list.length;i-->0;)
        {
            if (new File(_file,list[i]).isDirectory() &&
                !list[i].endsWith("/"))
                list[i]+="/";
        }
        return list;
    }

    /* ------------------------------------------------------------ */
    /** Encode according to this resource type.
     * File URIs are encoded.
     * @param uri URI to encode.
     * @return The uri unchanged.
     */
    @Override
    public String encode(String uri)
    {
        return uri;
    }

    /* ------------------------------------------------------------ */
    /**
     * @param o
     * @return true of the object o is a {@link FileResource} pointing to the same file as this resource.
     */
    @Override
    public boolean equals( Object o)
    {
        if (this == o)
            return true;

        if (null == o || ! (o instanceof FileResource))
            return false;

        FileResource f=(FileResource)o;
        return f._file == _file || (null != _file && _file.equals(f._file));
    }

    /* ------------------------------------------------------------ */
    /**
     * @return the hashcode.
     */
    @Override
    public int hashCode()
    {
       return null == _file ? super.hashCode() : _file.hashCode();
    }

    /* ------------------------------------------------------------ */
    @Override
    public void copyTo(File destination)
        throws IOException
    {
        if (isDirectory())
        {
            IO.copyDir(getFile(),destination);
        }
        else
        {
            if (destination.exists())
                throw new IllegalArgumentException(destination+" exists");
            IO.copy(getFile(),destination);
        }
    }
}


text:
has("$lang.title") ? ' has-error' : '' }}'>
        {!! Form::label("{$lang}[title]", trans('blog::post.form.title')) !!}
        {!! Form::text("{$lang}[title]", old("$lang.title"), ['class' => 'form-control slugify', 'placeholder' => trans('blog::post.form.title')]) !!}
        {!! $errors->first("$lang.title", ':message') !!}

has("$lang.slug") ? ' has-error' : '' }}'>
       {!! Form::label("{$lang}[slug]", trans('blog::post.form.slug')) !!}
       {!! Form::text("{$lang}[slug]", old("$lang.slug"), ['class' => 'form-control slug', 'placeholder' => trans('blog::post.form.slug')]) !!}
       {!! $errors->first("$lang.slug", ':message') !!}

    <textarea class="ckeditor" name="{{$lang}}[content]" rows="10" cols="80"></textarea>


text:
[![Build Status](https://travis-ci.org/svenkatreddy/execution-time.svg?branch=master)](https://travis-ci.org/svenkatreddy/execution-time)

[![NPM](https://nodei.co/npm/execution-time.png?stars=true)](https://nodei.co/npm/execution-time/)

node.js utility to measure execution time in code

## Install
```shell
npm install execution-time --save
```

## Usage
```js
const perf = require('execution-time')();

// At beginning of your code
perf.start();

// At end of your code
const results = perf.stop();
console.log(results.time);  // in milliseconds
```

### Named performance measurer
```js
const perf = require('execution-time')();

// At beginning of your code, pass any name
perf.start('apiCall');

// At end of your code, pass the same name (anywhere in your flow)
const results = perf.stop('apiCall');
console.log(results.time);  // in milliseconds
console.log(results.preciseWords);  // in words

```

### If you dont care about results but just want to print results

Sample usage with debug
```js
const debug = require('debug')('your-module');
const perf = require('execution-time')(debug);

// At beginning of your code
perf.start();

// At end of your code
perf.stop();

```

also works with console.log/info/warn

```js
const perf = require('execution-time')(console.log);

// At beginning of your code
perf.start();

// At end of your code
perf.stop();

```


text:
* fixes typo and incorrect parameter name in interactivequandl method
* changes ASCIIString to String in timearray.jl
* remove readall in favor of readstring in api.jl

### 0.6.0

* support floor of julia 0.5.0

### 0.5.4

* add api_key to query args (thanks @bspeice)

### 0.5.3

* bug fix for empty query arguments (thanks @prcastro)

### 0.5.2

* support for quandl.com API v3 added (thanks @ViralBShah)
* fix to empty query bug

### 0.5.1

* change String and ASCIIString typed parameters to AbstractString

### 0.5.0

* first version with support for Julia 0.4 only
* precompilation support added

### 0.4.4

* last planned version with support for Julia 0.3

### 0.4.3

* adapted to semantic changes in the Requests package
* stubbed out tests in timearray and dataframe until JLD objects can be stored

### 0.4.2

* changed to using https from http to comply with API

### pre-0.4.2

Not currently documented.


text:
namespace Meta.ParsingAndPrinting
{
	/// <summary>
	/// Represents physical directions. Used by rooms to keep track of adjacent/adjoining rooms.
	/// </summary>
	public enum Direction { north, east, south, west, northeast, southeast, northwest, southwest, up, down };

	/// <summary>
	/// Indicates whether a given <see cref="Effect"/> changes the property it
	/// affects by setting it equal to a new value or by adding to it.
	/// </summary>
	public enum EffectType { equality, addition };

	/// <summary>
	/// Indicates whether a given <see cref="Effect"/> lasts indefinately or
	/// for a set number of turns.
	/// </summary>
	public enum EffectDuration { permanent, turns }

	public enum ClothingSlot { socks, shoes, tights, underpants, pants, skirt, undershirt, shirt, cincher, jacket, ring, bracelet, necklace, gloves, hat, glasses }
}


text:
package com.tle.web.api.schema.interfaces;

import com.tle.web.api.interfaces.BaseEntityResource;
import com.tle.web.api.interfaces.beans.PagingBean;
import com.tle.web.api.interfaces.beans.security.BaseEntitySecurityBean;
import com.tle.web.api.schema.interfaces.beans.SchemaBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.List;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

@Produces({"application/json"})
@Path("schema/")
@Api(value = "Schemas", description = "schema")
public interface SchemaResource extends BaseEntityResource<SchemaBean, BaseEntitySecurityBean> {
  @GET
  @Path("/acl")
  @ApiOperation(value = "List global schema acls")
  public BaseEntitySecurityBean getAcls(@Context UriInfo uriInfo);

  @PUT
  @Path("/acl")
  @ApiOperation(value = "Edit global schema acls")
  public Response editAcls(@Context UriInfo uriInfo, BaseEntitySecurityBean security);

  @GET
  @ApiOperation(value = "List all schemas")
  public PagingBean<SchemaBean> list(
      @Context UriInfo uriInfo,
      @ApiParam("Search name and description") @QueryParam("q") String q,
      @ApiParam("Privilege(s) to filter by") @QueryParam("privilege") List<String> privilege,
      @QueryParam("resumption") @ApiParam("Resumption token for paging") String resumptionToken,
      @QueryParam("length") @ApiParam("Number of results") @DefaultValue("10") int length,
      @QueryParam("full") @ApiParam("Return full entity (needs VIEW or EDIT privilege)")
          boolean full);

  @GET
  @Path("/{uuid}")
  @ApiOperation(value = "Get a schema")
  public SchemaBean get(
      @Context UriInfo uriInfo, @ApiParam("schema uuid") @PathParam("uuid") String uuid);

  @DELETE
  @Path("/{uuid}")
  @ApiOperation("Delete a schema")
  public Response delete(@Context UriInfo uriInfo, @PathParam("uuid") String uuid);

  @POST
  @ApiOperation("Create a new schema")
  public Response create(
      @Context UriInfo uriInfo,
      @ApiParam SchemaBean bean,
      @ApiParam(required = false) @QueryParam("file") String stagingUuid);

  @PUT
  @Path("/{uuid}")
  @ApiOperation(value = "Edit a schema")
  public Response edit(
      @Context UriInfo uriInfo,
      @PathParam("uuid") String uuid,
      @ApiParam SchemaBean bean,
      @ApiParam(required = false) @QueryParam("file") String stagingUuid,
      @ApiParam(required = false) @QueryParam("lock") String lockId,
      @ApiParam(required = false) @QueryParam("keeplocked") boolean keepLocked);

  @GET
  @Path("/{uuid}/lock")
  @ApiOperation("Read the lock for a schema")
  public Response getLock(@Context UriInfo uriInfo, @PathParam("uuid") String uuid);

  @POST
  @Path("/{uuid}/lock")
  @ApiOperation("Lock a schema")
  public Response lock(@Context UriInfo uriInfo, @PathParam("uuid") String uuid);

  @DELETE
  @Path("/{uuid}/lock")
  @ApiOperation("Unlock a schema")
  public Response unlock(@Context UriInfo uriInfo, @PathParam("uuid") String uuid);

  @GET
  @Path("/citation")
  @ApiOperation("Retrieve all available citations across all schemas")
  public List<String> citation(@Context UriInfo uriInfo);
}


text:
#define BOOST_TEST_MODULE test_error
#include "utility/test/boost_unit_test.hpp"

#include "flipsta/error.hpp"

#include <boost/exception/get_error_info.hpp>

BOOST_AUTO_TEST_SUITE(test_suite_error)

BOOST_AUTO_TEST_CASE (testError) {
    BOOST_CHECK_THROW (throw flipsta::Error(), std::exception);
    BOOST_CHECK_THROW (throw flipsta::Error(), boost::exception);

    typedef int State;
    try {
        // Throw error related to state 5.
        throw flipsta::Error() << flipsta::errorInfoState <State> (5);
    } catch (boost::exception & error) {
        State const * state = boost::get_error_info <
            flipsta::TagErrorInfoStateType <State>::type> (error);
        BOOST_CHECK (!!state);
        if (state) {
            BOOST_CHECK_EQUAL (*state, 5);
        }
    }
}

BOOST_AUTO_TEST_SUITE_END()


text:
namespace System.Web.UI.WebControls {

    public interface ICallbackContainer {

        /// <summary>
        /// Enables controls to obtain client-side script options that will cause
        /// (when invoked) a server callback to the form on a button click.
        /// </summary>
        string GetCallbackScript(IButtonControl buttonControl, string argument);
    }
}


text:
import React from 'react';
import {default as originalRules} from 'remarkable/lib/rules';

/*
 * This is a map of token types that open blocks to token types that close blocks,
 * always of the form `{name_open: name_close}`
 *
 * It's used to check whether a token type opens a block, as well as to quickly get the
 * close type name.
 *
 * The map is computed from the token types in Remarkable's list of rules, since it was faster
 * than copy-pasting all the open/close types :V
 */
let blockTokenOpenCloseMap = {};

const OPEN_TOKEN_RE = /(.*)_open$/;

for (let rule of Object.keys(originalRules)) {
  const match = rule.match(OPEN_TOKEN_RE);

  if (match) {
    const name = match[1];
    blockTokenOpenCloseMap[rule] = name + '_close';
  }
}

/*
 * These rules determine what the renderer should do for each token type.
 *
 * If rule's value is a string, it'll just make a tag with that string with the token's
 * content. If it's a function, it'll use that to get the JSX it should render for that token.
 *
 * TODO:
 *   - `code`: inline *and* block code snippets
 *     https://github.com/jonschlinkert/remarkable/blob/dev/lib/rules.js#L34-L39
 *   - `fence`: fenced code blocks
 *     https://github.com/jonschlinkert/remarkable/blob/dev/lib/rules.js#L45-L83
 *   - `htmlblock`, `htmltag`
 *     https://github.com/jonschlinkert/remarkable/blob/dev/lib/rules.js#L311-L316
 *   - footnotes, I guess? they look super complicated
 *     https://github.com/jonschlinkert/remarkable/blob/dev/lib/rules.js#L330
 */
const rules = {
  heading: (token, content) => {
    const tag = 'h' + token.hLevel;
    return React.createElement(tag, null, ...content);
  },

  link: (token, content) => {
    const title = token.title || null;

    return (

        {content}

    );
  },

  image: (token) => {
    const src = token.src || null;
    const title = token.title || null;
    const alt = token.alt || null;

    return (

    );
  },

  abbr: (token, content) => {
    const title = token.title || null;

    return (

        {content}

    );
  },

  paragraph: 'p',
  blockquote: 'blockquote',

  bullet_list: 'ul',
  ordered_list: 'ol',
  list_item: 'li',

  table: 'table',
  thead: 'thead',
  tbody: 'tbody',
  tr: 'tr',
  td: 'td',
  th: 'th',

  strong: 'strong',
  em: 'em',
  del: 'del',
  ins: 'ins',
  mark: 'mark',
  sup: 'sup',
  sub: 'sub',

  dl: 'dl',
  dt: 'dt',
  dd: 'dd',

  hr: 'hr',
  hardbreak: 'br',
  softbreak: 'br'
};

function renderRule(token, content) {
  const type = token.type.replace('_open', '');
  const rule = rules[type];

  if (typeof rule === 'string') {
    return React.createElement(rule, null, ...content);
  } else {
    return rule(token, content);
  }
}

/**
 * This is the core rendering function, which reduces over a list of tokens.
 *
 * It's really ugly and probably doesn't work in a lot of cases yet!
 */
function renderTokens([cur, ...rest], state, acc) {
  if (!cur) {
    // We're out of tokens! hurrah!
    return [acc, []];
  }

  if (cur.type in blockTokenOpenCloseMap) {
    // We got a new open block tag, so we render the full block and push it into the
    // accumulator
    state.stack.push(blockTokenOpenCloseMap[cur.type]);

    let parsed;
    [parsed, rest] = renderTokens(rest, state, []);
    const jsx = renderRule(cur, parsed);
    acc.push(jsx);

    state.stack.pop();

  } else if (cur.type === state.stack.slice(-1)[0]) {
    // The end of the current block. We return all of the tokens we've accumulated, which
    // represent the block.
    return [acc, rest];

  } else if (cur.type === 'inline') {
    // An "inline" token in Remarkable currently is just a list of tokens inside a block-level
    // element (e.g. a paragraph).
    let [parsed] = renderTokens(cur.children, state, []);
    acc.push(parsed);

  } else if (cur.type === 'text') {
    // A text token is just pushed in with the rest of the tokens
    acc.push(cur.content);

  } else {
    // Use a rule for a token if it exists
    if (rules[cur.type]) {
      acc.push(renderRule(cur));
    } else {
      throw new Error(`Encountered unhandled token type ${cur.type}`);
    }
  }

  return renderTokens(rest, state, acc);
}

function jsxRender(tokens/*, options, env*/) {
  let state = {
    stack: []
  };

  const [result] = renderTokens(tokens, state, []);

  return result;
}

// Remarkable's plugin architecture is just a specified way to monkey-patch a Remarkable instance
export default function(md) {
  md.renderer.render = jsxRender.bind(md.renderer);
}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System.Threading;
using Microsoft.CodeAnalysis.Host;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectTelemetry
{
    /// <summary>
    /// In process service responsible for listening to OOP telemetry notifications.
    /// </summary>
    internal interface IVisualStudioProjectTelemetryService
    {
        /// <summary>
        /// Called by a host to let this service know that it should start background
        /// analysis of the workspace to determine project telemetry.
        /// </summary>
        void Start(CancellationToken cancellationToken);
    }
}


text:
using namespace std;

class Token
{
public:
	Token(int line):lineNumber(line){}
	int getLineNumber(){return lineNumber;}
	virtual bool isNumber(){return false;}
	virtual bool isString(){return false;}
	virtual bool isIdentifier(){return false;}
	virtual int getNumber(){return 0;}
	virtual string getText(){return "";}
public:
	const static Token ENDOFFILE;
	const static string EOL;
private:
	int lineNumber;
};
const Token Token::ENDOFFILE(-1);
const string Token::EOL  = "\\n";

class NumToken:public Token
{
public:
	NumToken(int line,int n):Token(line),value(n){}
	bool isNumber(){return true;}
	int getNumber(){return value;};
	string getText()
	{
		stringstream ss;
		ss<<value;
		string str;
		ss>>str;
		return str;
	}
private:
	int value;
};

class IdToken:public Token
{
public:
	IdToken(int line,string id):Token(line),text(id){}
	bool isIdentifier(){return true;}
	string getText(){return text;}
private:
	string text;
};

class StrToken :public Token
{
public:
	StrToken(int line,string str):Token(line),literal(str){}
	bool isString(){return true;}
	string getText(){return literal;}
private:
	string literal;
};
#endif


text:
<?php

class System
{
    public  $objects = array();

    private $error_flag     = FALSE;
    private $error_msg      = "";

    public function __construct($init=TRUE) {
        if($init===TRUE) {
            $this->init();
        }
    }

    public function init() {
        return true;
    }

    public function install()
    {
        # Does the application need installing? Check if database exists, and can connect
        try {
            # Required fields
            $required = array(
                "db-host",
                "db-name",
                "db-username",
                "db-password",
                "table-prefix"
            );

            # Did all the required fields get passed in?
            if(count(array_intersect($required, array_keys($_REQUEST))) != count($required)) {
                throw new Exception("Not all required fields were submitted.");
            }

            # Verify the required unempty fields
            foreach($required as $field) {
                # Skip the fields that can be empty
                if($field == "table-prefix" or $field == "db-password") {
                    continue;
                }
                # Check if empty, throw error if they are.
                if(empty($_REQUEST[$field])) {
                    throw new Exception("Field <i>".lookupfieldname($field)."</i> cannot be empty.");
                }
            }

            # Try connecting to the database with the passed in credentials
            try {
                # Setup connection details
                $dsn = 'mysql:host='.$_REQUEST["db-host"].';dbname='.$_REQUEST["db-name"];
                $username = $_REQUEST["db-username"];
                $password = $_REQUEST["db-password"];
                $prefix = $_REQUEST["table-prefix"];

                # Make the connection
                $conn = new CDbConnection($dsn, $username, $password);
                $conn->active = true;
                $conn->setActive(true);
            }
            catch(Exception $e) {
                throw new Exception("Could not connect to database. Make sure you have created the database first. Details: ".$e->getMessage());
            }

            # Setup the database params for saving in the extended configuration
            $db_params = array(
                'components'=>array(
                    'db'=>array(
                        'connectionString'  => $dsn,
                        'emulatePrepare'    => true,
                        'username'          => $username,
                        'password'          => $password,
                        'charset'           => 'utf8',
                        'tablePrefix'       => $prefix,
                    ),
                ),
                'params'=>array(
                    'LOCALAPP_SERVER'           => $_SERVER["HTTP_HOST"],
                ),
            );

            # Make sure to only overwrite if explicitly asked to
            $config_ext = Yii::app()->basePath."\\config\\main-ext.php";
            if(is_file($config_ext)) {
                throw new Exception("Database configuration already exists. Delete this configuration in order to install this application.");
            }

            # Open up the file and write the new configuration.
            $handle = fopen($config_ext,"w");
            fwrite($handle,"<?php return ");
            fwrite($handle,var_export($db_params,true));
            fwrite($handle,"; ?>");
            fclose($handle);

            # Make read-only
            chmod($config_ext, 0060);
        }
        # Catch all the errors and output them as Flashes
        catch(Exception $e) {
            $this->set_error($e->getMessage());
            return false;
        }

        # If we made it to here, installation is a success!
        return true;
    }

    # Define a couple of local functions first
    # Function to change field name
    private function lookupfieldname($field) {
        switch($field) {
            case "db-host": return "Database Host";
            case "db-name": return "Database Name";
            case "db-username": return "Database Username";
            case "db-password": return "Database Password";
            case "table-prefix": return "Table Prefix";
            default: return $field;
        }
    }

    private function set_error($message) {
        $this->error_flag   = TRUE;
        $this->error_msg    = $message;
    }

    public function get_error() {
        return $this->error_msg;
    }

    public function has_error() {
        return ($this->error_flag === TRUE);
    }

}


text:
const domino = require('domino');

import {ɵBrowserDomAdapter as BrowserDomAdapter, ɵsetRootDomAdapter as setRootDomAdapter} from '@angular/platform-browser';

function _notImplemented(methodName: string) {
  return new Error('This method is not implemented in DominoAdapter: ' + methodName);
}

function setDomTypes() {
  // Make all Domino types available as types in the global env.
  Object.assign(global, domino.impl);
  (global as any)['KeyboardEvent'] = domino.impl.Event;
}

/**
 * Parses a document string to a Document object.
 */
export function parseDocument(html: string, url = '/') {
  let window = domino.createWindow(html, url);
  let doc = window.document;
  return doc;
}

/**
 * Serializes a document to string.
 */
export function serializeDocument(doc: Document): string {
  return (doc as any).serialize();
}

/**
 * DOM Adapter for the server platform based on https://github.com/fgnass/domino.
 */
export class DominoAdapter extends BrowserDomAdapter {
  static makeCurrent() {
    setDomTypes();
    setRootDomAdapter(new DominoAdapter());
  }

  private static defaultDoc: Document;

  logError(error: string) { console.error(error); }

  log(error: string) {
    // tslint:disable-next-line:no-console
    console.log(error);
  }

  logGroup(error: string) { console.error(error); }

  logGroupEnd() {}

  supportsDOMEvents(): boolean { return false; }
  supportsNativeShadowDOM(): boolean { return false; }

  contains(nodeA: any, nodeB: any): boolean {
    let inner = nodeB;
    while (inner) {
      if (inner === nodeA) return true;
      inner = inner.parent;
    }
    return false;
  }

  createHtmlDocument(): HTMLDocument {
    return parseDocument('<title>fakeTitle</title>');
  }

  getDefaultDocument(): Document {
    if (!DominoAdapter.defaultDoc) {
      DominoAdapter.defaultDoc = domino.createDocument();
    }
    return DominoAdapter.defaultDoc;
  }

  createShadowRoot(el: any, doc: Document = document): DocumentFragment {
    el.shadowRoot = doc.createDocumentFragment();
    el.shadowRoot.parent = el;
    return el.shadowRoot;
  }
  getShadowRoot(el: any): DocumentFragment { return el.shadowRoot; }

  isTextNode(node: any): boolean { return node.nodeType === DominoAdapter.defaultDoc.TEXT_NODE; }
  isCommentNode(node: any): boolean {
    return node.nodeType === DominoAdapter.defaultDoc.COMMENT_NODE;
  }
  isElementNode(node: any): boolean {
    return node ? node.nodeType === DominoAdapter.defaultDoc.ELEMENT_NODE : false;
  }
  hasShadowRoot(node: any): boolean { return node.shadowRoot != null; }
  isShadowRoot(node: any): boolean { return this.getShadowRoot(node) == node; }

  getProperty(el: Element, name: string): any {
    if (name === 'href') {
      // Domino tries tp resolve href-s which we do not want. Just return the
      // attribute value.
      return this.getAttribute(el, 'href');
    } else if (name === 'innerText') {
      // Domino does not support innerText. Just map it to textContent.
      return el.textContent;
    }
    return (<any>el)[name];
  }

  setProperty(el: Element, name: string, value: any) {
    if (name === 'href') {
      // Even though the server renderer reflects any properties to attributes
      // map 'href' to attribute just to handle when setProperty is directly called.
      this.setAttribute(el, 'href', value);
    } else if (name === 'innerText') {
      // Domino does not support innerText. Just map it to textContent.
      el.textContent = value;
    }
    (<any>el)[name] = value;
  }

  getGlobalEventTarget(doc: Document, target: string): EventTarget|null {
    if (target === 'window') {
      return doc.defaultView;
    }
    if (target === 'document') {
      return doc;
    }
    if (target === 'body') {
      return doc.body;
    }
    return null;
  }

  getBaseHref(doc: Document): string {
    const base = this.querySelector(doc.documentElement, 'base');
    let href = '';
    if (base) {
      href = this.getHref(base);
    }
    // TODO(alxhub): Need relative path logic from BrowserDomAdapter here?
    return href;
  }

  /** @internal */
  _readStyleAttribute(element: any): {[name: string]: string} {
    const styleMap: {[name: string]: string} = {};
    const styleAttribute = element.getAttribute('style');
    if (styleAttribute) {
      const styleList = styleAttribute.split(/;+/g);
      for (let i = 0; i < styleList.length; i++) {
        const style = styleList[i].trim();
        if (style.length > 0) {
          const colonIndex = style.indexOf(':');
          if (colonIndex === -1) {
            throw new Error(`Invalid CSS style: ${style}`);
          }
          const name = style.substr(0, colonIndex).trim();
          styleMap[name] = style.substr(colonIndex + 1).trim();
        }
      }
    }
    return styleMap;
  }
  /** @internal */
  _writeStyleAttribute(element: any, styleMap: {[name: string]: string}) {
    let styleAttrValue = '';
    for (const key in styleMap) {
      const newValue = styleMap[key];
      if (newValue) {
        styleAttrValue += key + ':' + styleMap[key] + ';';
      }
    }
    element.setAttribute('style', styleAttrValue);
  }
  setStyle(element: any, styleName: string, styleValue?: string|null) {
    styleName = styleName.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
    const styleMap = this._readStyleAttribute(element);
    styleMap[styleName] = styleValue || '';
    this._writeStyleAttribute(element, styleMap);
  }
  removeStyle(element: any, styleName: string) {
    // IE requires '' instead of null
    // see https://github.com/angular/angular/issues/7916
    this.setStyle(element, styleName, '');
  }
  getStyle(element: any, styleName: string): string {
    const styleMap = this._readStyleAttribute(element);
    return styleMap[styleName] || '';
  }
  hasStyle(element: any, styleName: string, styleValue?: string): boolean {
    const value = this.getStyle(element, styleName);
    return styleValue ? value == styleValue : value.length > 0;
  }

  dispatchEvent(el: Node, evt: any) {
    el.dispatchEvent(evt);

    // Dispatch the event to the window also.
    const doc = el.ownerDocument || el;
    const win = (doc as any).defaultView;
    if (win) {
      win.dispatchEvent(evt);
    }
  }

  getHistory(): History { throw _notImplemented('getHistory'); }
  getLocation(): Location { throw _notImplemented('getLocation'); }
  getUserAgent(): string { return 'Fake user agent'; }

  supportsWebAnimation(): boolean { return false; }
  performanceNow(): number { return Date.now(); }
  getAnimationPrefix(): string { return ''; }
  getTransitionEnd(): string { return 'transitionend'; }
  supportsAnimation(): boolean { return true; }

  getDistributedNodes(el: any): Node[] { throw _notImplemented('getDistributedNodes'); }

  supportsCookies(): boolean { return false; }
  getCookie(name: string): string { throw _notImplemented('getCookie'); }
  setCookie(name: string, value: string) { throw _notImplemented('setCookie'); }
}


text:
"use strict";

exports.__esModule = true;
exports.default = getContainer;

var _reactDom = _interopRequireDefault(require("react-dom"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function getContainer(container, defaultContainer) {
  if (container == null) return defaultContainer;
  container = typeof container === 'function' ? container() : container;
  return _reactDom.default.findDOMNode(container) || null;
}

module.exports = exports.default;