text:
/*	$NetBSD: filecore_vfsops.c,v 1.9.2.1 2004/05/29 09:05:15 tron Exp $	*/

/*-
 * Copyright (c) 1994 The Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	filecore_vfsops.c	1.1	1998/6/26
 */

/*-
 * Copyright (c) 1998 Andrew McMurry
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. All advertising materials mentioning features or use of this software
 *    must display the following acknowledgement:
 *	This product includes software developed by the University of
 *	California, Berkeley and its contributors.
 * 4. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	filecore_vfsops.c	1.1	1998/6/26
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: filecore_vfsops.c,v 1.9.2.1 2004/05/29 09:05:15 tron Exp $");

#if defined(_KERNEL_OPT)
#include "opt_compat_netbsd.h"
#endif

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/namei.h>
#include <sys/proc.h>
#include <sys/vnode.h>
#include <miscfs/specfs/specdev.h>
#include <sys/mount.h>
#include <sys/buf.h>
#include <sys/file.h>
#include <sys/device.h>
#include <sys/errno.h>
#include <sys/malloc.h>
#include <sys/pool.h>
#include <sys/conf.h>
#include <sys/sysctl.h>

#include <fs/filecorefs/filecore.h>
#include <fs/filecorefs/filecore_extern.h>
#include <fs/filecorefs/filecore_node.h>
#include <fs/filecorefs/filecore_mount.h>

MALLOC_DEFINE(M_FILECOREMNT, "filecore mount", "Filecore FS mount structures");

extern const struct vnodeopv_desc filecore_vnodeop_opv_desc;

const struct vnodeopv_desc * const filecore_vnodeopv_descs[] = {
	&filecore_vnodeop_opv_desc,
	NULL,
};

struct vfsops filecore_vfsops = {
	MOUNT_FILECORE,
	filecore_mount,
	filecore_start,
	filecore_unmount,
	filecore_root,
	filecore_quotactl,
	filecore_statfs,
	filecore_sync,
	filecore_vget,
	filecore_fhtovp,
	filecore_vptofh,
	filecore_init,
	filecore_reinit,
	filecore_done,
	NULL,
	NULL,				/* filecore_mountroot */
	filecore_checkexp,
	filecore_vnodeopv_descs,
};

struct genfs_ops filecore_genfsops = {
	genfs_size,
};

/*
 * Called by vfs_mountroot when iso is going to be mounted as root.
 *
 * Name is updated by mount(8) after booting.
 */

static int filecore_mountfs __P((struct vnode *devvp, struct mount *mp,
		struct proc *p, struct filecore_args *argp));

#if 0
int
filecore_mountroot()
{
	struct mount *mp;
	extern struct vnode *rootvp;
	struct proc *p = curproc;	/* XXX */
	int error;
	struct filecore_args args;

	if (root_device->dv_class != DV_DISK)
		return (ENODEV);

	/*
	 * Get vnodes for swapdev and rootdev.
	 */
	if (bdevvp(rootdev, &rootvp))
		panic("filecore_mountroot: can't setup rootvp");

	if ((error = vfs_rootmountalloc(MOUNT_FILECORE, "root_device", &mp)) != 0)
		return (error);

	args.flags = FILECOREMNT_ROOT;
	if ((error = filecore_mountfs(rootvp, mp, p, &args)) != 0) {
		mp->mnt_op->vfs_refcount--;
		vfs_unbusy(mp);
		free(mp, M_MOUNT);
		return (error);
	}
	simple_lock(&mountlist_slock);
	CIRCLEQ_INSERT_TAIL(&mountlist, mp, mnt_list);
	simple_unlock(&mountlist_slock);
	(void)filecore_statfs(mp, &mp->mnt_stat, p);
	vfs_unbusy(mp);
	return (0);
}
#endif

/*
 * VFS Operations.
 *
 * mount system call
 */
int
filecore_mount(mp, path, data, ndp, p)
	struct mount *mp;
	const char *path;
	void *data;
	struct nameidata *ndp;
	struct proc *p;
{
	struct vnode *devvp;
	struct filecore_args args;
	int error;
	struct filecore_mnt *fcmp = NULL;

	if (mp->mnt_flag & MNT_GETARGS) {
		fcmp = VFSTOFILECORE(mp);
		if (fcmp == NULL)
			return EIO;
		args.flags = fcmp->fc_mntflags;
		args.uid = fcmp->fc_uid;
		args.gid = fcmp->fc_gid;
		args.fspec = NULL;
		vfs_showexport(mp, &args.export, &fcmp->fc_export);
		return copyout(&args, data, sizeof(args));
	}
	error = copyin(data, (caddr_t)&args, sizeof (struct filecore_args));
	if (error)
		return (error);

	if ((mp->mnt_flag & MNT_RDONLY) == 0)
		return (EROFS);

	/*
	 * If updating, check whether changing from read-only to
	 * read/write; if there is no device name, that's all we do.
	 */
	if (mp->mnt_flag & MNT_UPDATE) {
		fcmp = VFSTOFILECORE(mp);
		if (args.fspec == 0)
			return (vfs_export(mp, &fcmp->fc_export, &args.export));
	}
	/*
	 * Not an update, or updating the name: look up the name
	 * and verify that it refers to a sensible block device.
	 */
	NDINIT(ndp, LOOKUP, FOLLOW, UIO_USERSPACE, args.fspec, p);
	if ((error = namei(ndp)) != 0)
		return (error);
	devvp = ndp->ni_vp;

	if (devvp->v_type != VBLK) {
		vrele(devvp);
		return ENOTBLK;
	}
	if (bdevsw_lookup(devvp->v_rdev) == NULL) {
		vrele(devvp);
		return ENXIO;
	}
	/*
	 * If mount by non-root, then verify that user has necessary
	 * permissions on the device.
	 */
	if (p->p_ucred->cr_uid != 0) {
		vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
		error = VOP_ACCESS(devvp, VREAD, p->p_ucred, p);
		VOP_UNLOCK(devvp, 0);
		if (error) {
			vrele(devvp);
			return (error);
		}
	}
	if ((mp->mnt_flag & MNT_UPDATE) == 0)
		error = filecore_mountfs(devvp, mp, p, &args);
	else {
		if (devvp != fcmp->fc_devvp)
			error = EINVAL;	/* needs translation */
		else
			vrele(devvp);
	}
	if (error) {
		vrele(devvp);
		return error;
	}
	fcmp = VFSTOFILECORE(mp);
	return set_statfs_info(path, UIO_USERSPACE, args.fspec, UIO_USERSPACE,
	    mp, p);
}

/*
 * Common code for mount and mountroot
 */
static int
filecore_mountfs(devvp, mp, p, argp)
	struct vnode *devvp;
	struct mount *mp;
	struct proc *p;
	struct filecore_args *argp;
{
	struct filecore_mnt *fcmp = (struct filecore_mnt *)0;
	struct buf *bp = NULL;
	dev_t dev = devvp->v_rdev;
	int error = EINVAL;
	int ronly = (mp->mnt_flag & MNT_RDONLY) != 0;
	extern struct vnode *rootvp;
	struct filecore_disc_record *fcdr;
	unsigned map;
	unsigned log2secsize;

	if (!ronly)
		return EROFS;

	/*
	 * Disallow multiple mounts of the same device.
	 * Disallow mounting of a device that is currently in use
	 * (except for root, which might share swap device for miniroot).
	 * Flush out any old buffers remaining from a previous use.
	 */
	if ((error = vfs_mountedon(devvp)) != 0)
		return error;
	if (vcount(devvp) > 1 && devvp != rootvp)
		return EBUSY;
	if ((error = vinvalbuf(devvp, V_SAVE, p->p_ucred, p, 0, 0)) != 0)
		return (error);

	error = VOP_OPEN(devvp, ronly ? FREAD : FREAD|FWRITE, FSCRED, p);
	if (error)
		return error;

	/* Read the filecore boot block to check FS validity and to find the map */
	error = bread(devvp, FILECORE_BOOTBLOCK_BLKN,
			   FILECORE_BOOTBLOCK_SIZE, NOCRED, &bp);
#ifdef FILECORE_DEBUG_BR
		printf("bread(%p, %x, %d, CRED, %p)=%d\n", devvp,
		       FILECORE_BOOTBLOCK_BLKN, FILECORE_BOOTBLOCK_SIZE,
		       bp, error);
#endif
	if (error != 0)
		goto out;
	if (filecore_bbchecksum(bp->b_data) != 0) {
		error = EINVAL;
		goto out;
	}
	fcdr = (struct filecore_disc_record *)(bp->b_data+FILECORE_BB_DISCREC);
	map = ((((8 << fcdr->log2secsize) - fcdr->zone_spare)
	    * (fcdr->nzones / 2) - 8 * FILECORE_DISCREC_SIZE)
	    << fcdr->log2bpmb) >> fcdr->log2secsize;
	log2secsize = fcdr->log2secsize;
	bp->b_flags |= B_AGE;
#ifdef FILECORE_DEBUG_BR
	printf("brelse(%p) vf1\n", bp);
#endif
	brelse(bp);
	bp = NULL;

	/* Read the bootblock in the map */
	error = bread(devvp, map, 1 << log2secsize, NOCRED, &bp);
#ifdef FILECORE_DEBUG_BR
		printf("bread(%p, %x, %d, CRED, %p)=%d\n", devvp,
		       map, 1 << log2secsize, bp, error);
#endif
	if (error != 0)
		goto out;
       	fcdr = (struct filecore_disc_record *)(bp->b_data + 4);
	fcmp = malloc(sizeof *fcmp, M_FILECOREMNT, M_WAITOK);
	memset((caddr_t)fcmp, 0, sizeof *fcmp);
	if (fcdr->log2bpmb > fcdr->log2secsize)
		fcmp->log2bsize = fcdr->log2bpmb;
	else	fcmp->log2bsize = fcdr->log2secsize;
	fcmp->blksize = 1 << fcmp->log2bsize;
	memcpy((caddr_t)&fcmp->drec, (caddr_t)fcdr, sizeof(*fcdr));
	fcmp->map = map;
	fcmp->idspz = ((8 << fcdr->log2secsize) - fcdr->zone_spare)
	    / (fcdr->idlen + 1);
	fcmp->mask = (1 << fcdr->idlen) - 1;
	if (fcdr->big_flag & 1) {
		fcmp->nblks = ((((u_int64_t)fcdr->disc_size_2) << 32)
		    + fcdr->disc_size) / fcmp->blksize;
	} else {
		fcmp->nblks=fcdr->disc_size / fcmp->blksize;
	}

	bp->b_flags |= B_AGE;
#ifdef FILECORE_DEBUG_BR
	printf("brelse(%p) vf2\n", bp);
#endif
	brelse(bp);
	bp = NULL;

	mp->mnt_data = fcmp;
	mp->mnt_stat.f_fsid.val[0] = (long)dev;
	mp->mnt_stat.f_fsid.val[1] = makefstype(MOUNT_FILECORE);
	mp->mnt_maxsymlinklen = 0;
	mp->mnt_flag |= MNT_LOCAL;
	mp->mnt_dev_bshift = fcdr->log2secsize;
	mp->mnt_fs_bshift = fcmp->log2bsize;

	fcmp->fc_mountp = mp;
	fcmp->fc_dev = dev;
	fcmp->fc_devvp = devvp;
	fcmp->fc_mntflags = argp->flags;
	if (argp->flags & FILECOREMNT_USEUID) {
		fcmp->fc_uid = p->p_cred->p_ruid;
		fcmp->fc_gid = p->p_cred->p_rgid;
	} else {
		fcmp->fc_uid = argp->uid;
		fcmp->fc_gid = argp->gid;
	}

	return 0;
out:
	if (bp) {
#ifdef FILECORE_DEBUG_BR
		printf("brelse(%p) vf3\n", bp);
#endif
		brelse(bp);
	}
	vn_lock(devvp, LK_EXCLUSIVE | LK_RETRY);
	(void)VOP_CLOSE(devvp, ronly ? FREAD : FREAD|FWRITE, NOCRED, p);
	VOP_UNLOCK(devvp, 0);
	if (fcmp) {
		free((caddr_t)fcmp, M_FILECOREMNT);
		mp->mnt_data = NULL;
	}
	return error;
}

/*
 * Make a filesystem operational.
 * Nothing to do at the moment.
 */
/* ARGSUSED */
int
filecore_start(mp, flags, p)
	struct mount *mp;
	int flags;
	struct proc *p;
{
	return 0;
}

/*
 * unmount system call
 */
int
filecore_unmount(mp, mntflags, p)
	struct mount *mp;
	int mntflags;
	struct proc *p;
{
	struct filecore_mnt *fcmp;
	int error, flags = 0;

	if (mntflags & MNT_FORCE)
		flags |= FORCECLOSE;
#if 0
	mntflushbuf(mp, 0);
	if (mntinvalbuf(mp))
		return EBUSY;
#endif
	if ((error = vflush(mp, NULLVP, flags)) != 0)
		return (error);

	fcmp = VFSTOFILECORE(mp);

	if (fcmp->fc_devvp->v_type != VBAD)
		fcmp->fc_devvp->v_specmountpoint = NULL;
	vn_lock(fcmp->fc_devvp, LK_EXCLUSIVE | LK_RETRY);
	error = VOP_CLOSE(fcmp->fc_devvp, FREAD, NOCRED, p);
	vput(fcmp->fc_devvp);
	free((caddr_t)fcmp, M_FILECOREMNT);
	mp->mnt_data = NULL;
	mp->mnt_flag &= ~MNT_LOCAL;
	return (error);
}

/*
 * Return root of a filesystem
 */
int
filecore_root(mp, vpp)
	struct mount *mp;
	struct vnode **vpp;
{
	struct vnode *nvp;
        int error;

        if ((error = VFS_VGET(mp, FILECORE_ROOTINO, &nvp)) != 0)
                return (error);
        *vpp = nvp;
        return (0);
}

/*
 * Do operations associated with quotas, not supported
 */
/* ARGSUSED */
int
filecore_quotactl(mp, cmd, uid, arg, p)
	struct mount *mp;
	int cmd;
	uid_t uid;
	caddr_t arg;
	struct proc *p;
{

	return (EOPNOTSUPP);
}

/*
 * Get file system statistics.
 */
int
filecore_statfs(mp, sbp, p)
	struct mount *mp;
	struct statfs *sbp;
	struct proc *p;
{
	struct filecore_mnt *fcmp = VFSTOFILECORE(mp);

#ifdef COMPAT_09
	sbp->f_type = 255;
#else
	sbp->f_type = 0;
#endif
	sbp->f_bsize = fcmp->blksize;
	sbp->f_iosize = sbp->f_bsize;	/* XXX */
	sbp->f_blocks = fcmp->nblks;
	sbp->f_bfree = 0; /* total free blocks */
	sbp->f_bavail = 0; /* blocks free for non superuser */
	sbp->f_files =  0; /* total files */
	sbp->f_ffree = 0; /* free file nodes */
	copy_statfs_info(sbp, mp);
	return 0;
}

/* ARGSUSED */
int
filecore_sync(mp, waitfor, cred, p)
	struct mount *mp;
	int waitfor;
	struct ucred *cred;
	struct proc *p;
{
	return (0);
}

/*
 * File handle to vnode
 *
 * Have to be really careful about stale file handles:
 * - check that the inode number is in range
 * - call iget() to get the locked inode
 * - check for an unallocated inode (i_mode == 0)
 * - check that the generation number matches
 */

struct ifid {
	ushort		ifid_len;
	ushort		ifid_pad;
	u_int32_t	ifid_ino;
};

/* ARGSUSED */
int
filecore_fhtovp(mp, fhp, vpp)
	struct mount *mp;
	struct fid *fhp;
	struct vnode **vpp;
{
	struct ifid *ifhp = (struct ifid *)fhp;
	struct vnode *nvp;
	struct filecore_node *ip;
	int error;

	if ((error = VFS_VGET(mp, ifhp->ifid_ino, &nvp)) != 0) {
		*vpp = NULLVP;
		return (error);
	}
        ip = VTOI(nvp);
        if (filecore_staleinode(ip)) {
                vput(nvp);
                *vpp = NULLVP;
                return (ESTALE);
        }
	*vpp = nvp;
	return (0);
}

/* ARGSUSED */
int
filecore_checkexp(mp, nam, exflagsp, credanonp)
	struct mount *mp;
	struct mbuf *nam;
	int *exflagsp;
	struct ucred **credanonp;
{
	struct filecore_mnt *fcmp = VFSTOFILECORE(mp);
	struct netcred *np;

	/*
	 * Get the export permission structure for this <mp, client> tuple.
	 */
	np = vfs_export_lookup(mp, &fcmp->fc_export, nam);
	if (np == NULL)
		return (EACCES);

	*exflagsp = np->netc_exflags;
	*credanonp = &np->netc_anon;
	return (0);
}

/* This looks complicated. Look at other vgets as well as the iso9660 one.
 *
 * The filecore inode number is made up of 1 byte directory entry index and
 * 3 bytes of the internal disc address of the directory. On a read-only
 * filesystem this is unique. For a read-write version we may not be able to
 * do vget, see msdosfs.
 */

int
filecore_vget(mp, ino, vpp)
	struct mount *mp;
	ino_t ino;
	struct vnode **vpp;
{
	struct filecore_mnt *fcmp;
	struct filecore_node *ip;
	struct buf *bp;
	struct vnode *vp;
	dev_t dev;
	int error;

	fcmp = VFSTOFILECORE(mp);
	dev = fcmp->fc_dev;
	if ((*vpp = filecore_ihashget(dev, ino)) != NULLVP)
		return (0);

	/* Allocate a new vnode/filecore_node. */
	if ((error = getnewvnode(VT_FILECORE, mp, filecore_vnodeop_p, &vp))
	    != 0) {
		*vpp = NULLVP;
		return (error);
	}
	ip = pool_get(&filecore_node_pool, PR_WAITOK);
	memset(ip, 0, sizeof(struct filecore_node));
	vp->v_data = ip;
	ip->i_vnode = vp;
	ip->i_dev = dev;
	ip->i_number = ino;
	ip->i_block = -1;
	ip->i_parent = -2;

	/*
	 * Put it onto its hash chain and lock it so that other requests for
	 * this inode will block if they arrive while we are sleeping waiting
	 * for old data structures to be purged or for the contents of the
	 * disk portion of this inode to be read.
	 */
	filecore_ihashins(ip);

	if (ino == FILECORE_ROOTINO) {
		/* Here we need to construct a root directory inode */
		memcpy((caddr_t)ip->i_dirent.name, (caddr_t)"root", 4);
		ip->i_dirent.load = 0;
		ip->i_dirent.exec = 0;
		ip->i_dirent.len = FILECORE_DIR_SIZE;
		ip->i_dirent.addr = fcmp->drec.root;
		ip->i_dirent.attr = FILECORE_ATTR_DIR | FILECORE_ATTR_READ;

	} else {
		/* Read in Data from Directory Entry */
		if ((error = filecore_bread(fcmp, ino & FILECORE_INO_MASK,
		    FILECORE_DIR_SIZE, NOCRED, &bp)) != 0) {
			vput(vp);
#ifdef FILECORE_DEBUG_BR
			printf("brelse(%p) vf4\n", bp);
#endif
			brelse(bp);
			*vpp = NULL;
			return (error);
		}

		memcpy((caddr_t)&ip->i_dirent,
		    (caddr_t)fcdirentry(bp->b_data, ino >> FILECORE_INO_INDEX),
		    sizeof(struct filecore_direntry));
#ifdef FILECORE_DEBUG_BR
		printf("brelse(%p) vf5\n", bp);
#endif
		brelse(bp);
	}

	ip->i_mnt = fcmp;
	ip->i_devvp = fcmp->fc_devvp;
	ip->i_diroff = 0;
	VREF(ip->i_devvp);

	/*
	 * Setup type
	 */
	vp->v_type = VREG;
	if (ip->i_dirent.attr & FILECORE_ATTR_DIR)
		vp->v_type = VDIR;

	/*
	 * Initialize the associated vnode
	 */
	switch (vp->v_type) {
	case VFIFO:
	case VCHR:
	case VBLK:
		/*
		 * Devices not supported.
		 */
		vput(vp);
		return (EOPNOTSUPP);
	case VLNK:
	case VNON:
	case VSOCK:
	case VDIR:
	case VBAD:
	case VREG:
		break;
	}

	if (ino == FILECORE_ROOTINO)
		vp->v_flag |= VROOT;

	/*
	 * XXX need generation number?
	 */

	genfs_node_init(vp, &filecore_genfsops);
	vp->v_size = ip->i_size;
	*vpp = vp;
	return (0);
}

/*
 * Vnode pointer to File handle
 */
/* ARGSUSED */
int
filecore_vptofh(vp, fhp)
	struct vnode *vp;
	struct fid *fhp;
{
	struct filecore_node *ip = VTOI(vp);
	struct ifid *ifhp;

	ifhp = (struct ifid *)fhp;
	ifhp->ifid_len = sizeof(struct ifid);
	ifhp->ifid_ino = ip->i_number;
       	return 0;
}

SYSCTL_SETUP(sysctl_vfs_filecore_setup, "sysctl vfs.filecore subtree setup")
{

	sysctl_createv(clog, 0, NULL, NULL,
		       CTLFLAG_PERMANENT,
		       CTLTYPE_NODE, "vfs", NULL,
		       NULL, 0, NULL, 0,
		       CTL_VFS, CTL_EOL);
	sysctl_createv(clog, 0, NULL, NULL,
		       CTLFLAG_PERMANENT,
		       CTLTYPE_NODE, "filecore",
		       SYSCTL_DESCR("Acorn FILECORE file system"),
		       NULL, 0, NULL, 0,
		       CTL_VFS, 19, CTL_EOL);
	/*
	 * XXX the "19" above could be dynamic, thereby eliminating
	 * one more instance of the "number to vfs" mapping problem,
	 * but "19" is the order as taken from sys/mount.h
	 */
}


text:
<?php

final class HarbormasterBuildActionController
  extends HarbormasterController {

  private $id;
  private $action;
  private $via;

  public function willProcessRequest(array $data) {
    $this->id = $data['id'];
    $this->action = $data['action'];
    $this->via = idx($data, 'via');
  }

  public function processRequest() {
    $request = $this->getRequest();
    $viewer = $request->getUser();
    $command = $this->action;

    $build = id(new HarbormasterBuildQuery())
      ->setViewer($viewer)
      ->withIDs(array($this->id))
      ->requireCapabilities(
        array(
          PhabricatorPolicyCapability::CAN_VIEW,
          PhabricatorPolicyCapability::CAN_EDIT,
        ))
      ->executeOne();
    if (!$build) {
      return new Aphront404Response();
    }

    switch ($command) {
      case HarbormasterBuildCommand::COMMAND_RESTART:
        $can_issue = $build->canRestartBuild();
        break;
      case HarbormasterBuildCommand::COMMAND_PAUSE:
        $can_issue = $build->canPauseBuild();
        break;
      case HarbormasterBuildCommand::COMMAND_RESUME:
        $can_issue = $build->canResumeBuild();
        break;
      case HarbormasterBuildCommand::COMMAND_ABORT:
        $can_issue = $build->canAbortBuild();
        break;
      default:
        return new Aphront400Response();
    }

    switch ($this->via) {
      case 'buildable':
        $return_uri = '/'.$build->getBuildable()->getMonogram();
        break;
      default:
        $return_uri = $this->getApplicationURI('/build/'.$build->getID().'/');
        break;
    }

    if ($request->isDialogFormPost() && $can_issue) {
      $editor = id(new HarbormasterBuildTransactionEditor())
        ->setActor($viewer)
        ->setContentSourceFromRequest($request)
        ->setContinueOnNoEffect(true)
        ->setContinueOnMissingFields(true);

      $xaction = id(new HarbormasterBuildTransaction())
        ->setTransactionType(HarbormasterBuildTransaction::TYPE_COMMAND)
        ->setNewValue($command);

      $editor->applyTransactions($build, array($xaction));

      return id(new AphrontRedirectResponse())->setURI($return_uri);
    }

    switch ($command) {
      case HarbormasterBuildCommand::COMMAND_RESTART:
        if ($can_issue) {
          $title = pht('Really restart build?');
          $body = pht(
            'Progress on this build will be discarded and the build will '.
            'restart. Side effects of the build will occur again. Really '.
            'restart build?');
          $submit = pht('Restart Build');
        } else {
          $title = pht('Unable to Restart Build');
          if ($build->isRestarting()) {
            $body = pht(
              'This build is already restarting. You can not reissue a '.
              'restart command to a restarting build.');
          } else {
            $body = pht('You can not restart this build.');
          }
        }
        break;
      case HarbormasterBuildCommand::COMMAND_ABORT:
        if ($can_issue) {
          $title = pht('Really abort build?');
          $body = pht(
            'Progress on this build will be discarded. Really '.
            'abort build?');
          $submit = pht('Abort Build');
        } else {
          $title = pht('Unable to Abort Build');
          $body = pht('You can not abort this build.');
        }
        break;
      case HarbormasterBuildCommand::COMMAND_PAUSE:
        if ($can_issue) {
          $title = pht('Really pause build?');
          $body = pht(
            'If you pause this build, work will halt once the current steps '.
            'complete. You can resume the build later.');
          $submit = pht('Pause Build');
        } else {
          $title = pht('Unable to Pause Build');
          if ($build->isComplete()) {
            $body = pht(
              'This build is already complete. You can not pause a completed '.
              'build.');
          } else if ($build->isPaused()) {
            $body = pht(
              'This build is already paused. You can not pause a build which '.
              'has already been paused.');
          } else if ($build->isPausing()) {
            $body = pht(
              'This build is already pausing. You can not reissue a pause '.
              'command to a pausing build.');
          } else {
            $body = pht(
              'This build can not be paused.');
          }
        }
        break;
      case HarbormasterBuildCommand::COMMAND_RESUME:
        if ($can_issue) {
          $title = pht('Really resume build?');
          $body = pht(
            'Work will continue on the build. Really resume?');
          $submit = pht('Resume Build');
        } else {
          $title = pht('Unable to Resume Build');
          if ($build->isResuming()) {
            $body = pht(
              'This build is already resuming. You can not reissue a resume '.
              'command to a resuming build.');
          } else if (!$build->isPaused()) {
            $body = pht(
              'This build is not paused. You can only resume a paused '.
              'build.');
          }
        }
        break;
    }

    $dialog = id(new AphrontDialogView())
      ->setUser($viewer)
      ->setTitle($title)
      ->appendChild($body)
      ->addCancelButton($return_uri);

    if ($can_issue) {
      $dialog->addSubmitButton($submit);
    }

    return id(new AphrontDialogResponse())->setDialog($dialog);
  }

}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>QueryResultIterable (Google App Engine API for Java)</title>
<meta name="date" content="2019-04-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.google.appengine.api.datastore

Interface QueryResultIterable<T>

Type Parameters:

T - the type of result returned by the query

All Superinterfaces:

java.lang.Iterable<T>

public interface QueryResultIterable<T>
extends java.lang.Iterable<T>

A class that produces QueryResultIterators.

Method Summary

All Methods Instance Methods Abstract Methods

Modifier and Type
Method and Description

QueryResultIterator<T>
iterator()

Methods inherited from interface java.lang.Iterable

forEach, spliterator

Method Detail

iterator

QueryResultIterator<T> iterator()

Specified by:

iterator in interface java.lang.Iterable<T>

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Java is a registered trademark of Oracle and/or its affiliates. Other names may be trademarks of their respective owners.

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
#region copyright
/// GladNet Copyright (C) 2014 Andrew Blakely
/// andrew.blakely@ymail.com
/// GitHub: HeIIoKitty
/// Unity3D: Glader
/// Please refer to the repo License file for licensing information
/// If this source code has been distributed without a copy of the original license file then this is an illegal copy and you should delete it
#endregion
using GladNet.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GladNet.Server.Logging
{
	/*public enum LoggerState
	{
		None,
		Debug,
		Error,
		Warn
	}*/

	public interface ILoggable
	{
		ILogger ClassLogger { get; }
	}
}


text:
"""Show how to customize the styling of the cluster view with CSS."""

from phy import IPlugin
from phy.cluster.supervisor import ClusterView

class ExampleClusterViewStylingPlugin(IPlugin):
    def attach_to_controller(self, controller):
        # We add a custom CSS style to the ClusterView.
        ClusterView._styles += """

            /* This CSS selector represents all rows for good clusters. */
            table tr[data-group='good'] {

                /* We change the text color. Many other CSS attributes can be changed,
                such as background-color, the font weight, etc. */
                color: red;
            }

        """


text:
/**
 * Created by zhiyuans on 9/21/2016.
 */
const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const ObjectId = Schema.Types.ObjectId;

const EVENT_TYPE = require('../constants/event-type');
const addressSchema = require('./address');

const eventSchema = new Schema({
  title: String,
  abstract: String,
  time: Date,
  types: [String],
  bigPost: String,
  smallPost: String,
  price: {
    beforeDiscount: [Number],
    afterDiscount: [Number]
  },
  address: addressSchema,
  phone: String,
  detail: String,
  comments: [ObjectId],
  isSelection: Boolean
});

module.exports = eventSchema;


text:
. /srv/venv/bin/activate
cd /srv/www/eventus/src/
git pull
python manage.py migrate
python manage.py collectstatic --no-input
service apache2 restart


text:
(function() {
	'use strict';

	angular.module('eliteApp').controller('MyTeamsCtrl', ['$state', 'myTeamsService', 'eliteApi', myTeamsCtrl]);

	function myTeamsCtrl($state, myTeamsService, eliteApi) {
		var vm = this;

		vm.myTeams = myTeamsService.getFollowedTeams();

		vm.goToTeam = function(team) {
			eliteApi.setLeagueId(team.leagueId);
			$state.go('app.team-detail', { id: team.id });
		};

	}

})();


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppWindowTranslucentStatusTheme" parent="AppTheme" />

    <style name="AppWindowTranslucentBackgroundTheme" parent="AppTheme">
        <item name="android:windowBackground">@null</item>
    </style>

</resources>


text:
//function addfromfolderck() {
//
//}

// pour gestion editeur d'images
function jInsertEditorText( text, editor ) {
    var newEl = new Element('span').set('html',text);
    var valeur = newEl.getChildren()[0].getAttribute('src');
    $(editor).value = valeur;
    addthumbnail(valeur, editor);
}

function addthumbnail(imgsrc, editor) {
    var slideimg = $(editor).getParent().getElement('img');
    var testurl = 'http';
    if (imgsrc.toLowerCase().indexOf(testurl.toLowerCase()) != -1) {
        slideimg.src = imgsrc;
    } else {
        slideimg.src = JURI+imgsrc;
    }

    slideimg.setProperty('width','64px');
    slideimg.setProperty('height','64px');
}

function addslideetd(imgname, imgcaption, imgthumb, imglink, imgtarget, imgvideo, slideselect, imgalignment, articleid, imgtime) {
    /*if (!articleid) articleid = '';
    if (!imgtime) imgtime = '';*/
    if (!imgname) imgname = '';
    //if (!imgthumb) imgthumb = '../modules/mod_slideshowetd/elements/etdslidesmanager/unknown.png';
    if (!imgcaption) imgcaption = '';
    imgcaption = imgcaption.replace(/\|dq\|/g,""");
    if (!imglink) imglink = '';
    //if (!imgvideo) imgvideo = '';
    if (!imgtarget || imgtarget == 'default') {
        imgtarget = '';
        imgtargetoption = '<option value="default" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_DEFAULT', 'default')+'</option><option value="_parent">'+Joomla.JText._('MOD_ETDSLIDESHOW_SAMEWINDOW', 'same window')+'</option><option value="_blank">'+Joomla.JText._('MOD_ETDSLIDESHOW_NEWWINDOW', 'new window')+'</option><option value="lightbox">'+Joomla.JText._('MOD_ETDSLIDESHOW_LIGHTBOX', 'in a Lightbox')+'</option>';
    } else {
        if (imgtarget == '_parent') {
            imgtargetoption = '<option value="default">'+Joomla.JText._('MOD_ETDSLIDESHOW_DEFAULT', 'default')+'</option><option value="_parent" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_SAMEWINDOW', 'same window')+'</option><option value="_blank">'+Joomla.JText._('MOD_ETDSLIDESHOW_NEWWINDOW', 'new window')+'</option>';
        } else if (imgtarget == 'lightbox') {
            imgtargetoption = '<option value="default">'+Joomla.JText._('MOD_ETDSLIDESHOW_DEFAULT', 'default')+'</option><option value="_parent">'+Joomla.JText._('MOD_ETDSLIDESHOW_SAMEWINDOW', 'same window')+'</option><option value="_blank">'+Joomla.JText._('MOD_ETDSLIDESHOW_NEWWINDOW', 'new window')+'</option>';
        } else {
            imgtargetoption = '<option value="default">'+Joomla.JText._('MOD_ETDSLIDESHOW_DEFAULT', 'default')+'</option><option value="_parent">'+Joomla.JText._('MOD_ETDSLIDESHOW_SAMEWINDOW', 'same window')+'</option><option value="_blank" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_NEWWINDOW', 'new window')+'</option>';
        }
    }
    /*if (!slideselect) {
        slideselect = '';
        slideselectoption = '<option value="image" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_IMAGE', 'Image')+'</option><option value="video">'+Joomla.JText._('MOD_ETDSLIDESHOW_VIDEO', 'Video')+'</option>';
    } else {
        if (slideselect == 'image') {
            slideselectoption = '<option value="image" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_IMAGE', 'Image')+'</option><option value="video">'+Joomla.JText._('MOD_ETDSLIDESHOW_VIDEO', 'Video')+'</option>';
        } else {
            slideselectoption = '<option value="image">'+Joomla.JText._('MOD_ETDSLIDESHOW_IMAGE', 'Image')+'</option><option value="video" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_VIDEO', 'Video')+'</option>';
        }
    }*/

    /*if (!imgalignment) {
        imgalignment = '';
        imgdataalignmentoption = '<option value="default" selected="selected">Default</option>'
        +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
        +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
        +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
        +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
        +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
        +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
        +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
        +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
        +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
    } else {
        if (imgalignment == 'topLeft') {
            imgdataalignmentoption = '<option value="default">Default</option>'
            +'<option value="topLeft" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        } else if (imgalignment == 'topCenter') {
            imgdataalignmentoption = '<option value="default">Default</option>'
            +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        } else if (imgalignment == 'topRight') {
            imgdataalignmentoption = '<option value="default">Default</option>'
            +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        } else if (imgalignment == 'centerLeft') {
            imgdataalignmentoption = '<option value="default">Default</option>'
            +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        } else if (imgalignment == 'center') {
            imgdataalignmentoption = '<option value="default">Default</option>'
            +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        } else if (imgalignment == 'centerRight') {
            imgdataalignmentoption = '<option value="default">Default</option>'
            +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        } else if (imgalignment == 'bottomLeft') {
            imgdataalignmentoption = '<option value="default">Default</option>'
            +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        } else if (imgalignment == 'bottomCenter') {
            imgdataalignmentoption = '<option value="default">Default</option>'
            +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        } else if (imgalignment == 'bottomRight') {
            imgdataalignmentoption = '<option value="default">Default</option>'
            +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight" selected="selected">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        } else {
            imgdataalignmentoption = '<option value="default" selected="selected">Default</option>'
            +'<option value="topLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPLEFT', 'top left')+'</option>'
            +'<option value="topCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPCENTER', 'top center')+'</option>'
            +'<option value="topRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_TOPRIGHT', 'top right')+'</option>'
            +'<option value="centerLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLELEFT', 'center left')+'</option>'
            +'<option value="center">'+Joomla.JText._('MOD_ETDSLIDESHOW_CENTER', 'center')+'</option>'
            +'<option value="centerRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_MIDDLERIGHT', 'center right')+'</option>'
            +'<option value="bottomLeft">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMLEFT', 'bottom left')+'</option>'
            +'<option value="bottomCenter">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMCENTER', 'bottom center')+'</option>'
            +'<option value="bottomRight">'+Joomla.JText._('MOD_ETDSLIDESHOW_BOTTOMRIGHT', 'bottom right')+'</option>';
        }
    }*/

    index = checkIndex(0);
    var etdslide = new Element('li', {
        'class': 'etdslide',
        'id': 'etdslide'+index
        });
    etdslide.set('html','

'+index+'

'
        + '<input name="etdslidedelete'+index+'" class="etdslidedelete" type="button" value="'+Joomla.JText._('MOD_ETDSLIDESHOW_REMOVE2', '')+'" onclick="javascript:removeslide(this.getParent().getParent());" />'
        + '

'

        + '<input name="etdslideimgname'+index+'" id="etdslideimgname'+index+'" class="etdslideimgname hasTip" title="Image::This is the main image for the slide, it will also be used to create the thumbnail" type="text" value="'+imgname+'" onchange="javascript:addthumbnail(this.value, this);" />'

        + ''+Joomla.JText._('MOD_ETDSLIDESHOW_SELECTIMAGE', 'select image')+'
'
        //+ '
'+Joomla.JText._('MOD_ETDSLIDESHOW_USETOSHOW', 'Display')+'<select class="etdslideselect">'+slideselectoption+'</select>'
        //+ '<input name="etdslideimgtime'+index+'" class="etdslideimgtime" type="text" value="'+imgtime+'" onchange="javascript:storesetwarning();" style="width:25px;" />ms'
        + '
'
        + '
'+Joomla.JText._('MOD_ETDSLIDESHOW_CAPTION', 'Caption')+'<input name="etdslidecaptiontext'+index+'" class="etdslidecaptiontext" type="text" value="'+imgcaption+'" onchange="javascript:storesetwarning();" />
'

        + '

'
        //+ ''+Joomla.JText._('MOD_ETDSLIDESHOW_IMAGEOPTIONS', 'Image options')+''
        + ''+Joomla.JText._('MOD_ETDSLIDESHOW_LINKOPTIONS', 'Link options')+''
        //+ ''+Joomla.JText._('MOD_ETDSLIDESHOW_VIDEOOPTIONS', 'Video options')+''
        //+ ''+Joomla.JText._('MOD_ETDSLIDESHOW_ARTICLEOPTIONS', 'Article options')+''
        + '

'
        /*+ '
'
        + '
'+Joomla.JText._('MOD_ETDSLIDESHOW_ALIGNEMENT_LABEL', 'Image alignment')+'<select name="etdslidedataalignmenttext'+index+'" class="etdslidedataalignmenttext" >'+imgdataalignmentoption+'</select>
'
        + '
'*/
        + '
'
        + '
'+Joomla.JText._('MOD_ETDSLIDESHOW_LINK', 'Link url')+'<input name="etdslidelinktext'+index+'" class="etdslidelinktext" type="text" value="'+imglink+'" onchange="javascript:storesetwarning();" />
'
        + '
'+Joomla.JText._('MOD_ETDSLIDESHOW_TARGET', 'Target')+'<select name="etdslidetargettext'+index+'" class="etdslidetargettext" >'+imgtargetoption+'</select>
'
        + '
'
        /*+ '
'
        + '
'+Joomla.JText._('MOD_ETDSLIDESHOW_VIDEOURL', 'Video url')+'<input name="etdslidevideotext'+index+'" class="etdslidevideotext" type="text" value="'+imgvideo+'" onchange="javascript:storesetwarning();" />
'
        + '
'
        + '
'
        + '
'+Joomla.JText._('MOD_ETDSLIDESHOW_ARTICLE_ID', 'Article ID')+'<input name="etdslidearticleid'+index+'" class="etdslidearticleid" type="text" value="'+articleid+'" onchange="javascript:storesetwarning();" />
'
        + '
'*/
        + '

'
        + '

');

    document.id('etdslideslist').adopt(etdslide);

    storeslideetd();
    makesortables();
    SqueezeBox.initialize({});
    SqueezeBox.assign(etdslide.getElement('a.modal'), {
        parse: 'rel'
    });
    new Fx.Accordion($('accordion'+index), '#etdslideaccordion'+index+' .etdslideaccordeonbutton', '#etdslideaccordion'+index+' .etdslideaccordeoncontent',
    {
        onActive: function(toggler, content) {
            toggler.addClass('open');
        },
        onBackground: function(toggler, content) {
            toggler.removeClass('open');
        }
    });
}

function checkIndex(i) {
    while ($('etdslide'+i)) i++;
    return i;
}

function removeslide(slide) {
    if (confirm(Joomla.JText._('MOD_ETDSLIDESHOW_REMOVE', 'Remove this slide')+' ?')) {
        slide.destroy();
        storeslideetd();
    }
}

function storesetwarning() {
// $('ckstoreslide').setStyle('background-color', 'red');
}

function storeremovewarning() {
// $('ckstoreslide').setStyle('background-color', 'white');
}

function storeslideetd() {
    var i = 0;
    var slides = new Array();
    document.id('etdslideslist').getElements('.etdslide').each(function(el) {
        slide = new Object();
        slide['imgname'] = el.getElement('.etdslideimgname').value;
        slide['imgcaption'] = el.getElement('.etdslidecaptiontext').value;
        slide['imgcaption'] = slide['imgcaption'].replace(/"/g,"|dq|");
        slide['imgthumb'] = el.getElement('img').src;
        slide['imglink'] = el.getElement('.etdslidelinktext').value;
        slide['imglink'] = slide['imglink'].replace(/"/g,"|dq|");
        slide['imgtarget'] = el.getElement('.etdslidetargettext').value;
        /*slide['imgalignment'] = el.getElement('.etdslidedataalignmenttext').value;
        slide['imgvideo'] = el.getElement('.etdslidevideotext').value;
        slide['slideselect'] = el.getElement('.etdslideselect').value;
        slide['slidearticleid'] = el.getElement('.etdslidearticleid').value;
        slide['imgtime'] = el.getElement('.etdslideimgtime').value;*/
        slides[i] = slide;
        i++;
    });

    slides = JSON.encode(slides);
    slides = slides.replace(/"/g,"|qq|");
    document.id('etdslides').value = slides;
    storeremovewarning();

}

function callslides() {
    // alert(document.id('etdslides').value);
    var slides = JSON.decode(document.id('etdslides').value.replace(/\|qq\|/g,"\""));
    if (slides) {
        slides.each(function(slide) {
            addslideetd(slide['imgname'],
                slide['imgcaption'],
                slide['imgthumb'],
                slide['imglink'],
                slide['imgtarget']/*,
                slide['imgvideo'],
                slide['slideselect'],
                slide['imgalignment'],
                slide['slidearticleid'],
                slide['imgtime']*/
                );
        });
        storeremovewarning();
    }
}

function makesortables() {
    var sb = new Sortables('etdslideslist', {
        /* set options */
        clone:true,
        revert: true,
        handle:'.etdslidehandle',
        /* initialization stuff here */
        initialize: function() {

        },
        /* once an item is selected */
        onStart: function(el) {
            el.setStyle('background','#add8e6');
        },
        /* when a drag is complete */
        onComplete: function(el) {
            el.setStyle('background','#fff');
            storesetwarning();
        },
        onSort: function(el, clone) {

        }
    });
}

window.addEvent('domready', function() {
    callslides();

    var script = document.createElement("script");
    script.setAttribute('type','text/javascript');
    script.text="Joomla.submitbutton = function(task){"
    +"storeslideetd();"
    +"if (task == 'module.cancel' || document.formvalidator.isValid(document.id('module-form'))) {	Joomla.submitform(task, document.getElementById('module-form'));"
    +"if (self != top) {"
    +"window.top.setTimeout('window.parent.SqueezeBox.close()', 1000);"
    +"}"
    +"} else {"
    +"alert('Formulaire invalide');"
    +"}}";
    document.body.appendChild(script);
});


text:
package game.tile.arena.entity.attack;

import java.util.LinkedList;

public class AttackList extends LinkedList<Attack> {

    public Attack getWrap(int index) {
        return get(getWrapIndex(index));
    }
    public int getWrapIndex(int index) {
        if (index < 0)
            return size();
        if (index > this.size()-1)
            return 0;
        return index;
    }
}


text:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using ILPathways.Business;
//using ILPathways.DAL;
using IOER.Library;
using ILPathways.Utilities;
using MyManager = Isle.BizServices.ContentServices;

namespace IOER.Content
{
    /// <summary>
    /// Show a document from the Document.Version table
    /// </summary>
    public partial class Show : BaseAppPage
    {
        const string thisClassName = "Content/Show.aspx";
        protected void Page_Load( object sender, EventArgs e )
        {

            lblMessage.Text = "";
            if ( !Page.IsPostBack )
            {
                this.InitializeForm();

            }
        }//

        /// <summary>
        /// Perform form initialization activities
        /// </summary>
        private void InitializeForm()
        {
            DocumentVersion entity = new DocumentVersion();
            MyManager mgr = new MyManager();

            //get actual requested document id
            string rowId = this.GetRequestKeyValue( "rid", "" );
            try
            {
                if ( rowId.Length != 36 )
                {
                    lblMessage.Text = "Invalid request";
                    return;
                }

                //get
                //need to add security checks. May need to go thru content (in case had privacy at content level, but not CS level) and/or content supplement
                //so may pass the attachment id??
                entity = mgr.DocumentVersionGet( rowId );

                if ( entity.HasValidRowId() )
                {
                    if ( entity.MimeType.Length > 0 )
                    {
                        Response.ContentType = entity.MimeType;
                    }
                    else
                    {
                        //guess, future, derive from file extension
                        Response.ContentType = "image/jpeg";
                    }
                    Response.BinaryWrite( entity.ResourceData );
                }
                else
                {
                    lblMessage.Text = "Invalid request";
                    //log condition
                    string queryString = HttpContext.Current.Request.QueryString.ToString();
                    LoggingHelper.LogError( string.Format( thisClassName + ".InitializeForm - DocumentVersion record not found for passed id of: {0} for url: {1}", rowId, queryString ), false );
                }

            }
            catch ( Exception ex )
            {
                //Action??		- display message and close form??
                LoggingHelper.LogError( ex, thisClassName + ".InitializeForm - Unexpected error encountered" );
                //can't show anything to the user
                lblMessage.Text = "Invalid request";
            }

        }	// End
    }
}


text:
"""Testing the functionality of the patches second moment computation."""
import itertools
from typing import Tuple, Union

from absl.testing import absltest
from absl.testing import parameterized
import jax
from jax import lax
import jax.numpy as jnp
import kfac_jax
import numpy as np

psm = kfac_jax.patches_second_moment
utils = kfac_jax.utils

class TestPatchesMoments(parameterized.TestCase):
  """Test class for the patches second moment functions."""

  def assertAllClose(
      self,
      x: utils.PyTree,
      y: utils.PyTree,
      check_dtypes: bool = True,
      atol: float = 1e-6,
      rtol: float = 1e-6,
  ):
    """Asserts that the two PyTrees are close up to the provided tolerances."""
    x_v, x_tree = jax.tree_util.tree_flatten(x)
    y_v, y_tree = jax.tree_util.tree_flatten(y)
    self.assertEqual(x_tree, y_tree)
    for xi, yi in zip(x_v, y_v):
      self.assertEqual(xi.shape, yi.shape)
      if check_dtypes:
        self.assertEqual(xi.dtype, yi.dtype)
      np.testing.assert_allclose(xi, yi, rtol=rtol, atol=atol)

  @parameterized.parameters(list(itertools.product(
      [8, 16],  # h
      [(1, 2), (3, 3), (4, 5)],  # kernel_shape
      [(1, 1), (1, 2), (1, 3),
       (2, 2), (2, 3), (3, 3)],  # strides
      ["VALID", "SAME"],  # padding
  )) + [
      (9, (2, 2), (2, 2), ((0, 0), (2, 3))),  # custom padding
      (8, (2, 2), (1, 3), ((0, 1), (2, 3))),  # custom padding
  ])
  def test_num_locations(
      self,
      h_and_w: int,
      kernel_shape: Tuple[int, int],
      strides: Tuple[int, int],
      padding: Union[str, Tuple[Tuple[int, int], Tuple[int, int]]],
  ):
    """Tests calculation of the number of convolutional locations."""
    spatial_shape = (h_and_w, h_and_w)
    patches = lax.conv_general_dilated_patches(
        jnp.zeros((1,) + spatial_shape + (3,)),
        filter_shape=kernel_shape,
        window_strides=strides,
        padding=padding,
        dimension_numbers=("NHWC", "IOHW", "NHWC"),
    )
    num_locations = patches.size // patches.shape[-1]
    num_location_fast = psm.num_conv_locations(
        spatial_shape,
        kernel_spatial_shape=kernel_shape,
        spatial_strides=strides,
        spatial_padding=padding)
    self.assertEqual(num_locations, num_location_fast)

  @parameterized.parameters(list(itertools.product(
      [3],  # c
      [8, 16],  # h
      [(1, 2), (3, 3), (4, 5)],  # kernel_shape
      [(1, 1), (1, 2), (1, 3),
       (2, 2), (2, 3), (3, 3)],  # strides
      ["VALID", "SAME"],  # padding
      ["NHWC", "NCHW"],  # data_format
      [False, True],  # per_channel
  )) + [
      (3, 9, (2, 2), (2, 2), ((0, 0), (2, 3)), "NHWC", False),  # custom padding
      (3, 9, (2, 2), (2, 2), ((0, 0), (2, 3)), "NHWC", True),  # custom padding
      (3, 8, (2, 2), (1, 3), ((0, 1), (2, 3)), "NHWC", False),  # custom padding
      (3, 8, (2, 2), (1, 3), ((0, 1), (2, 3)), "NHWC", True),  # custom padding
  ])
  def test_patches_moments_2d(
      self,
      c: int,
      h_and_w: int,
      kernel_spatial_shape: Tuple[int, int],
      strides: Tuple[int, int],
      padding: Union[str, Tuple[Tuple[int, int], Tuple[int, int]]],
      data_format: str,
      per_channel: bool,
  ):
    """Tests the patches second moment calculation for 2D convolution."""
    rng = jax.random.PRNGKey(1214321)
    n = 5
    axis = data_format.index("C")

    if data_format == "NHWC":
      shape = (n, h_and_w, h_and_w, c)
    else:
      shape = (n, c, h_and_w, h_and_w)
    w_shape = (*kernel_spatial_shape, c, c + 1)
    feature_group_count = c if per_channel else 1

    num_locations = psm.num_conv_locations(
        (h_and_w, h_and_w),
        kernel_spatial_shape=kernel_spatial_shape,
        spatial_strides=strides,
        spatial_padding=padding)
    normalizer = n * num_locations

    ones_inputs = jnp.ones(shape)
    key, rng = jax.random.split(rng)
    random_inputs = jax.random.normal(key, shape)
    random_inputs = jnp.asarray(random_inputs.astype(ones_inputs.dtype))
    random_w = jax.random.uniform(rng, w_shape, dtype=ones_inputs.dtype)
    random_out = jax.lax.conv_general_dilated(
        lhs=random_inputs,
        rhs=random_w,
        window_strides=strides,
        padding=padding,
        dimension_numbers=(data_format, "HWIO", data_format)
    )
    random_out = jnp.sum(jnp.square(random_out), axis=axis)
    weighting_array = 1.0 + jax.random.uniform(rng, shape=random_out.shape)

    for inputs in (ones_inputs, random_inputs):
      matrix, vector = psm.patches_moments_explicit(
          inputs,
          kernel_spatial_shape=kernel_spatial_shape,
          strides=strides,
          padding=padding,
          data_format=data_format,
          feature_group_count=feature_group_count,
          unroll_loop=True,
          precision=jax.lax.Precision.HIGHEST,
          weighting_array=weighting_array,
      )
      matrix_fast, vector_fast = psm.patches_moments(
          inputs,
          kernel_spatial_shape=kernel_spatial_shape,
          strides=strides,
          padding=padding,
          data_format=data_format,
          feature_group_count=feature_group_count,
          precision=jax.lax.Precision.HIGHEST,
          weighting_array=weighting_array,
      )

      # For accurate results we compare the mean over the batch and locations
      matrix, vector, matrix_fast, vector_fast = jax.tree_util.tree_map(
          lambda x: x / normalizer, (matrix, vector, matrix_fast, vector_fast)
          # pylint: disable=cell-var-from-loop
      )
      self.assertAllClose(matrix, matrix_fast)
      self.assertAllClose(vector, vector_fast)

if __name__ == "__main__":
  absltest.main()


text:
package transactionpool

import (
	"github.com/NebulousLabs/Sia/modules"
	"github.com/NebulousLabs/Sia/types"

	"github.com/NebulousLabs/bolt"
)

// purge removes all transactions from the transaction pool.
func (tp *TransactionPool) purge() {
	tp.knownObjects = make(map[ObjectID]TransactionSetID)
	tp.transactionSets = make(map[TransactionSetID][]types.Transaction)
	tp.transactionSetDiffs = make(map[TransactionSetID]modules.ConsensusChange)
	tp.transactionListSize = 0
}

// ProcessConsensusChange gets called to inform the transaction pool of changes
// to the consensus set.
func (tp *TransactionPool) ProcessConsensusChange(cc modules.ConsensusChange) {
	tp.mu.Lock()

	// Update the database of confirmed transactions.
	err := tp.db.Update(func(tx *bolt.Tx) error {
		for _, block := range cc.RevertedBlocks {
			for _, txn := range block.Transactions {
				err := tp.deleteTransaction(tx, txn.ID())
				if err != nil {
					return err
				}
			}
		}
		for _, block := range cc.AppliedBlocks {
			for _, txn := range block.Transactions {
				err := tp.addTransaction(tx, txn.ID())
				if err != nil {
					return err
				}
			}
		}
		return tp.putRecentConsensusChange(tx, cc.ID)
	})
	if err != nil {
		// TODO: Handle error
	}

	// Scan the applied blocks for transactions that got accepted. This will
	// help to determine which transactions to remove from the transaction
	// pool. Having this list enables both efficiency improvements and helps to
	// clean out transactions with no dependencies, such as arbitrary data
	// transactions from the host.
	txids := make(map[types.TransactionID]struct{})
	for _, block := range cc.AppliedBlocks {
		for _, txn := range block.Transactions {
			txids[txn.ID()] = struct{}{}
		}
	}

	// TODO: Right now, transactions that were reverted to not get saved and
	// retried, because some transactions such as storage proofs might be
	// illegal, and there's no good way to preserve dependencies when illegal
	// transactions are suddenly involved.
	//
	// One potential solution is to have modules manually do resubmission if
	// something goes wrong. Another is to have the transaction pool remember
	// recent transaction sets on the off chance that they become valid again
	// due to a reorg.
	//
	// Another option is to scan through the blocks transactions one at a time
	// check if they are valid. If so, lump them in a set with the next guy.
	// When they stop being valid, you've found a guy to throw away. It's n^2
	// in the number of transactions in the block.

	// Save all of the current unconfirmed transaction sets into a list.
	var unconfirmedSets [][]types.Transaction
	for _, tSet := range tp.transactionSets {
		// Compile a new transaction set the removes all transactions duplicated
		// in the block. Though mostly handled by the dependency manager in the
		// transaction pool, this should both improve efficiency and will strip
		// out duplicate transactions with no dependencies (arbitrary data only
		// transactions)
		var newTSet []types.Transaction
		for _, txn := range tSet {
			_, exists := txids[txn.ID()]
			if !exists {
				newTSet = append(newTSet, txn)
			}
		}
		unconfirmedSets = append(unconfirmedSets, newTSet)
	}

	// Purge the transaction pool. Some of the transactions sets may be invalid
	// after the consensus change.
	tp.purge()

	// Add all of the unconfirmed transaction sets back to the transaction
	// pool. The ones that are invalid will throw an error and will not be
	// re-added.
	//
	// Accepting a transaction set requires locking the consensus set (to check
	// validity). But, ProcessConsensusChange is only called when the consensus
	// set is already locked, causing a deadlock problem. Therefore,
	// transactions are readded to the pool in a goroutine, so that this
	// function can finish and consensus can unlock. The tpool lock is held
	// however until the goroutine completes.
	//
	// Which means that no other modules can require a tpool lock when
	// processing consensus changes. Overall, the locking is pretty fragile and
	// more rules need to be put in place.
	for _, set := range unconfirmedSets {
		tp.acceptTransactionSet(set, cc.TryTransactionSet) // Error is not checked.
	}

	// Inform subscribers that an update has executed.
	tp.mu.Demote()
	tp.updateSubscribersTransactions()
	tp.mu.DemotedUnlock()
}

// PurgeTransactionPool deletes all transactions from the transaction pool.
func (tp *TransactionPool) PurgeTransactionPool() {
	tp.mu.Lock()
	tp.purge()
	tp.mu.Unlock()
}


text: {{pane.title}}


text:
An HTTP Json interface for a dedicated server of the game ARK: Survival Evolved. It makes it easy to access all ARK profile data like character and tribe profiles. It can be used to create a website in a language like PHP or just to create a tool to keep an eye on your server.
All documentation can be found on the repository wiki pages.

Third-party Sources

- NewtonSoft.Json
- ArkData


text:
classdef (Abstract) Base

    properties
        x@double;
        y@double;
        angle@double; % TS added this property 20191209
        length@double
        width@double;
        height@double;
        depth@double;
        inputsId@char;
        proportion@double;
        inProduction@logical;
    end

    methods (Static = true)

        function cage = fromXMLDOM(cageDOM)
            type = char(cageDOM.getElementsByTagName('cageType').item(0).getTextContent);

            if isequal(type, 'CIRCULAR')
                cage = Depomod.Layout.Cage.Circle;
            elseif isequal(type, 'SQUARE') || isequal(type, 'RECTANGULAR')
                cage = Depomod.Layout.Cage.Square;
            end

            cage.x            = str2double(cageDOM.getElementsByTagName('xCoordinate').item(0).getTextContent);
            cage.y            = str2double(cageDOM.getElementsByTagName('yCoordinate').item(0).getTextContent);
            cage.length       = str2double(cageDOM.getElementsByTagName('length').item(0).getTextContent);
            cage.width        = str2double(cageDOM.getElementsByTagName('width').item(0).getTextContent);
            cage.height       = str2double(cageDOM.getElementsByTagName('hieght').item(0).getTextContent);
            cage.depth        = str2double(cageDOM.getElementsByTagName('depth').item(0).getTextContent);
            cage.inputsId     = char(cageDOM.getElementsByTagName('inputsId').item(0).getTextContent);
            cage.proportion   = str2double(cageDOM.getElementsByTagName('proportion').item(0).getTextContent);
            cage.inProduction = logical(eval(char(cageDOM.getElementsByTagName('inProduction').item(0).getTextContent)));
        end

        function cage = fromCSVRow(string)
            columns = strsplit(string, ',');

            if isequal(columns{4}, 'circle')
                cage = Depomod.Layout.Cage.Circle;
            elseif isequal(columns{4}, 'square')
                cage = Depomod.Layout.Cage.Square;
            end

            cage.x       = str2double(columns{1});
            cage.y       = str2double(columns{2});
            cage.angle   = str2double(columns{3}); % TS changed this 20191209
            cage.length  = str2double(columns{6});
            cage.width   = str2double(columns{5});
            cage.height  = str2double(columns{7});

            % ensure identical dimensions if circular.
            if cage.width ~= cage.length
                val = max([cage.width, cage.length]);

                cage.length  = val;
                cage.width   = val;
            end
        end

    end

    methods
        function s = shape(C)
            s = 'square';

            if isequal(class(C), 'Depomod.Layout.Cage.Circle')
                s = 'circle';
            end
        end

        function bool = isCircle(C)
            bool = isequal(C.shape, 'circle');
        end

        function bool = isSquare(C)
            bool = isequal(C.shape, 'square');
        end

        function bool = isRectangular(C)
            bool = isequal(C.shape, 'square');
        end

    end

end


text:
import bcrypt from 'bcrypt-nodejs';

export default (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      autoIncrement: true,
      primaryKey: true
    },
    firstname: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        len: {
          args: [2, 40],
          msg: 'First Name length should range between 2 - 40 characters'
        }
      },
      set(value) {
        this.setDataValue('firstname', value.trim());
      }
    },
    lastname: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        len: {
          args: [2, 40],
          msg: 'Last Name length should range between 2 - 40 characters'
        }
      },
      set(value) {
        this.setDataValue('lastname', value.trim());
      }
    },
    username: {
      type: DataTypes.STRING,
      allowNull: false,
      unique: {
        args: true,
        msg: 'Oops. There is an existing account with this username.'
      },
      validate: {
        len: {
          args: [6, 40],
          msg: 'Username length should range between 6 - 40 characters'
        }
      },
      set(value) {
        this.setDataValue('username', value.trim());
      }
    },
    email: {
      allowNull: false,
      type: DataTypes.STRING,
      unique: {
        args: true,
        msg: 'Oops. There is an existing account with this email.'
      },
      validate: {
        isEmail: {
          args: true,
          msg: 'The email you entered is invalid.'
        },
        max: {
          args: 254,
          msg: 'The email you entered is invalid  and longer \
than 254 characters.'
        }
      },
      set(value) {
        this.setDataValue('email', value.trim().toLowerCase());
      }
    },
    roleId: {
      allowNull: false,
      defaultValue: 2,
      type: DataTypes.INTEGER,
      validate: {
        notEmpty: {
          msg: 'Role id is required'
        }
      }
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false,
      validate: {
        isPassword(value) {
          if (value.length < 6) {
            throw new Error('Your password cannot be less than 6 characters');
          }
        }
      }
    }
  }, {
    classMethods: {
      associate: (models) => {
        // associations can be defined here
        User.belongsTo(models.Role, { foreignKey: 'roleId' });
        User.hasMany(models.Document, {
          foreignKey: 'creatorId',
          onDelete: 'CASCADE',
          hooks: true
        });
      }
    },

    instanceMethods: {
      passwordMatch(password) {
        return bcrypt.compareSync(password, this.password);
      },

      hashPassword() {
        this.password = bcrypt.hashSync(this.password, bcrypt.genSaltSync());
      }
    },

    hooks: {
      beforeCreate: (user) => {
        user.hashPassword();
      },
      beforeUpdate: (user) => {
        if (user.new_password) {
          user.hashPassword();
        }
      }
    }
  });
  return User;
};


text:
import webdriver from 'selenium-webdriver';
import expect from 'expect';

function checkValue(value, done) {
  this.driver.findElement(webdriver.By.className('counter'))
    .getText().then((val) => {
      expect(val).toBe(value + '');
      done();
    });
}

export function hasValue(value) {
  it('should contain text "Clicked: ' + value + ' times"', function (done) {
    checkValue.call(this, value, done);
  });
}
export function hasValueWait(value, timeout) {
  it('should contain text "Clicked: ' + value + ' times"', function (done) {
    /*
    this.driver.wait(() =>
      this.driver.findElements(webdriver.By.className('counter'))
        .then((elems) => elems.length === 1)
      , 4000, 'element with such value doesn\'t exist')
      .then(() => done());
      */
    setTimeout(() => {
      checkValue.call(this, value, done);
    }, timeout);
  });
}

export function hasClickedButton(className, idx, newValue, timeout) {
  it('should click button with idx=' + idx, function (done) {
    this.driver.findElement(
        webdriver.By.xpath(
          '//div[' + (className ? '@class="' + className + '" and ' : '') +
          './/span[text()="Clicked: "] and .//span[text()=" times"]]//button[' + idx + ']'
        ))
      .click().then(() => done());
  });
  hasValueWait(newValue, timeout);
}

export function clickButtons(initialValue, className) {
  [
    [1, initialValue + 1],
    [4, initialValue + 2, 2000],
    [2, initialValue + 1]
  ].forEach((params) => {
    describe(' -> ' + params[1], function () {
      hasClickedButton(className, ...params);
    });
  });
}

export function hasTitle(value) {
  it('should have title ' + value, function (done) {
    this.driver.getTitle().then((title) => {
      expect(title).toBe(value);
      done();
    });
  });
}


text:
package godo

import (
	"context"
	"fmt"
	"net/http"
)

const imageBasePath = "v2/images"

// ImagesService is an interface for interfacing with the images
// endpoints of the DigitalOcean API
// See: https://developers.digitalocean.com/documentation/v2#images
type ImagesService interface {
	List(context.Context, *ListOptions) ([]Image, *Response, error)
	ListDistribution(ctx context.Context, opt *ListOptions) ([]Image, *Response, error)
	ListApplication(ctx context.Context, opt *ListOptions) ([]Image, *Response, error)
	ListUser(ctx context.Context, opt *ListOptions) ([]Image, *Response, error)
	ListByTag(ctx context.Context, tag string, opt *ListOptions) ([]Image, *Response, error)
	GetByID(context.Context, int) (*Image, *Response, error)
	GetBySlug(context.Context, string) (*Image, *Response, error)
	Create(context.Context, *CustomImageCreateRequest) (*Image, *Response, error)
	Update(context.Context, int, *ImageUpdateRequest) (*Image, *Response, error)
	Delete(context.Context, int) (*Response, error)
}

// ImagesServiceOp handles communication with the image related methods of the
// DigitalOcean API.
type ImagesServiceOp struct {
	client *Client
}

var _ ImagesService = &ImagesServiceOp{}

// Image represents a DigitalOcean Image
type Image struct {
	ID            int      `json:"id,float64,omitempty"`
	Name          string   `json:"name,omitempty"`
	Type          string   `json:"type,omitempty"`
	Distribution  string   `json:"distribution,omitempty"`
	Slug          string   `json:"slug,omitempty"`
	Public        bool     `json:"public,omitempty"`
	Regions       []string `json:"regions,omitempty"`
	MinDiskSize   int      `json:"min_disk_size,omitempty"`
	SizeGigaBytes float64  `json:"size_gigabytes,omitempty"`
	Created       string   `json:"created_at,omitempty"`
	Description   string   `json:"description,omitempty"`
	Tags          []string `json:"tags,omitempty"`
	Status        string   `json:"status,omitempty"`
	ErrorMessage  string   `json:"error_message,omitempty"`
}

// ImageUpdateRequest represents a request to update an image.
type ImageUpdateRequest struct {
	Name string `json:"name"`
}

// CustomImageCreateRequest represents a request to create a custom image.
type CustomImageCreateRequest struct {
	Name         string   `json:"name"`
	Url          string   `json:"url"`
	Region       string   `json:"region"`
	Distribution string   `json:"distribution,omitempty"`
	Description  string   `json:"description,omitempty"`
	Tags         []string `json:"tags,omitempty"`
}

type imageRoot struct {
	Image *Image
}

type imagesRoot struct {
	Images []Image
	Links  *Links `json:"links"`
	Meta   *Meta  `json:"meta"`
}

type listImageOptions struct {
	Private bool   `url:"private,omitempty"`
	Type    string `url:"type,omitempty"`
	Tag     string `url:"tag_name,omitempty"`
}

func (i Image) String() string {
	return Stringify(i)
}

// List lists all the images available.
func (s *ImagesServiceOp) List(ctx context.Context, opt *ListOptions) ([]Image, *Response, error) {
	return s.list(ctx, opt, nil)
}

// ListDistribution lists all the distribution images.
func (s *ImagesServiceOp) ListDistribution(ctx context.Context, opt *ListOptions) ([]Image, *Response, error) {
	listOpt := listImageOptions{Type: "distribution"}
	return s.list(ctx, opt, &listOpt)
}

// ListApplication lists all the application images.
func (s *ImagesServiceOp) ListApplication(ctx context.Context, opt *ListOptions) ([]Image, *Response, error) {
	listOpt := listImageOptions{Type: "application"}
	return s.list(ctx, opt, &listOpt)
}

// ListUser lists all the user images.
func (s *ImagesServiceOp) ListUser(ctx context.Context, opt *ListOptions) ([]Image, *Response, error) {
	listOpt := listImageOptions{Private: true}
	return s.list(ctx, opt, &listOpt)
}

// ListByTag lists all images with a specific tag applied.
func (s *ImagesServiceOp) ListByTag(ctx context.Context, tag string, opt *ListOptions) ([]Image, *Response, error) {
	listOpt := listImageOptions{Tag: tag}
	return s.list(ctx, opt, &listOpt)
}

// GetByID retrieves an image by id.
func (s *ImagesServiceOp) GetByID(ctx context.Context, imageID int) (*Image, *Response, error) {
	if imageID < 1 {
		return nil, nil, NewArgError("imageID", "cannot be less than 1")
	}

	return s.get(ctx, interface{}(imageID))
}

// GetBySlug retrieves an image by slug.
func (s *ImagesServiceOp) GetBySlug(ctx context.Context, slug string) (*Image, *Response, error) {
	if len(slug) < 1 {
		return nil, nil, NewArgError("slug", "cannot be blank")
	}

	return s.get(ctx, interface{}(slug))
}

func (s *ImagesServiceOp) Create(ctx context.Context, createRequest *CustomImageCreateRequest) (*Image, *Response, error) {
	if createRequest == nil {
		return nil, nil, NewArgError("createRequest", "cannot be nil")
	}

	req, err := s.client.NewRequest(ctx, http.MethodPost, imageBasePath, createRequest)
	if err != nil {
		return nil, nil, err
	}

	root := new(imageRoot)
	resp, err := s.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}

	return root.Image, resp, err
}

// Update an image name.
func (s *ImagesServiceOp) Update(ctx context.Context, imageID int, updateRequest *ImageUpdateRequest) (*Image, *Response, error) {
	if imageID < 1 {
		return nil, nil, NewArgError("imageID", "cannot be less than 1")
	}

	if updateRequest == nil {
		return nil, nil, NewArgError("updateRequest", "cannot be nil")
	}

	path := fmt.Sprintf("%s/%d", imageBasePath, imageID)
	req, err := s.client.NewRequest(ctx, http.MethodPut, path, updateRequest)
	if err != nil {
		return nil, nil, err
	}

	root := new(imageRoot)
	resp, err := s.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}

	return root.Image, resp, err
}

// Delete an image.
func (s *ImagesServiceOp) Delete(ctx context.Context, imageID int) (*Response, error) {
	if imageID < 1 {
		return nil, NewArgError("imageID", "cannot be less than 1")
	}

	path := fmt.Sprintf("%s/%d", imageBasePath, imageID)

	req, err := s.client.NewRequest(ctx, http.MethodDelete, path, nil)
	if err != nil {
		return nil, err
	}

	resp, err := s.client.Do(ctx, req, nil)

	return resp, err
}

// Helper method for getting an individual image
func (s *ImagesServiceOp) get(ctx context.Context, ID interface{}) (*Image, *Response, error) {
	path := fmt.Sprintf("%s/%v", imageBasePath, ID)

	req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
	if err != nil {
		return nil, nil, err
	}

	root := new(imageRoot)
	resp, err := s.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}

	return root.Image, resp, err
}

// Helper method for listing images
func (s *ImagesServiceOp) list(ctx context.Context, opt *ListOptions, listOpt *listImageOptions) ([]Image, *Response, error) {
	path := imageBasePath
	path, err := addOptions(path, opt)
	if err != nil {
		return nil, nil, err
	}
	path, err = addOptions(path, listOpt)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest(ctx, http.MethodGet, path, nil)
	if err != nil {
		return nil, nil, err
	}

	root := new(imagesRoot)
	resp, err := s.client.Do(ctx, req, root)
	if err != nil {
		return nil, resp, err
	}
	if l := root.Links; l != nil {
		resp.Links = l
	}
	if m := root.Meta; m != nil {
		resp.Meta = m
	}

	return root.Images, resp, err
}


text:
CREATE TABLE "practices"
(
    id serial NOT NULL,
    starttime timestamp NOT NULL,
    endtime timestamp NOT NULL,
    location text NOT NULL,
    message text
)


text:
package com.sequenceiq.cloudbreak.structuredevent.rest.urlparsers;

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

@Configuration
@ComponentScan(basePackages = {"com.sequenceiq.cloudbreak.structuredevent.rest.urlparsers"})
public class RestUrlParserConfig {
}


text:
<?php namespace vvMalko\Subscriptions\Subscription\Events;

use vvMalko\Subscriptions\Plans\PaymentOption;
use vvMalko\Subscriptions\Plans\Plan;
use vvMalko\Subscriptions\Subscription\Subscription;

/**
 * Class SubscriptionWasCreated
 *
 * Event was fired when subscription created
 *
 * @package vvMalko\Subscriptions\Subscription\Events
 */
class SubscriptionWasCreated
{
	/**
	 * created subscription
	 *
	 * @var \vvMalko\Subscriptions\Subscription\Subscription
	 */
	public $subscription;

	/**
	 * plan
	 *
	 * @var \vvMalko\Subscriptions\Plans\Plan
	 */
	public $plan;

	/**
	 * payment option
	 *
	 * @var \vvMalko\Subscriptions\Plans\PaymentOption
	 */
	public $paymentOption;

	/**
	 * @param \vvMalko\Subscriptions\Subscription\Subscription $subscription
	 * @param \vvMalko\Subscriptions\Plans\Plan $plan
	 * @param \vvMalko\Subscriptions\Plans\PaymentOption $paymentOption
	 */
	public function __construct(Subscription $subscription, Plan $plan, PaymentOption $paymentOption)
	{
		$this->subscription = $subscription;
		$this->plan = $plan;
		$this->paymentOption = $paymentOption;
	}
}


text:
package dao.quiz

import javax.inject.{Inject, Singleton}
import com.artclod.mathml.scalar.MathMLElem
import com.artclod.util.OneOfThree
import com.artclod.util.ofthree.{First, Second, Third}
import controllers.quiz.{QuestionPartChoiceJson, QuestionPartFunctionJson}
import dao.ColumnTypeMappings
import dao.quiz.table.{QuestionTables, SkillTables}
import dao.user.UserDAO
import dao.user.table.UserTables
import models._
import models.organization.Course
import models.quiz.{User2Quiz, _}
import models.user.User
import org.joda.time.DateTime
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}
import play.api.mvc.Result
import play.api.mvc.Results._
import play.twirl.api.Html
import slick.lifted

import scala.collection.immutable
import scala.concurrent.{ExecutionContext, Future}

// ====
import slick.driver.JdbcProfile
//import slick.jdbc.JdbcProfile // Use this after upgrading slick
// ====

@Singleton
class QuestionDAO @Inject()(protected val dbConfigProvider: DatabaseConfigProvider, protected val userTables: UserTables, protected val questionTables: QuestionTables, protected val skillDAO: SkillDAO, protected val skillTables: SkillTables, protected val userConstantsDAO: UserConstantsDAO)(implicit executionContext: ExecutionContext) extends HasDatabaseConfigProvider[JdbcProfile] with ColumnTypeMappings {
  // ====
  //  import profile.api._ // Use this after upgrading slick
  import dbConfig.driver.api._

  // * ====== TABLE INSTANCES ====== *
  val Questions = questionTables.Questions
  val QuestionSections = questionTables.QuestionSections
  val QuestionPartChoices = questionTables.QuestionPartChoices
  val QuestionPartFunctions = questionTables.QuestionPartFunctions
  val QuestionPartSequences = questionTables.QuestionPartSequences

  // * ====== QUERIES ====== *

  // ====== FIND ======
  def byId(id : QuestionId): Future[Option[Question]] = db.run(Questions.filter(_.id === id).result.headOption)

  def sectionsById(id : QuestionId): Future[Seq[QuestionSection]] = db.run(QuestionSections.filter(_.questionId === id).result)

  def choicePartsId(id : QuestionId): Future[Seq[QuestionPartChoice]] = db.run(QuestionPartChoices.filter(_.questionId === id).result)

  def functionPartsId(id : QuestionId): Future[Seq[QuestionPartFunction]] = db.run(QuestionPartFunctions.filter(_.questionId === id).result)

  def sequencePartsId(id : QuestionId): Future[Seq[QuestionPartSequence]] = db.run(QuestionPartSequences.filter(_.questionId === id).result)

  def frameById(id : QuestionId): Future[Option[QuestionFrame]] = {
    val questionFuture = byId(id)
    val userConstantsFuture = userConstantsDAO.allUserConstants(id)
    val sectionsFuture = sectionsById(id)
    val choicePartsFuture = choicePartsId(id)
    val functionPartsFuture = functionPartsId(id)
    val sequencePartsFuture = sequencePartsId(id)
    val skillsFuture = skillDAO.skillsFor(id)

    questionFuture.flatMap(questionOp => {
      userConstantsFuture.flatMap(userConstants => {
        sectionsFuture.flatMap(sections => {
          choicePartsFuture.flatMap( choiceParts => {
            functionPartsFuture.flatMap( functionParts => {
              sequencePartsFuture.flatMap( sequenceParts => {
                skillsFuture.map( skills => {
        val secId2Fp = functionParts.groupBy(p => p.sectionId)
        val secId2Cp = choiceParts.groupBy(p => p.sectionId)
        val secId2Sp = sequenceParts.groupBy(p => p.sectionId)

        val sectionFrames = sections.map(section => QuestionSectionFrame(section, secId2Cp.getOrElse(section.id, Seq()), secId2Fp.getOrElse(section.id, Seq()), secId2Sp.getOrElse(section.id, Seq())))

        val questionFrameOp : Option[QuestionFrame] = questionOp.map(question => {
          sectionFrames.nonEmpty match {
            case false => throw new IllegalArgumentException("There were no sections for id = " + id)
            case true => QuestionFrame(question, Vector(sectionFrames:_*).sorted, Vector(skills:_*), QuestionUserConstantsFrame(userConstants))
          }
        })

        questionFrameOp

    }) }) }) }) }) }) })
  }

  // === Access ===
  def access(userId: UserId, questionId: QuestionId): Future[Access] = db.run {
    val ownerAccess = (for(q <- Questions if q.ownerId === userId && q.id === questionId) yield q).result.headOption.map(_ match { case Some(_) => Own case None => Non})
    // Currently we only have owner access to a question
//    val directAccess = (for(u2z <- User2Quizzes if u2z.userId === userId && u2z.quizId === quizId) yield u2z.access).result.headOption.map(_.getOrElse(Non))
//    val courseAccess = (for(u2c <- courseTables.User2Courses; c2z <- Courses2Quizzes if u2c.userId === userId && u2c.courseId === c2z.courseId && c2z.quizId === quizId) yield u2c.access).result.headOption.map(_.getOrElse(Non));

//    ownerAccess.flatMap(owner => directAccess.flatMap(direct => courseAccess.map(course => owner max direct max course)))
    ownerAccess
  }

  //--- Skills for question
//  def skillsFor(id : QuestionId) = {
//    null
//  }

  def skillsForAll(): Future[Seq[(Question, Skill)]] = db.run({
    (for (q <- Questions; q2s <- skillTables.Skills2Questions; s <- skillTables.Skills if q.id === q2s.questionId && q2s.skillId === s.id) yield (q, s)).result
  })

  def skillsForAllSet(): Future[Seq[(Question, Set[Skill])]] =
    skillsForAll().map(s => s.groupBy(_._1).mapValues(_.map(_._2)).mapValues(_.toSet).toSeq )

  // ---
  def apply(questionId: QuestionId): Future[Either[Result, Question]] = byId(questionId).map { _ match {
    case None => Left(NotFound(views.html.errors.notFoundPage("There was no question for id=["+questionId+"]")))
    case Some(question) => Right(question)
  } }

  def frameByIdEither(questionId : QuestionId): Future[Either[Result, QuestionFrame]] = frameById(questionId).map { _ match {
    case None => Left(NotFound(views.html.errors.notFoundPage("There was no question for id=["+questionId+"]")))
    case Some(questionFrame) => Right(questionFrame)
  } }

  def frameByOptionIdEither(questionIdOp: Option[QuestionId]): Future[Either[Result, Option[QuestionFrame]]] =
    questionIdOp match {
      case Some(questionId) => frameById(questionId).map { _ match {
        case None => Left(NotFound(views.html.errors.notFoundPage("There was no question for id=["+questionId+"]")))
        case Some(questionFrame) => Right(Some(questionFrame))
      } }
      case None => Future.successful(Right(None))
    }

  // ====== Question Search =====
  private def questionSearch(titleQuery: String, userId: UserId) = db.run({
    (for (q <- Questions; q2s <- skillTables.Skills2Questions; s <- skillTables.Skills
          if ((q.title like titleQuery) && q.id === q2s.questionId && q2s.skillId === s.id) && q.archivedNum === 0.toShort // Don't show the question if it's been archived
    ) yield (q, s))
      .union(
    (for (q <- Questions; q2s <- skillTables.Skills2Questions; s <- skillTables.Skills
          if ((q.title like titleQuery) && q.id === q2s.questionId && q2s.skillId === s.id) && (q.archivedNum =!= 0.toShort && q.ownerId === userId) // Show archived questions if the user is the owner
    ) yield (q, s))
    ).result
  })

  def questionSearchSet(userId: UserId, nameQuery: String, requiredSkills: Seq[String], bannedSkills: Seq[String]): Future[Seq[(Question, Set[Skill])]] = {
    val req = requiredSkills.toSet
    val ban = bannedSkills.toSet

    val ret = questionSearch(nameQuery, userId).map(s => s.groupBy(_._1).mapValues(_.map(_._2)).mapValues(_.toSet).toSeq)

    ret.map(questionList => {
      questionList.filter(question => {
        val skillsForQuestion = question._2.map(_.name).toSet
        val reqPass = req.subsetOf(skillsForQuestion)
        val banPass = ban.intersect(skillsForQuestion).isEmpty
        reqPass && banPass
      })
    })
  }

//  def questionSearchSet(nameQuery: String, requiredSkills: Seq[String], bannedSkills: Seq[String]): Future[Seq[(Question, Set[Skill])]] = {
//    val req = requiredSkills.toSet
//    val ban = bannedSkills.toSet
//
//    val ret = questionSearch(nameQuery).map(s => s.groupBy(_._1).mapValues(_.map(_._2)).mapValues(_.toSet).toSeq)
//
//    ret.map(questionList => {
//      questionList.filter(question => {
//        val skillsForQuestion = question._2.map(_.name).toSet
//        val reqPass = req.subsetOf(skillsForQuestion)
//        val banPass = ban.intersect(skillsForQuestion).isEmpty
//        reqPass && banPass
//      })
//    })
//  }

  // ====== Create ======
  def insert(questionFrame: QuestionFrame) : Future[QuestionFrame] = {
    insert(questionFrame.question).flatMap{ question => {
      val skillsFuture = skillDAO.addSkills(question, questionFrame.skills) // Note we don't create new skills here they should already exist, but we need to "wait" on the future

      val userConstantsFuture = userConstantsDAO.insert(questionFrame.userConstants.questionId(question.id))

      val sectionsFutures : Seq[Future[QuestionSectionFrame]] = questionFrame.id(question.id).sections.map(section => insert(section))
      val futureOfSections : Future[Vector[QuestionSectionFrame]] = com.artclod.concurrent.raiseFuture(sectionsFutures).map(_.sorted)

      userConstantsFuture.flatMap(userConstants => skillsFuture.flatMap(skillCount => futureOfSections.map(sections =>
        QuestionFrame(question, sections, questionFrame.skills, userConstants)
      )))

      }
    }
  }

  def insert(sectionFrame: QuestionSectionFrame) : Future[QuestionSectionFrame] = {
    insert(sectionFrame.section).flatMap(section => {
      (sectionFrame.id(section.id).parts match {
        case First(ps)  => insertChoices(ps).map(p   => First[  Vector[QuestionPartChoice], Vector[QuestionPartFunction], Vector[QuestionPartSequence] ](Vector(p:_*).sorted))
        case Second(ps) => insertFunctions(ps).map(p => Second[ Vector[QuestionPartChoice], Vector[QuestionPartFunction], Vector[QuestionPartSequence] ](Vector(p:_*).sorted))
        case Third(ps)  => insertSequences(ps).map(p => Third[  Vector[QuestionPartChoice], Vector[QuestionPartFunction], Vector[QuestionPartSequence] ](Vector(p:_*).sorted))
      }).map(parts => QuestionSectionFrame(section = section, parts = parts) )
    })
  }

  def insert(question: Question): Future[Question] = db.run(
    (Questions returning Questions.map(_.id) into ((needsId, id) => needsId.copy(id = id))) += question
  )

  def insert(questionSection: QuestionSection): Future[QuestionSection] = db.run(
    (QuestionSections returning QuestionSections.map(_.id) into ((needsId, id) => needsId.copy(id = id))) += questionSection
  )

  def insertChoices(questionPartChoices: Seq[QuestionPartChoice]): Future[Seq[QuestionPartChoice]] = db.run {
    (QuestionPartChoices returning QuestionPartChoices.map(_.id) into ((needsId, id) => needsId.copy(id = id))) ++= questionPartChoices
  }

  def insertFunctions(questionPartFunctions: Seq[QuestionPartFunction]): Future[Seq[QuestionPartFunction]] = db.run {
    (QuestionPartFunctions returning QuestionPartFunctions.map(_.id) into ((needsId, id) => needsId.copy(id = id))) ++= questionPartFunctions
  }

  def insertSequences(questionPartSequence: Seq[QuestionPartSequence]): Future[Seq[QuestionPartSequence]] = db.run {
    (QuestionPartSequences returning QuestionPartSequences.map(_.id) into ((needsId, id) => needsId.copy(id = id))) ++= questionPartSequence
  }

  // ====== Update ======
  // https://stackoverflow.com/questions/16757368/how-do-you-update-multiple-columns-using-slick-lifted-embedding
  def update(question: Question, archived: Short) =
    db.run((for { q <- Questions if q.id === question.id } yield q ).map(q => (q.archivedNum) ).update( archived))

}


text:
import { EntityMetadata } from "../../metadata/EntityMetadata"

export class ViewUtils {
    /**
     * Comparator for .sort() that will order views bases on dependencies in creation order
     */
    static viewMetadataCmp(
        metadataA: EntityMetadata | undefined,
        metadataB: EntityMetadata | undefined,
    ): number {
        if (!metadataA || !metadataB) {
            return 0
        }
        if (
            metadataA.dependsOn &&
            (metadataA.dependsOn.has(metadataB.target) ||
                metadataA.dependsOn.has(metadataB.name))
        ) {
            return 1
        }
        if (
            metadataB.dependsOn &&
            (metadataB.dependsOn.has(metadataA.target) ||
                metadataB.dependsOn.has(metadataA.name))
        ) {
            return -1
        }
        return 0
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

  <com.github.ppamorim.library.DraggerPanel
      android:id="@+id/dragger_panel"
      android:layout_width="match_parent"
      android:layout_height="match_parent"/>

</FrameLayout>


text:
package bootkube

import (
	"os"
	"path/filepath"

	"github.com/openshift/installer/pkg/asset"
	"github.com/openshift/installer/pkg/asset/templates/content"
)

const (
	machineConfigServerTLSSecretFileName = "machine-config-server-tls-secret.yaml.template"
)

var _ asset.WritableAsset = (*MachineConfigServerTLSSecret)(nil)

// MachineConfigServerTLSSecret is the constant to represent contents of machine_configservertlssecret.yaml.template file
type MachineConfigServerTLSSecret struct {
	FileList []*asset.File
}

// Dependencies returns all of the dependencies directly needed by the asset
func (t *MachineConfigServerTLSSecret) Dependencies() []asset.Asset {
	return []asset.Asset{}
}

// Name returns the human-friendly name of the asset.
func (t *MachineConfigServerTLSSecret) Name() string {
	return "MachineConfigServerTLSSecret"
}

// Generate generates the actual files by this asset
func (t *MachineConfigServerTLSSecret) Generate(parents asset.Parents) error {
	fileName := machineConfigServerTLSSecretFileName
	data, err := content.GetBootkubeTemplate(fileName)
	if err != nil {
		return err
	}
	t.FileList = []*asset.File{
		{
			Filename: filepath.Join(content.TemplateDir, fileName),
			Data:     []byte(data),
		},
	}
	return nil
}

// Files returns the files generated by the asset.
func (t *MachineConfigServerTLSSecret) Files() []*asset.File {
	return t.FileList
}

// Load returns the asset from disk.
func (t *MachineConfigServerTLSSecret) Load(f asset.FileFetcher) (bool, error) {
	file, err := f.FetchByName(filepath.Join(content.TemplateDir, machineConfigServerTLSSecretFileName))
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}
	t.FileList = []*asset.File{file}
	return true, nil
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

	class verificarTokenChangePassword extends CI_Model
	{
		public function __construct()
		{
			parent::__construct();
		}

		public function verifyTokenChangePassword($token)
		{

			$sql1 =	"select
							usu.id_usuario,
							ufp.token
					 from
							users_forgot_passwords ufp
					 join 	usuarios usu on (ufp.id_usuario = usu.id_usuario)
					 where 	ufp.token = ? and usu.estado = 1 ";

					$query = $this->db->query($sql1,array($token));

			   $datos = array("msjCantidadRegistros" => 0, "msjNoHayRegistros" => '' ,"usuarioTokens" => array());

				$datos["msjCantidadRegistros"] = $query->num_rows();

				if($datos["msjCantidadRegistros"] > 0)
				{
					$datos["usuarioTokens"] = $query->result();
				}
				else
				{
					$datos["msjNoHayRegistros"] = "No existe un token de ese usuario.";
				}

				return $datos;

		}

	}
?>