text:
/*
 * ATM Forum UNI 3.0/3.1 Signalling Manager
 * ----------------------------------------
 *
 * System interface module
 *
 */

#include <sys/param.h>
#include <sys/systm.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <sys/malloc.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/socketvar.h>
#include <sys/syslog.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netatm/port.h>
#include <netatm/queue.h>
#include <netatm/atm.h>
#include <netatm/atm_sys.h>
#include <netatm/atm_sap.h>
#include <netatm/atm_cm.h>
#include <netatm/atm_if.h>
#include <netatm/atm_vc.h>
#include <netatm/atm_ioctl.h>
#include <netatm/atm_sigmgr.h>
#include <netatm/atm_stack.h>
#include <netatm/atm_pcb.h>
#include <netatm/atm_var.h>

#include <netatm/ipatm/ipatm_var.h>
#include <netatm/ipatm/ipatm_serv.h>
#include <netatm/uni/uniip_var.h>

#include <netatm/uni/unisig.h>
#include <netatm/uni/unisig_var.h>
#include <netatm/uni/unisig_msg.h>

#include <vm/uma.h>

#ifndef lint
__RCSID("@(#) $FreeBSD: src/sys/netatm/uni/unisig_if.c,v 1.13 2002/06/13 14:32:51 arr Exp $");
#endif

/*
 * Global variables
 */
uma_zone_t	unisig_vc_zone;
uma_zone_t	unisig_msg_zone;
uma_zone_t	unisig_ie_zone;

/*
 * Local functions
 */
static int	unisig_attach(struct sigmgr *, struct atm_pif *);
static int	unisig_detach(struct atm_pif *);
static int	unisig_setup(Atm_connvc *, int *);
static int	unisig_release(struct vccb *, int *);
static int	unisig_accept(struct vccb *, int *);
static int	unisig_reject(struct vccb *, int *);
static int	unisig_abort(struct vccb *);
static int	unisig_ioctl(int, caddr_t, caddr_t);

/*
 * Local variables
 */
static struct sigmgr	unisig_mgr30 = {
	NULL,
	ATM_SIG_UNI30,
	NULL,
	unisig_attach,
	unisig_detach,
	unisig_setup,
	unisig_accept,
	unisig_reject,
	unisig_release,
	unisig_free,
	unisig_ioctl
};

static struct sigmgr	unisig_mgr31 = {
	NULL,
	ATM_SIG_UNI31,
	NULL,
	unisig_attach,
	unisig_detach,
	unisig_setup,
	unisig_accept,
	unisig_reject,
	unisig_release,
	unisig_free,
	unisig_ioctl
};

/*
 * Initialize UNISIG processing
 *
 * This will be called during module loading.  We'll just register
 * the UNISIG protocol descriptor and wait for a UNISIG ATM interface
 * to come online.
 *
 * Arguments:
 *	none
 *
 * Returns:
 *	0	startup was successful
 *	errno	startup failed - reason indicated
 *
 */
int
unisig_start()
{
	int	err = 0;

	/*
	 * Verify software version
	 */
	if (atm_version != ATM_VERSION) {
		log(LOG_ERR, "version mismatch: unisig=%d.%d kernel=%d.%d\n",
				ATM_VERS_MAJ(ATM_VERSION),
				ATM_VERS_MIN(ATM_VERSION),
				ATM_VERS_MAJ(atm_version),
				ATM_VERS_MIN(atm_version));
		return (EINVAL);
	}

	/*
	 * Atleast ensure the versioning prior to creating our
	 * UMA zone.
	 */
	unisig_vc_zone = uma_zcreate("unisig vcc", sizeof(struct unisig_vccb),
	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
	if (unisig_vc_zone == NULL)
		panic("unisig_start: uma_zcreate failed to create vcc zone");
	unisig_msg_zone = uma_zcreate("unisig msg", sizeof(struct unisig_msg),
	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
	if (unisig_msg_zone == NULL)
		panic("unisig_start: uma_zcreate failed to create msg zone");
	unisig_ie_zone = uma_zcreate("unisig ie", sizeof(struct ie_generic),
	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
	if (unisig_ie_zone == NULL)
		panic("unisig_start: uma_zcreate failed to create ie zone");

	uma_zone_set_max(unisig_vc_zone, 50);
	uma_zone_set_max(unisig_msg_zone, 50);
	uma_zone_set_max(unisig_ie_zone, 50);

	/*
	 * Register ourselves with system
	 */
	err = atm_sigmgr_register(&unisig_mgr30);
	if (err)
		goto done;

	err = atm_sigmgr_register(&unisig_mgr31);

done:
	return (err);
}

/*
 * Halt UNISIG processing
 *
 * This should be called just prior to unloading the module from
 * memory.  All UNISIG interfaces must be deregistered before the
 * protocol can be shutdown.
 *
 * Arguments:
 *	none
 *
 * Returns:
 *	0	startup was successful
 *	errno	startup failed - reason indicated
 *
 */
int
unisig_stop()
{
	int	err = 0;
	int	s = splnet();

	/*
	 * Any protocol instances still registered?
	 */
	if ((unisig_mgr30.sm_prinst != NULL) ||
	    (unisig_mgr31.sm_prinst != NULL)) {

		/* Yes, can't stop now */
		err = EBUSY;
		goto done;
	}

	/*
	 * De-register from system
	 */
	(void) atm_sigmgr_deregister(&unisig_mgr30);
	(void) atm_sigmgr_deregister(&unisig_mgr31);

	/*
	 * Free up our storage pools
	 */
	uma_zdestroy(unisig_vc_zone);
	uma_zdestroy(unisig_msg_zone);
	uma_zdestroy(unisig_ie_zone);
done:
	(void)splx(s);
	return (err);
}

/*
 * Attach a UNISIG-controlled interface
 *
 * Each ATM physical interface must be attached with the signalling
 * manager for the interface's signalling protocol (via the
 * atm_sigmgr_attach function).  This function will handle the
 * attachment for UNISIG-controlled interfaces.  A new UNISIG protocol
 * instance will be created and then we'll just sit around waiting for
 * status or connection requests.
 *
 * Function must be called at splnet.
 *
 * Arguments:
 *	smp	pointer to UNISIG signalling manager control block
 *	pip	pointer to ATM physical interface control block
 *
 * Returns:
 *	0	attach successful
 *	errno	attach failed - reason indicated
 *
 */
static int
unisig_attach(smp, pip)
	struct sigmgr	*smp;
	struct atm_pif	*pip;
{
	int			err = 0, s;
	struct unisig		*usp = NULL;

	ATM_DEBUG2("unisig_attach: smp=%p, pip=%p\n", smp, pip);

	/*
	 * Allocate UNISIG protocol instance control block
	 */
	usp = malloc(sizeof(struct unisig), M_DEVBUF, M_NOWAIT | M_ZERO);
	if (usp == NULL) {
		err = ENOMEM;
		goto done;
	}
	/*
	 * Set state in UNISIG protocol instance control block
	 */
	usp->us_state = UNISIG_NULL;
	usp->us_proto = smp->sm_proto;

	/*
	 * Set initial call reference allocation value
	 */
	usp->us_cref = 1;

	/*
	 * Link instance into manager's chain
	 */
	LINK2TAIL((struct siginst *)usp, struct siginst, smp->sm_prinst,
			si_next);

	/*
	 * Link in interface
	 */
	usp->us_pif = pip;
	s = splimp();
	pip->pif_sigmgr = smp;
	pip->pif_siginst = (struct siginst *) usp;
	(void) splx(s);

	/*
	 * Clear our ATM address.  The address will be set by user
	 * command or by registration via ILMI.
	 */
	usp->us_addr.address_format = T_ATM_ABSENT;
	usp->us_addr.address_length = 0;
	usp->us_subaddr.address_format = T_ATM_ABSENT;
	usp->us_subaddr.address_length = 0;

	/*
	 * Set pointer to IP
	 */
	usp->us_ipserv = &uniip_ipserv;

	/*
	 * Kick-start the UNISIG protocol
	 */
	UNISIG_TIMER(usp, 0);

	/*
	 * Log the fact that we've attached
	 */
	log(LOG_INFO, "unisig: attached to interface %s%d\n",
			pip->pif_name, pip->pif_unit);

done:
	/*
	 * Reset our work if attach fails
	 */
	if (err) {
		if (usp) {
			UNISIG_CANCEL(usp);
			UNLINK((struct siginst *)usp, struct siginst,
					smp->sm_prinst, si_next);
			free(usp, M_DEVBUF);
		}
		s = splimp();
		pip->pif_sigmgr = NULL;
		pip->pif_siginst = NULL;
		(void) splx(s);
	}

	return (err);
}

/*
 * Detach a UNISIG-controlled interface
 *
 * Each ATM physical interface may be detached from its signalling
 * manager (via the atm_sigmgr_detach function).  This function will
 * handle the detachment for all UNISIG-controlled interfaces.  All
 * circuits will be immediately terminated.
 *
 * Function must be called at splnet.
 *
 * Arguments:
 *	pip	pointer to ATM physical interface control block
 *
 * Returns:
 *	0	detach successful
 *	errno	detach failed - reason indicated
 *
 */
static int
unisig_detach(pip)
	struct atm_pif	*pip;
{
	struct unisig		*usp;
	int			err;

	ATM_DEBUG1("unisig_detach: pip=%p\n", pip);

	/*
	 * Get UNISIG protocol instance
	 */
	usp = (struct unisig *)pip->pif_siginst;

	/*
	 * Return an error if we're already detaching
	 */
	if (usp->us_state == UNISIG_DETACH) {
		return(EALREADY);
	}

	/*
	 * Pass the detach event to the signalling manager
	 * state machine
	 */
	err = unisig_sigmgr_state(usp, UNISIG_SIGMGR_DETACH,
			(KBuffer *)0);

	/*
	 * Log the fact that we've detached
	 */
	if (!err)
		log(LOG_INFO, "unisig: detached from interface %s%d\n",
				pip->pif_name, pip->pif_unit);

	return (0);
}

/*
 * Open a UNISIG ATM Connection
 *
 * All service user requests to open a VC connection (via
 * atm_open_connection) over an ATM interface attached to the UNISIG
 * signalling manager are handled here.
 *
 * Function will be called at splnet.
 *
 * Arguments:
 *	cvp	pointer to user's requested connection parameters
 *	errp	pointer to an int for extended error information
 *
 * Returns:
 *	CALL_PROCEEDING	connection establishment is in progress
 *	CALL_FAILED	connection establishment failed
 *	CALL_CONNECTED	connection has been successfully established
 *
 */
static int
unisig_setup(cvp, errp)
	Atm_connvc	*cvp;
	int		*errp;
{
	struct atm_pif	*pip = cvp->cvc_attr.nif->nif_pif;
	struct unisig	*usp = (struct unisig *)pip->pif_siginst;
	int		rc = 0;

	ATM_DEBUG1("unisig_setup: cvp=%p\n", cvp);

	/*
	 * Intialize the returned error code
	 */
	*errp = 0;

	/*
	 * Open the connection
	 */
	switch (cvp->cvc_attr.called.addr.address_format) {
	case T_ATM_PVC_ADDR:
		/*
		 * Create a PVC
		 */
		*errp = unisig_open_vcc(usp, cvp);
		rc = (*errp ? CALL_FAILED : CALL_CONNECTED);
		break;

	case T_ATM_ENDSYS_ADDR:
	case T_ATM_E164_ADDR:

		/*
		 * Create an SVC
		 */
		*errp = unisig_open_vcc(usp, cvp);
		rc = (*errp ? CALL_FAILED : CALL_PROCEEDING);
		break;

	default:
		*errp = EPROTONOSUPPORT;
		rc = CALL_FAILED;
	}

	return (rc);
}

/*
 * Close a UNISIG ATM Connection
 *
 * All service user requests to terminate a previously open VC
 * connection (via the atm_close_connection function), which is running
 * over an interface attached to the UNISIG signalling manager, are
 * handled here.
 *
 * Function will be called at splnet.
 *
 * Arguments:
 *	vcp	pointer to connection's VC control block
 *	errp	pointer to an int for extended error information
 *
 * Returns:
 *	CALL_PROCEEDING	connection termination is in progress
 *	CALL_FAILED	connection termination failed
 *	CALL_CLEARED	connection has been successfully terminated
 *
 */
static int
unisig_release(vcp, errp)
	struct vccb	*vcp;
	int		*errp;
{
	int		rc = 0;
	struct atm_pif	*pip = vcp->vc_pif;
	struct unisig	*usp = (struct unisig *)pip->pif_siginst;

	ATM_DEBUG1("unisig_release: vcp=%p\n", vcp);

	/*
	 * Initialize returned error code
	 */
	*errp = 0;

	/*
	 * Validate the connection type (PVC or SVC)
	 */
	if (!(vcp->vc_type & (VCC_PVC | VCC_SVC))) {
		*errp = EPROTONOSUPPORT;
		return(CALL_FAILED);
	}

	/*
	 * Close the VCCB
	 */
	*errp = unisig_close_vcc(usp, (struct unisig_vccb *)vcp);

	/*
	 * Set the return code
	 */
	if (*errp) {
		rc = CALL_FAILED;
	} else if (vcp->vc_sstate == UNI_NULL ||
			vcp->vc_sstate == UNI_FREE) {
		rc = CALL_CLEARED;
	} else {
		rc = CALL_PROCEEDING;
	}

	return (rc);
}

/*
 * Accept a UNISIG Open from a remote host
 *
 * A user calls this routine (via the atm_accept_call function)
 * after it is notified that an open request was received for it.
 *
 * Function will be called at splnet.
 *
 * Arguments:
 *	vcp	pointer to user's VCCB
 *	errp	pointer to an int for extended error information
 *
 * Returns:
 *	CALL_PROCEEDING	connection establishment is in progress
 *	CALL_FAILED	connection establishment failed
 *	CALL_CONNECTED	connection has been successfully established
 *
 */
static int
unisig_accept(vcp, errp)
	struct vccb	*vcp;
	int		*errp;
{
	struct unisig_vccb	*uvp = (struct unisig_vccb *)vcp;
	struct atm_pif		*pip = uvp->uv_pif;
	struct unisig		*usp = (struct unisig *)pip->pif_siginst;

	ATM_DEBUG1("unisig_accept: vcp=%p\n", vcp);

	/*
	 * Initialize the returned error code
	 */
	*errp = 0;

	/*
	 * Return an error if we're detaching
	 */
	if (usp->us_state == UNISIG_DETACH) {
		*errp = ENETDOWN;
		goto free;
	}

	/*
	 * Return an error if we lost the connection
	 */
	if (uvp->uv_sstate == UNI_FREE) {
		*errp = ENETDOWN;
		goto free;
	}

	/*
	 * Pass the acceptance to the VC state machine
	 */
	*errp = unisig_vc_state(usp, uvp, UNI_VC_ACCEPT_CALL,
			(struct unisig_msg *) 0);
	if (*errp)
		goto failed;

	return(CALL_PROCEEDING);

failed:
	/*
	 * On error, free the VCCB and return CALL_FAILED
	 */

free:
	uvp->uv_sstate = UNI_FREE;
	uvp->uv_ustate = VCCU_CLOSED;
	DEQUEUE(uvp, struct unisig_vccb, uv_sigelem, usp->us_vccq);
	unisig_free((struct vccb *)uvp);

	return(CALL_FAILED);
}

/*
 * Reject a UNISIG Open from a remote host
 *
 * A user calls this routine (via the atm_reject_call function)
 * after it is notified that an open request was received for it.
 *
 * Function will be called at splnet.
 *
 * Arguments:
 *	uvp	pointer to user's VCCB
 *	errp	pointer to an int for extended error information
 *
 * Returns:
 *	CALL_CLEARED	call request rejected
 *	CALL_FAILED	call rejection failed
 *
 */
static int
unisig_reject(vcp, errp)
	struct vccb	*vcp;
	int		*errp;
{
	struct unisig_vccb	*uvp = (struct unisig_vccb *)vcp;
	struct atm_pif		*pip = uvp->uv_pif;
	struct unisig		*usp = (struct unisig *)pip->pif_siginst;

	ATM_DEBUG1("unisig_reject: uvp=%p\n", uvp);

	/*
	 * Initialize the returned error code
	 */
	*errp = 0;

	/*
	 * Return an error if we're detaching
	 */
	if (usp->us_state == UNISIG_DETACH) {
		*errp = ENETDOWN;
		goto failed;
	}

	/*
	 * Call the VC state machine
	 */
	*errp = unisig_vc_state(usp, uvp, UNI_VC_REJECT_CALL,
			(struct unisig_msg *) 0);
	if (*errp)
		goto failed;

	return(CALL_CLEARED);

failed:
	/*
	 * On error, free the VCCB and return CALL_FAILED
	 */
	uvp->uv_sstate = UNI_FREE;
	uvp->uv_ustate = VCCU_CLOSED;
	DEQUEUE(uvp, struct unisig_vccb, uv_sigelem, usp->us_vccq);
	(void) unisig_free((struct vccb *)uvp);
	return(CALL_FAILED);
}

/*
 * Abort a UNISIG ATM Connection
 *
 * All (non-user) requests to abort a previously open VC connection (via
 * the atm_abort_connection function), which is running over an
 * interface attached to the UNISIG signalling manager, are handled here.
 * The VCC owner will be notified of the request, in order to initiate
 * termination of the connection.
 *
 * Function will be called at splnet.
 *
 * Arguments:
 *      vcp     pointer to connection's VC control block
 *
 * Returns:
 *      0       connection release was successful
 *      errno   connection release failed - reason indicated
 *
 */
static int
unisig_abort(vcp)
	struct vccb	*vcp;
{

	ATM_DEBUG1("unisig_abort: vcp=%p\n", vcp);

	/*
	 * Only abort once
	 */
	if (vcp->vc_ustate == VCCU_ABORT) {
		return (EALREADY);
	}

	/*
	 * Cancel any timer that might be running
	 */
	UNISIG_VC_CANCEL(vcp);

	/*
	 * Set immediate timer to schedule connection termination
	 */
	vcp->vc_ustate = VCCU_ABORT;
	UNISIG_VC_TIMER(vcp, 0);

	return (0);
}

/*
 * Free UNISIG ATM connection resources
 *
 * All service user requests to free the resources of a closed VCC
 * connection (via the atm_free_connection function), which is running
 * over an interface attached to the UNISIG signalling manager, are
 *handled here.
 *
 * Function will be called at splnet.
 *
 * Arguments:
 *	vcp	pointer to connection's VC control block
 *
 * Returns:
 *	0	connection free was successful
 *	errno	connection free failed - reason indicated
 *
 */
int
unisig_free(vcp)
	struct vccb	*vcp;
{
	struct atm_pif *pip = vcp->vc_pif;
	struct unisig *usp = (struct unisig *)pip->pif_siginst;

	ATM_DEBUG1("unisig_free: vcp = %p\n", vcp);

	/*
	 * Make sure VCC has been closed
	 */
	if ((vcp->vc_ustate != VCCU_CLOSED &&
			vcp->vc_ustate != VCCU_ABORT) ||
			vcp->vc_sstate != UNI_FREE) {
		ATM_DEBUG2("unisig_free: bad state, sstate=%d, ustate=%d\n",
				vcp->vc_sstate, vcp->vc_ustate);
		return(EEXIST);
	}

	/*
	 * Remove VCCB from protocol queue
	 */
	DEQUEUE(vcp, struct vccb, vc_sigelem, usp->us_vccq);

	/*
	 * Free VCCB storage
	 */
	vcp->vc_ustate = VCCU_NULL;
	vcp->vc_sstate = UNI_NULL;
	uma_zfree(unisig_vc_zone, vcp);

	/*
	 * If we're detaching and this was the last VCC queued,
	 * get rid of the protocol instance
	 */
	if ((usp->us_state == UNISIG_DETACH) &&
			(Q_HEAD(usp->us_vccq, struct vccb) == NULL)) {
		struct sigmgr   *smp = pip->pif_sigmgr;
		int     s = splimp();

		pip->pif_sigmgr = NULL;
		pip->pif_siginst = NULL;
		(void) splx(s);

		UNLINK((struct siginst *)usp, struct siginst,
				smp->sm_prinst, si_next);
		free(usp, M_DEVBUF);
	}

	return (0);
}

/*
 * UNISIG IOCTL support
 *
 * Function will be called at splnet.
 *
 * Arguments:
 *	code	PF_ATM sub-operation code
 *      data    pointer to code specific parameter data area
 *      arg1    pointer to code specific argument
 *
 * Returns:
 *	0	request procesed
 *	errno	error processing request - reason indicated
 *
 */
static int
unisig_ioctl(code, data, arg1)
        int		code;
        caddr_t		data;
        caddr_t		arg1;
{
	struct atmdelreq	*adp;
	struct atminfreq	*aip;
	struct atmsetreq	*asp;
	struct unisig		*usp;
	struct unisig_vccb	*uvp;
	struct air_vcc_rsp	rsp;
	struct atm_pif		*pip;
	Atm_connection		*cop;
	u_int			vpi, vci;
	int			err = 0, buf_len, i;
	caddr_t			buf_addr;

	ATM_DEBUG1("unisig_ioctl: code=%d\n", code);

	switch (code) {

	case AIOCS_DEL_PVC:
	case AIOCS_DEL_SVC:
		/*
		 * Delete a VCC
		 */
		adp = (struct atmdelreq *)data;
		usp = (struct unisig *)arg1;

		/*
		 * Don't let a user close the UNISIG signalling VC
		 */
		vpi = adp->adr_pvc_vpi;
		vci = adp->adr_pvc_vci;
		if ((vpi == UNISIG_SIG_VPI && vci == UNISIG_SIG_VCI))
			return(EINVAL);

		/*
		 * Find requested VCC
		 */
		for (uvp = Q_HEAD(usp->us_vccq, struct unisig_vccb); uvp;
				uvp = Q_NEXT(uvp, struct unisig_vccb, uv_sigelem)) {
			if ((uvp->uv_vpi == vpi) && (uvp->uv_vci == vci))
				break;
		}
		if (uvp == NULL)
			return (ENOENT);

		/*
		 * Check VCC type
		 */
		switch (code) {
		case AIOCS_DEL_PVC:
			if (!(uvp->uv_type & VCC_PVC)) {
				return(EINVAL);
			}
			break;
		case AIOCS_DEL_SVC:
			if (!(uvp->uv_type & VCC_SVC)) {
				return(EINVAL);
			}
			break;
		}

		/*
		 * Schedule VCC termination
		 */
		unisig_cause_attr_from_user(&uvp->uv_connvc->cvc_attr,
				T_ATM_CAUSE_UNSPECIFIED_NORMAL);
		err = unisig_abort((struct vccb *)uvp);
		break;

	case AIOCS_INF_VCC:
		/*
		 * Return VCC information
		 */
		aip = (struct atminfreq *)data;
		usp = (struct unisig *)arg1;

		buf_addr = aip->air_buf_addr;
		buf_len = aip->air_buf_len;

		/*
		 * Loop through the VCC queue
		 */
		for (uvp = Q_HEAD(usp->us_vccq, struct unisig_vccb); uvp;
				uvp = Q_NEXT(uvp, struct unisig_vccb, uv_sigelem)) {
			/*
			 * Make sure there's room in the user's buffer
			 */
			if (buf_len < sizeof(rsp)) {
				err = ENOSPC;
				break;
			}

			/*
			 * Fill out the response struct for the VCC
			 */
			(void) snprintf(rsp.avp_intf,
				    sizeof(rsp.avp_intf), "%s%d",
					usp->us_pif->pif_name,
					usp->us_pif->pif_unit);
			rsp.avp_vpi = uvp->uv_vpi;
			rsp.avp_vci = uvp->uv_vci;
			rsp.avp_type = uvp->uv_type;
			rsp.avp_aal = uvp->uv_connvc->cvc_attr.aal.type;
			rsp.avp_sig_proto = uvp->uv_proto;
			cop = uvp->uv_connvc->cvc_conn;
			if (cop)
				rsp.avp_encaps = cop->co_mpx;
			else
				rsp.avp_encaps = 0;
			rsp.avp_state = uvp->uv_sstate;
			if (uvp->uv_connvc->cvc_flags & CVCF_CALLER) {
				rsp.avp_daddr = uvp->uv_connvc->cvc_attr.called.addr;
			} else {
				rsp.avp_daddr = uvp->uv_connvc->cvc_attr.calling.addr;
			}
			rsp.avp_dsubaddr.address_format = T_ATM_ABSENT;
			rsp.avp_dsubaddr.address_length = 0;
			rsp.avp_ipdus = uvp->uv_ipdus;
			rsp.avp_opdus = uvp->uv_opdus;
			rsp.avp_ibytes = uvp->uv_ibytes;
			rsp.avp_obytes = uvp->uv_obytes;
			rsp.avp_ierrors = uvp->uv_ierrors;
			rsp.avp_oerrors = uvp->uv_oerrors;
			rsp.avp_tstamp = uvp->uv_tstamp;
			bzero(rsp.avp_owners,
					sizeof(rsp.avp_owners));
			for (i = 0; cop && i < sizeof(rsp.avp_owners);
					cop = cop->co_next,
					i += T_ATM_APP_NAME_LEN+1) {
				strncpy(&rsp.avp_owners[i],
					cop->co_endpt->ep_getname(cop->co_toku),
					T_ATM_APP_NAME_LEN);
			}

			/*
			 * Copy the response into the user's buffer
			 */
			if ((err = copyout((caddr_t)&rsp, buf_addr,
					sizeof(rsp))) != 0)
				break;
			buf_addr += sizeof(rsp);
			buf_len -= sizeof(rsp);
		}

		/*
		 * Update the buffer pointer and length
		 */
		aip->air_buf_addr = buf_addr;
		aip->air_buf_len = buf_len;
		break;

	case AIOCS_INF_ARP:
	case AIOCS_INF_ASV:
	case AIOCS_SET_ASV:
		/*
		 * Get ARP table information or get/set ARP server address
		 */
		err = uniarp_ioctl(code, data, arg1);
		break;

	case AIOCS_SET_PRF:
		/*
		 * Set NSAP prefix
		 */
		asp = (struct atmsetreq *)data;
		usp = (struct unisig *)arg1;
		pip = usp->us_pif;
		if (usp->us_addr.address_format != T_ATM_ABSENT) {
			if (bcmp(asp->asr_prf_pref, usp->us_addr.address,
					sizeof(asp->asr_prf_pref)) != 0)
				err = EALREADY;
			break;
		}
		usp->us_addr.address_format = T_ATM_ENDSYS_ADDR;
		usp->us_addr.address_length = sizeof(Atm_addr_nsap);
		bcopy(&pip->pif_macaddr,
			((Atm_addr_nsap *)usp->us_addr.address)->aan_esi,
			sizeof(pip->pif_macaddr));
		bcopy((caddr_t) asp->asr_prf_pref,
			&((Atm_addr_nsap *)usp->us_addr.address)->aan_afi,
			sizeof(asp->asr_prf_pref));
		log(LOG_INFO, "uni: set address %s on interface %s\n",
				unisig_addr_print(&usp->us_addr),
				asp->asr_prf_intf);

		/*
		 * Pass event to signalling manager state machine
		 */
		err = unisig_sigmgr_state(usp, UNISIG_SIGMGR_ADDR_SET,
				(KBuffer *) NULL);

		/*
		 * Clean up if there was an error
		 */
		if (err) {
			usp->us_addr.address_format = T_ATM_ABSENT;
			usp->us_addr.address_length = 0;
			break;
		}

		/*
		 * Inform ARP code of new address
		 */
		uniarp_ifaddr((struct siginst *)usp);
		break;

	default:
		err = EOPNOTSUPP;
	}

	return (err);
}


text:
<?php

require_once __DIR__.'/symfony-standard/app/bootstrap.php.cache';
require_once __DIR__.'/symfony-standard/app/AppKernel.php';
// require_once __DIR__.'/symfony-standard/app/AppCache.php';

use Leach\Container\SymfonyContainer;

$kernel = new AppKernel('prod', false);
// $kernel = new AppCache($kernel);
$kernel->loadClassCache();

return new SymfonyContainer($kernel);

redpajama_set_name: RedPajamaGithub


text:
require 'rails/railtie'

module SimpleSearchFilter
  class Railtie < Rails::Railtie
    #config.eager_load_namespaces << SimpleSearchFilter

    if Rails.env.development?
      config.watchable_dirs['lib'] = [:rb]
      config.watchable_dirs['lib/simple_search_filter'] = [:rb]
      config.watchable_dirs['app/views'] = [:rb]
    end

    initializer 'simple_search_filter' do |_app|
      # init my gem
    end

    config.after_initialize do

    end
  end
end


text:
'use strict';
// Detect the capabilities
var capabilities = require('./capabilities');

// This is the extensible list of constraint builders
var builders = {
  // This is the current (August 25, 2015) specification for MediaTrackConstraints
  standard: require('./constraints/standard'),
  // This is the legacy specification that is still used by Chrome
  legacy: require('./constraints/legacy')
};

/**
  Returns a constraints builder for the appropriate version of the getUserMedia constraints
  that are required
 **/
module.exports = function(cfg, opts) {
  var constraintsType = (opts || {}).constraintsType || capabilities.constraintsType || 'legacy';
  var builder = builders[constraintsType];
  if (!builder) throw new Error('Unsupported constraints builder');
  return builder(cfg, opts);
};


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('time_based', '0049_auto_20210112_1210'),
    ]

    operations = [
        migrations.AlterField(
            model_name='slotparticipant',
            name='participant',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='slot_participants', to='time_based.DateParticipant'),
        ),
        migrations.AlterField(
            model_name='timecontribution',
            name='slot_participant',
            field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='contributions', to='time_based.SlotParticipant'),
        ),
        migrations.AlterUniqueTogether(
            name='slotparticipant',
            unique_together=set([('slot', 'participant')]),
        ),
    ]


text:
local VolumetricConvolution, parent
   = torch.class('cudnn.VolumetricConvolution', 'nn.VolumetricConvolution')
local ffi = require 'ffi'
local errcheck = cudnn.errcheck

-- if you change the configuration of the module manually, call this
function VolumetricConvolution:resetWeightDescriptors()
   assert(torch.typename(self.weight) == 'torch.CudaTensor',
          'Only Cuda supported duh!')
   assert(torch.typename(self.bias) == 'torch.CudaTensor',
          'Only Cuda supported duh!')
   -- create filterDescriptor for weight
   self.weightDesc = ffi.new('struct cudnnFilterStruct*[1]')
   errcheck('cudnnCreateFilterDescriptor', self.weightDesc)
   local desc = torch.IntTensor({self.nOutputPlane, self.nInputPlane,
                             self.kT, self.kH, self.kW})
   errcheck('cudnnSetFilterNdDescriptor', self.weightDesc[0],
            'CUDNN_DATA_FLOAT', 5,
            desc:data());
   local function destroyWDesc(d)
      errcheck('cudnnDestroyFilterDescriptor', d[0]);
   end
   ffi.gc(self.weightDesc, destroyWDesc)

   -- create descriptor for bias
   self.biasDesc = cudnn.toDescriptor(self.bias:view(1, self.nOutputPlane,
                                                     1, 1))
end

function VolumetricConvolution:fastest(mode)
   if mode == nil then mode = true end
   self.fastest_mode = mode
   self.iSize = self.iSize or torch.LongStorage(4)
   self.iSize:fill(0)
   return self
end

function VolumetricConvolution:setMode(fmode, bdmode, bwmode)
   if fmode ~= nil then
      self.fmode = fmode
   end
   if bdmode ~= nil then
      self.bdmode = bdmode
   end
   if bwmode ~= nil then
      self.bwmode = bwmode
   end
   self.iSize = self.iSize or torch.LongStorage(4)
   self.iSize:fill(0)
   return self
end

function VolumetricConvolution:resetMode()
   self.fmode = nil
   self.bdmode = nil
   self.bwmode = nil
   return self
end

function VolumetricConvolution:createIODescriptors(input)
   local batch = true
   if input:dim() == 4 then
      input = input:view(1, input:size(1), input:size(2),
                         input:size(3), input:size(4))
      batch = false
   end
   assert(input:dim() == 5 and input:isContiguous());
   self.iSize = self.iSize or torch.LongStorage(4):fill(0)
   if not self.iDesc or not self.oDesc or
      input:size(1) ~= self.iSize[1] or input:size(2) ~= self.iSize[2]
   or input:size(3) ~= self.iSize[3] or input:size(4) ~= self.iSize[4]
   or input:size(5) ~= self.iSize[5] then
         self.iSize = input:size()
         -- resize gradInput
         if self.gradInput then self.gradInput:resizeAs(input); end
         -- create input descriptor
         self.iDesc = cudnn.toDescriptor(input)
         -- create conv descriptor
         self.convDesc = ffi.new('struct cudnnConvolutionStruct*[1]')
         errcheck('cudnnCreateConvolutionDescriptor', self.convDesc)
         local pad = torch.IntTensor({self.padT, self.padH, self.padW})
         local stride = torch.IntTensor({self.dT, self.dH, self.dW})
         local upscale = torch.IntTensor({1,1,1})
         errcheck('cudnnSetConvolutionNdDescriptor_v3', self.convDesc[0],
                  3, pad:data(),
                  stride:data(), upscale:data(), 'CUDNN_CROSS_CORRELATION',
          'CUDNN_DATA_FLOAT');
         local function destroyConvDesc(d)
            errcheck('cudnnDestroyConvolutionDescriptor', d[0]);
         end
         ffi.gc(self.convDesc, destroyConvDesc)

         -- create output descriptor and resize output
         local oSize = torch.IntTensor(5)
         local oSizeD = oSize:data()
         errcheck('cudnnGetConvolutionNdForwardOutputDim',
                  self.convDesc[0], self.iDesc[0],
                  self.weightDesc[0], 5, oSizeD)
         self.output:resize(oSize:long():storage())
         -- create descriptor for output
         self.oDesc = cudnn.toDescriptor(self.output)
         self.oDescBias = cudnn.toDescriptor(
            self.output:view(self.output:size(1),
                             self.output:size(2),
                             self.output:size(3)*self.output:size(4),
                             self.output:size(5)))
     -----------------------------------------------------------------
     local maxBufSize = 0
         -- create forwardAlgorithm descriptors for
         local algType = ffi.new("cudnnConvolutionFwdAlgo_t[?]", 1)
     local algSearchMode = 'CUDNN_CONVOLUTION_FWD_SPECIFY_WORKSPACE_LIMIT'
     local algWorkspaceLimit = self.workspace_limit
        or (self.nInputPlane * self.kT * self.kH * self.kW * 4) -- 4 = sizeof int/float.
     if self.fastest_mode  or cudnn.fastest == true then
         algSearchMode = 'CUDNN_CONVOLUTION_FWD_PREFER_FASTEST'
     end
     errcheck('cudnnGetConvolutionForwardAlgorithm',
              cudnn.getHandle(),
              self.iDesc[0], self.weightDesc[0],
              self.convDesc[0], self.oDesc[0],
              algSearchMode, algWorkspaceLimit, algType)
     algType[0] = self.fmode or algType[0]
         self.fwdAlgType = algType
         local bufSize = torch.LongTensor(1)
         errcheck('cudnnGetConvolutionForwardWorkspaceSize',
                  cudnn.getHandle(),
                  self.iDesc[0], self.weightDesc[0],
                  self.convDesc[0], self.oDesc[0],
                  algType[0], bufSize:data())
     maxBufSize = math.max(maxBufSize, bufSize[1])

     -- create backwardFilterAlgorithm descriptors for
         local algType = ffi.new("cudnnConvolutionBwdFilterAlgo_t[?]", 1)
     local algSearchMode = 'CUDNN_CONVOLUTION_BWD_FILTER_NO_WORKSPACE'
     local algWorkspaceLimit = self.workspace_limit
        or (self.nInputPlane * self.kT * self.kH * self.kW * 4) -- 4 = sizeof int/float.
     if self.fastest_mode  or cudnn.fastest == true then
         algSearchMode = 'CUDNN_CONVOLUTION_BWD_FILTER_PREFER_FASTEST'
     end
         errcheck('cudnnGetConvolutionBackwardFilterAlgorithm',
                  cudnn.getHandle(),
                  self.iDesc[0], self.oDesc[0],
                  self.convDesc[0], self.weightDesc[0],
                  algSearchMode, algWorkspaceLimit, algType)
     algType[0] = self.bwmode or algType[0]
         self.bwdFilterAlgType = algType
         local bufSize = torch.LongTensor(1)
         errcheck('cudnnGetConvolutionBackwardFilterWorkspaceSize',
                  cudnn.getHandle(),
                  self.iDesc[0], self.oDesc[0],
                  self.convDesc[0], self.weightDesc[0],
                  algType[0], bufSize:data())
     maxBufSize = math.max(maxBufSize, bufSize[1])

     -- create backwardDataAlgorithm descriptors for
         local algType = ffi.new("cudnnConvolutionBwdDataAlgo_t[?]", 1)
     local algSearchMode = 'CUDNN_CONVOLUTION_BWD_DATA_NO_WORKSPACE'
     local algWorkspaceLimit = self.workspace_limit
        or (self.nInputPlane * self.kT * self.kH * self.kW * 4) -- 4 = sizeof int/float.
     if self.fastest_mode  or cudnn.fastest == true then
         algSearchMode = 'CUDNN_CONVOLUTION_BWD_DATA_PREFER_FASTEST'
     end
         errcheck('cudnnGetConvolutionBackwardDataAlgorithm',
                  cudnn.getHandle(),
                  self.weightDesc[0], self.oDesc[0],
                  self.convDesc[0], self.iDesc[0],
                  algSearchMode, algWorkspaceLimit, algType)
     algType[0] = self.bdmode or algType[0]
         self.bwdDataAlgType = algType
         local bufSize = torch.LongTensor(1)
         errcheck('cudnnGetConvolutionBackwardDataWorkspaceSize',
                  cudnn.getHandle(),
                  self.weightDesc[0], self.oDesc[0],
                  self.convDesc[0], self.iDesc[0],
                  algType[0], bufSize:data())
     maxBufSize = math.max(maxBufSize, bufSize[1])

     self.extraBuffer = self.extraBuffer or cudnn.getSharedWorkspace()
     self.extraBufferSizeInBytes = self.extraBuffer:nElement() * 4 -- float
         if maxBufSize > self.extraBufferSizeInBytes then
           self.extraBuffer:resize(math.ceil(maxBufSize/4))
           self.extraBufferSizeInBytes = maxBufSize
         end

     -----------------------------------------------------------------
         if not batch then
            self.gradInput = self.gradInput:view(self.gradInput:size(2),
                                                 self.gradInput:size(3),
                                                 self.gradInput:size(4),
                                                 self.gradInput:size(5))
            self.output = self.output:view(self.output:size(2),
                                           self.output:size(3),
                                           self.output:size(4),
                                           self.output:size(5))
         end
   end
end

local one = torch.FloatTensor({1});
local zero = torch.FloatTensor({0});

local function makeContiguous(self, input, gradOutput)
   if not input:isContiguous() then
      self._input = self._input or input.new()
      self._input:typeAs(input):resizeAs(input):copy(input)
      input = self._input
   end
   if gradOutput and not gradOutput:isContiguous() then
      self._gradOutput = self._gradOutput or gradOutput.new()
      self._gradOutput:typeAs(gradOutput):resizeAs(gradOutput):copy(gradOutput)
      gradOutput = self._gradOutput
   end
   return input, gradOutput
end

function VolumetricConvolution:updateOutput(input)
   if not self.weightDesc then self:resetWeightDescriptors() end
   input = makeContiguous(self, input)
   self:createIODescriptors(input)
   errcheck('cudnnConvolutionForward', cudnn.getHandle(),
            one:data(),
            self.iDesc[0], input:data(),
            self.weightDesc[0], self.weight:data(),
            self.convDesc[0], self.fwdAlgType[0],
            self.extraBuffer:data(), self.extraBufferSizeInBytes,
            zero:data(),
            self.oDesc[0], self.output:data());
   errcheck('cudnnAddTensor', cudnn.getHandle(),
            one:data(),
            self.biasDesc[0], self.bias:data(), one:data(),
            self.oDescBias[0], self.output:data());
   return self.output
end

function VolumetricConvolution:updateGradInput(input, gradOutput)
   if not self.gradInput then return end
   input, gradOutput = makeContiguous(self, input, gradOutput)
   assert(gradOutput:dim() == 4 or gradOutput:dim() == 5,
          'gradOutput has to be a 4D or 5D tensor');
   if not self.weightDesc then self:resetWeightDescriptors() end
   self:createIODescriptors(input)
   errcheck('cudnnConvolutionBackwardData_v3', cudnn.getHandle(),
        one:data(),
        self.weightDesc[0], self.weight:data(),
        self.oDesc[0], gradOutput:data(),
        self.convDesc[0],
        self.bwdDataAlgType[0],
        self.extraBuffer:data(), self.extraBufferSizeInBytes,
        zero:data(),
        self.iDesc[0], self.gradInput:data());
   return self.gradInput
end

function VolumetricConvolution:accGradParameters(input, gradOutput, scale)
   self.scaleT = self.scaleT or torch.FloatTensor(1):fill(1.0)
   -- this line forces this member to always be on CPU (needed for cudnn)
   self.scaleT = self.scaleT:float()

   scale = scale or 1.0
   self.scaleT[1] = scale
   input, gradOutput = makeContiguous(self, input, gradOutput)
   assert(gradOutput:dim() == 4 or gradOutput:dim() == 5,
          'gradOutput has to be a 4D or 5D tensor');
   self:createIODescriptors(input)
   if not self.weightDesc then self:resetWeightDescriptors() end
   -- gradBias
   errcheck('cudnnConvolutionBackwardBias', cudnn.getHandle(),
            self.scaleT:data(),
            self.oDescBias[0], gradOutput:data(),
            one:data(),
            self.biasDesc[0], self.gradBias:data());
   -- gradWeight
   errcheck('cudnnConvolutionBackwardFilter_v3', cudnn.getHandle(),
        self.scaleT:data(),
        self.iDesc[0], input:data(),
        self.oDesc[0], gradOutput:data(),
        self.convDesc[0],
        self.bwdFilterAlgType[0],
        self.extraBuffer:data(), self.extraBufferSizeInBytes,
        one:data(),
        self.weightDesc[0], self.gradWeight:data());
end

function VolumetricConvolution:clearDesc()
   self.weightDesc = nil
   self.biasDesc = nil
   self.convDesc = nil
   self.iDesc = nil
   self.oDesc = nil
   self.oDescBias = nil
   self.fwdAlgType = nil
   self.bwdDataAlgType = nil
   self.bwdFilterAlgType = nil
   self.extraBuffer = nil
   self.extraBufferInBytes = nil
   self.scaleT = nil
end

function VolumetricConvolution:write(f)
   self:clearDesc()
   local var = {}
   for k,v in pairs(self) do
      var[k] = v
   end
   f:writeObject(var)
end

function VolumetricConvolution:clearState()
   self:clearDesc()
   nn.utils.clear(self, 'extraBuffer', '_input', '_gradOutput')
   return nn.Module.clearState(self)
end


text:
package pipeline.diagram.edit.helpers;

/**
 * @generated
 */
public class SourceEditHelper extends PipelineBaseEditHelper {
}


text:
#include "tensorflow/contrib/lite/experimental/microfrontend/lib/noise_reduction_util.h"

#include <stdio.h>

void NoiseReductionFillConfigWithDefaults(struct NoiseReductionConfig* config) {
  config->smoothing_bits = 10;
  config->even_smoothing = 0.025;
  config->odd_smoothing = 0.06;
  config->min_signal_remaining = 0.05;
}

int NoiseReductionPopulateState(const struct NoiseReductionConfig* config,
                                struct NoiseReductionState* state,
                                int num_channels) {
  state->smoothing_bits = config->smoothing_bits;
  state->odd_smoothing = config->odd_smoothing * (1 << kNoiseReductionBits);
  state->even_smoothing = config->even_smoothing * (1 << kNoiseReductionBits);
  state->min_signal_remaining =
      config->min_signal_remaining * (1 << kNoiseReductionBits);
  state->num_channels = num_channels;
  state->estimate = calloc(state->num_channels, sizeof(*state->estimate));
  if (state->estimate == NULL) {
    fprintf(stderr, "Failed to alloc estimate buffer\n");
    return 0;
  }
  return 1;
}

void NoiseReductionFreeStateContents(struct NoiseReductionState* state) {
  free(state->estimate);
}


text:
package com.javarush.task.task06.task0621;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/*
Родственные связи кошек
*/

public class Solution {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        String grendFatherName = reader.readLine();
        Cat catGrandFather = new Cat(grendFatherName);

        String grendMotherName = reader.readLine();
        Cat catGrandMother = new Cat(grendMotherName);

        String fatherName = reader.readLine();
        Cat catFather = new Cat(fatherName, null, catGrandFather);

        String motherName = reader.readLine();
        Cat catMother = new Cat(motherName, catGrandMother, null);

        String sonName = reader.readLine();
        Cat carSon = new Cat(sonName, catMother, catFather);

        String daughterName = reader.readLine();
        Cat catDaughter = new Cat(daughterName, catMother, catFather);

        System.out.println(catGrandFather);
        System.out.println(catGrandMother);

        System.out.println(catFather);
        System.out.println(catMother);

        System.out.println(carSon);
        System.out.println(catDaughter);
    }

    public static class Cat {
        private String name;
        private Cat mother;
        private Cat father;

        Cat(String name) {
            this.name = name;
        }

        Cat(String name, Cat mother, Cat father) {
            this.name = name;
            this.mother = mother;
            this.father = father;
        }

//        Cat(String name, Cat parent){
//            this.name=name;
//            this.father=father;
//        }

        @Override
        public String toString() {
            if (mother == null && father == null)
                return "Cat name is " + name + ", no mother" + ", no father";
            else if (mother != null && father == null)
                return "Cat name is " + name + ", mother is " + mother.name + ", no father";
            else if (mother == null && father != null)
                return "Cat name is " + name + ", no mother " + ", father is " + father.name;
            else return "Cat name is " + name + ", mother is " + mother.name + ", father is " + father.name;
        }
    }

}


text:
[![Latest Version on Packagist][ico-version]][link-packagist]
[![Software License][ico-license]](LICENSE.md)
[![Total Downloads][ico-downloads]][link-downloads]

# Install

Via Composer

``` bash
$ composer require am2studio/laravel-acl
```

## Service Provider

in ```config/app.php```

under ```'providers'``` add

```php
AM2Studio\LaravelAcl\LaravelAclServiceProvider::class
```

## Config and Migration

``` php
php artisan vendor:publish --provider="AM2Studio\LaravelACL\LaravelACLServiceProvider" --tag=config
php artisan vendor:publish --provider="AM2Studio\LaravelACL\LaravelACLServiceProvider" --tag=migrations
```

## Trait

In user model add following

```php
...
use AM2Studio\LaravelAcl\Traits\LaravelACLTrait;

class User extends Model {
    use LaravelACLTrait, ... ;
}
```

# Usage

## Creating roles

```php
use AM2Studio\LaravelACL\Models\Role;

$userRole = Role::create([
    'name' => 'User',
    'slug' => 'user',
    'description => '',
]);
```

## Attaching and detaching roles

```php
$user = User::find(1);
$user->attachRole($userRole);
$user->detachRole($userRole);
$user->detachAllRoles();
```
## Checking for role

```php
$user->is('user'); // Checkes if user has user role
$user->is('admin|user'); // Checks if user has user OR admin role
$user->is('admin|user', true); // Checks if user has user AND admin role
```

## Creating permissions

```php
use AM2Studio\LaravelACL\Models\Permssion;

$p = Role::create([
    'name' => 'Event edit',
    'slug' => 'event.edit',
    'description => '',
]);
```

## Attaching and detaching permissions

```php
$user = User::find(1);
$user->attachPermission($p);
$user->detachPermission($p);
$user->detachAllPermissions();

$role = Role::find(1);
$role->attachPermission($p);
$role->detachPermission($p);
$role->detachAllPermissions();
```

## Checking for role

```php
$user->can('event.edit'); // Checkes if user has permission
$user->can('event.edit|event.create'); // Checks if user has event.edit OR event.create permission
$user->can('event.edit|event.create', true); // Checks if user has event.edit AND event.create permission
```

## Model permissions

```php

$p2 = Role::create([
    'name' => 'Event edit',
    'slug' => 'event.edit',
    'description => '',
    'model' => 'event',
]);
$p3 = Role::create([
    'name' => 'Event edit',
    'slug' => 'event.edit',
    'description => '',
    'model' => 'event',
    'resource_id' => 1,
]);

$event = Event::find(1);

$user->attachPermisson($p2);
$user->attachPermisson($p3);

$user->allowed('event.edit', $event); // Checks if user has rights to Event model
$user->allowed('event.edit', $event, $event->id); // Checks if user has rights to Event model with selected id
```

## Blade Extensions

```php
@role('admin')
@endrole

@permission('edit.event')
@endpermission

@allowed('edit.event', $event)
@endallowed

@role('admin|user', 'all')
@endrole
```

## Change log

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

## Contributing

Please see [CONTRIBUTING](CONTRIBUTING.md) and [CONDUCT](CONDUCT.md) for details.

## Credits

- [Marko Šamec][link-author]
- [All Contributors][link-contributors]

## License

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

[ico-version]: https://img.shields.io/packagist/v/am2studio/laravel-acl.svg?style=flat-square
[ico-license]: https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square
[ico-travis]: https://img.shields.io/travis/am2studio/laravel-acl/master.svg?style=flat-square
[ico-scrutinizer]: https://img.shields.io/scrutinizer/coverage/g/am2studio/laravel-acl.svg?style=flat-square
[ico-code-quality]: https://img.shields.io/scrutinizer/g/am2studio/laravel-acl.svg?style=flat-square
[ico-downloads]: https://img.shields.io/packagist/dt/am2studio/laravel-acl.svg?style=flat-square

[link-packagist]: https://packagist.org/packages/am2studio/laravel-acl
[link-travis]: https://travis-ci.org/am2studio/laravel-acl
[link-scrutinizer]: https://scrutinizer-ci.com/g/am2studio/laravel-acl/code-structure
[link-code-quality]: https://scrutinizer-ci.com/g/am2studio/laravel-acl
[link-downloads]: https://packagist.org/packages/am2studio/laravel-acl
[link-author]: https://github.com/msamec
[link-contributors]: ../../contributors


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>ch.tkuhn</groupId>
  <artifactId>nanolytics</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>nanolytics</name>

  <properties>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <sesame.version>2.8.0</sesame.version>
    <timestamp>${maven.build.timestamp}</timestamp>
    <maven.build.timestamp.format>yyyy-MM-dd HH:mm</maven.build.timestamp.format>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.nanopub</groupId>
      <artifactId>nanopub</artifactId>
      <version>1.5</version>
    </dependency>
    <dependency>
      <groupId>com.beust</groupId>
      <artifactId>jcommander</artifactId>
      <version>1.32</version>
    </dependency>
    <dependency>
      <groupId>org.openrdf.sesame</groupId>
      <artifactId>sesame-repository-sail</artifactId>
      <version>${sesame.version}</version>
    </dependency>
    <dependency>
      <groupId>org.openrdf.sesame</groupId>
      <artifactId>sesame-sail-memory</artifactId>
      <version>${sesame.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>1.6.4</version>
    </dependency>
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.16</version>
    </dependency>
  </dependencies>
  <build>
    <plugins>
      <plugin>
        <artifactId>maven-dependency-plugin</artifactId>
        <version>2.8</version>
        <executions>
          <execution>
            <id>build-classpath</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>build-classpath</goal>
            </goals>
            <configuration>
              <outputFile>classpath.txt</outputFile>
            </configuration>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>pl.project13.maven</groupId>
        <artifactId>git-commit-id-plugin</artifactId>
        <version>2.1.12</version>
        <executions>
           <execution>
            <goals>
              <goal>revision</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>
</project>


text:
package org.apache.flink.runtime.operators.coordination;

import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.runtime.checkpoint.OperatorCoordinatorCheckpointContext;
import org.apache.flink.runtime.concurrent.ComponentMainThreadExecutor;
import org.apache.flink.runtime.executiongraph.Execution;
import org.apache.flink.runtime.executiongraph.ExecutionJobVertex;
import org.apache.flink.runtime.jobgraph.OperatorID;
import org.apache.flink.runtime.messages.Acknowledge;
import org.apache.flink.util.ExceptionUtils;
import org.apache.flink.util.FlinkException;
import org.apache.flink.util.FlinkRuntimeException;
import org.apache.flink.util.SerializedValue;
import org.apache.flink.util.TemporaryClassLoaderContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Nullable;

import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.BiFunction;
import java.util.function.Consumer;

import static org.apache.flink.util.Preconditions.checkNotNull;
import static org.apache.flink.util.Preconditions.checkState;

/**
 * The {@code OperatorCoordinatorHolder} holds the {@link OperatorCoordinator} and manages all its
 * interactions with the remaining components. It provides the context and is responsible for
 * checkpointing and exactly once semantics.
 *
 *
Exactly-one Semantics

 *
 *
The semantics are described under {@link OperatorCoordinator#checkpointCoordinator(long,
 * CompletableFuture)}.
 *
 *
Exactly-one Mechanism

 *
 *
This implementation can handle one checkpoint being triggered at a time. If another checkpoint
 * is triggered while the triggering of the first one was not completed or aborted, this class will
 * throw an exception. That is in line with the capabilities of the Checkpoint Coordinator, which
 * can handle multiple concurrent checkpoints on the TaskManagers, but only one concurrent
 * triggering phase.
 *
 *
The mechanism for exactly once semantics is as follows:
 *
 *

 *
Events pass through a special channel, the {@link OperatorEventValve}. If we are not
 *       currently triggering a checkpoint, then events simply pass through.
 *
Atomically, with the completion of the checkpoint future for the coordinator, this operator
 *       operator event valve is closed. Events coming after that are held back (buffered), because
 *       they belong to the epoch after the checkpoint.
 *
Once all coordinators in the job have completed the checkpoint, the barriers to the sources
 *       are injected. After that (see {@link #afterSourceBarrierInjection(long)}) the valves are
 *       opened again and the events are sent.
 *
If a task fails in the meantime, the events are dropped from the valve. From the
 *       coordinator's perspective, these events are lost, because they were sent to a failed
 *       subtask after it's latest complete checkpoint.
 *

 *
 *
IMPORTANT: A critical assumption is that all events from the scheduler to the Tasks are
 * transported strictly in order. Events being sent from the coordinator after the checkpoint
 * barrier was injected must not overtake the checkpoint barrier. This is currently guaranteed by
 * Flink's RPC mechanism.
 *
 *
Consider this example:
 *
 *

 * Coordinator one events: => a . . b . |trigger| . . |complete| . . c . . d . |barrier| . e . f
 * Coordinator two events: => . . x . . |trigger| . . . . . . . . . .|complete||barrier| . . y . . z
 *

 *
 *
Two coordinators trigger checkpoints at the same time. 'Coordinator Two' takes longer to
 * complete, and in the meantime 'Coordinator One' sends more events.
 *
 *
'Coordinator One' emits events 'c' and 'd' after it finished its checkpoint, meaning the
 * events must take place after the checkpoint. But they are before the barrier injection, meaning
 * the runtime task would see them before the checkpoint, if they were immediately transported.
 *
 *
'Coordinator One' closes its valve as soon as the checkpoint future completes. Events 'c' and
 * 'd' get held back in the valve. Once 'Coordinator Two' completes its checkpoint, the barriers are
 * sent to the sources. Then the valves are opened, and events 'c' and 'd' can flow to the tasks
 * where they are received after the barrier.
 *
 *
Concurrency and Threading Model

 *
 *
This component runs mainly in a main-thread-executor, like RPC endpoints. However, some
 * actions need to be triggered synchronously by other threads. Most notably, when the checkpoint
 * future is completed by the {@code OperatorCoordinator} implementation, we need to synchronously
 * suspend event-sending.
 */
public class OperatorCoordinatorHolder
        implements OperatorCoordinator, OperatorCoordinatorCheckpointContext {

    private final OperatorCoordinator coordinator;
    private final OperatorID operatorId;
    private final LazyInitializedCoordinatorContext context;
    private final OperatorEventValve eventValve;

    private final int operatorParallelism;
    private final int operatorMaxParallelism;

    private Consumer<Throwable> globalFailureHandler;
    private ComponentMainThreadExecutor mainThreadExecutor;

    private OperatorCoordinatorHolder(
            final OperatorID operatorId,
            final OperatorCoordinator coordinator,
            final LazyInitializedCoordinatorContext context,
            final OperatorEventValve eventValve,
            final int operatorParallelism,
            final int operatorMaxParallelism) {

        this.operatorId = checkNotNull(operatorId);
        this.coordinator = checkNotNull(coordinator);
        this.context = checkNotNull(context);
        this.eventValve = checkNotNull(eventValve);
        this.operatorParallelism = operatorParallelism;
        this.operatorMaxParallelism = operatorMaxParallelism;
    }

    public void lazyInitialize(
            Consumer<Throwable> globalFailureHandler,
            ComponentMainThreadExecutor mainThreadExecutor) {
        this.globalFailureHandler = globalFailureHandler;
        this.mainThreadExecutor = mainThreadExecutor;
        context.lazyInitialize(globalFailureHandler, mainThreadExecutor);
    }

    // ------------------------------------------------------------------------
    //  Properties
    // ------------------------------------------------------------------------

    public OperatorCoordinator coordinator() {
        return coordinator;
    }

    @Override
    public OperatorID operatorId() {
        return operatorId;
    }

    @Override
    public int maxParallelism() {
        return operatorMaxParallelism;
    }

    @Override
    public int currentParallelism() {
        return operatorParallelism;
    }

    // ------------------------------------------------------------------------
    //  OperatorCoordinator Interface
    // ------------------------------------------------------------------------

    @Override
    public void start() throws Exception {
        mainThreadExecutor.assertRunningInMainThread();
        checkState(context.isInitialized(), "Coordinator Context is not yet initialized");
        coordinator.start();
    }

    @Override
    public void close() throws Exception {
        coordinator.close();
        context.unInitialize();
    }

    @Override
    public void handleEventFromOperator(int subtask, OperatorEvent event) throws Exception {
        mainThreadExecutor.assertRunningInMainThread();
        coordinator.handleEventFromOperator(subtask, event);
    }

    @Override
    public void subtaskFailed(int subtask, @Nullable Throwable reason) {
        mainThreadExecutor.assertRunningInMainThread();
        coordinator.subtaskFailed(subtask, reason);
        eventValve.resetForTask(subtask);
    }

    @Override
    public void subtaskReset(int subtask, long checkpointId) {
        mainThreadExecutor.assertRunningInMainThread();
        coordinator.subtaskReset(subtask, checkpointId);
    }

    @Override
    public void checkpointCoordinator(long checkpointId, CompletableFuture<byte[]> result) {
        // unfortunately, this method does not run in the scheduler executor, but in the
        // checkpoint coordinator time thread.
        // we can remove the delegation once the checkpoint coordinator runs fully in the
        // scheduler's
        // main thread executor
        mainThreadExecutor.execute(() -> checkpointCoordinatorInternal(checkpointId, result));
    }

    @Override
    public void notifyCheckpointComplete(long checkpointId) {
        // unfortunately, this method does not run in the scheduler executor, but in the
        // checkpoint coordinator time thread.
        // we can remove the delegation once the checkpoint coordinator runs fully in the
        // scheduler's
        // main thread executor
        mainThreadExecutor.execute(() -> coordinator.notifyCheckpointComplete(checkpointId));
    }

    @Override
    public void notifyCheckpointAborted(long checkpointId) {
        // unfortunately, this method does not run in the scheduler executor, but in the
        // checkpoint coordinator time thread.
        // we can remove the delegation once the checkpoint coordinator runs fully in the
        // scheduler's
        // main thread executor
        mainThreadExecutor.execute(() -> coordinator.notifyCheckpointAborted(checkpointId));
    }

    @Override
    public void resetToCheckpoint(long checkpointId, @Nullable byte[] checkpointData)
            throws Exception {
        // ideally we would like to check this here, however this method is called early during
        // execution graph construction, before the main thread executor is set

        eventValve.reset();
        if (context != null) {
            context.resetFailed();
        }
        coordinator.resetToCheckpoint(checkpointId, checkpointData);
    }

    private void checkpointCoordinatorInternal(
            final long checkpointId, final CompletableFuture<byte[]> result) {
        mainThreadExecutor.assertRunningInMainThread();

        // synchronously!!!, with the completion, we need to shut the event valve
        result.whenComplete(
                (success, failure) -> {
                    if (failure != null) {
                        result.completeExceptionally(failure);
                    } else {
                        try {
                            eventValve.shutValve(checkpointId);
                            result.complete(success);
                        } catch (Exception e) {
                            result.completeExceptionally(e);
                        }
                    }
                });

        try {
            eventValve.markForCheckpoint(checkpointId);
            coordinator.checkpointCoordinator(checkpointId, result);
        } catch (Throwable t) {
            ExceptionUtils.rethrowIfFatalErrorOrOOM(t);
            result.completeExceptionally(t);
            globalFailureHandler.accept(t);
        }
    }

    // ------------------------------------------------------------------------
    //  Checkpointing Callbacks
    // ------------------------------------------------------------------------

    @Override
    public void afterSourceBarrierInjection(long checkpointId) {
        // this method is commonly called by the CheckpointCoordinator's executor thread (timer
        // thread).

        // we ideally want the scheduler main-thread to be the one that sends the blocked events
        // however, we need to react synchronously here, to maintain consistency and not allow
        // another checkpoint injection in-between (unlikely, but possible).
        // fortunately, the event-sending goes pretty much directly to the RPC gateways, which are
        // thread safe.

        // this will automatically be fixed once the checkpoint coordinator runs in the
        // scheduler's main thread executor
        eventValve.openValveAndUnmarkCheckpoint();
    }

    @Override
    public void abortCurrentTriggering() {
        // this method is commonly called by the CheckpointCoordinator's executor thread (timer
        // thread).

        // we ideally want the scheduler main-thread to be the one that sends the blocked events
        // however, we need to react synchronously here, to maintain consistency and not allow
        // another checkpoint injection in-between (unlikely, but possible).
        // fortunately, the event-sending goes pretty much directly to the RPC gateways, which are
        // thread safe.

        // this will automatically be fixed once the checkpoint coordinator runs in the
        // scheduler's main thread executor
        eventValve.openValveAndUnmarkCheckpoint();
    }

    // ------------------------------------------------------------------------
    //  Factories
    // ------------------------------------------------------------------------

    public static OperatorCoordinatorHolder create(
            SerializedValue<OperatorCoordinator.Provider> serializedProvider,
            ExecutionJobVertex jobVertex,
            ClassLoader classLoader)
            throws Exception {

        try (TemporaryClassLoaderContext ignored = TemporaryClassLoaderContext.of(classLoader)) {
            final OperatorCoordinator.Provider provider =
                    serializedProvider.deserializeValue(classLoader);
            final OperatorID opId = provider.getOperatorId();

            final BiFunction<
                            SerializedValue<OperatorEvent>, Integer, CompletableFuture<Acknowledge>>
                    eventSender =
                            (serializedEvent, subtask) -> {
                                final Execution executionAttempt =
                                        jobVertex.getTaskVertices()[subtask]
                                                .getCurrentExecutionAttempt();
                                return executionAttempt.sendOperatorEvent(opId, serializedEvent);
                            };

            return create(
                    opId,
                    provider,
                    eventSender,
                    jobVertex.getName(),
                    jobVertex.getGraph().getUserClassLoader(),
                    jobVertex.getParallelism(),
                    jobVertex.getMaxParallelism());
        }
    }

    @VisibleForTesting
    static OperatorCoordinatorHolder create(
            final OperatorID opId,
            final OperatorCoordinator.Provider coordinatorProvider,
            final BiFunction<
                            SerializedValue<OperatorEvent>, Integer, CompletableFuture<Acknowledge>>
                    eventSender,
            final String operatorName,
            final ClassLoader userCodeClassLoader,
            final int operatorParallelism,
            final int operatorMaxParallelism)
            throws Exception {

        final OperatorEventValve valve = new OperatorEventValve(eventSender);

        final LazyInitializedCoordinatorContext context =
                new LazyInitializedCoordinatorContext(
                        opId, valve, operatorName, userCodeClassLoader, operatorParallelism);

        final OperatorCoordinator coordinator = coordinatorProvider.create(context);

        return new OperatorCoordinatorHolder(
                opId, coordinator, context, valve, operatorParallelism, operatorMaxParallelism);
    }

    // ------------------------------------------------------------------------
    //  Nested Classes
    // ------------------------------------------------------------------------

    /**
     * An implementation of the {@link OperatorCoordinator.Context}.
     *
     *
All methods are safe to be called from other threads than the Scheduler's and the
     * JobMaster's main threads.
     *
     *
Implementation note: Ideally, we would like to operate purely against the scheduler
     * interface, but it is not exposing enough information at the moment.
     */
    private static final class LazyInitializedCoordinatorContext
            implements OperatorCoordinator.Context {

        private static final Logger LOG =
                LoggerFactory.getLogger(LazyInitializedCoordinatorContext.class);

        private final OperatorID operatorId;
        private final OperatorEventValve eventValve;
        private final String operatorName;
        private final ClassLoader userCodeClassLoader;
        private final int operatorParallelism;

        private Consumer<Throwable> globalFailureHandler;
        private Executor schedulerExecutor;

        private volatile boolean failed;

        public LazyInitializedCoordinatorContext(
                final OperatorID operatorId,
                final OperatorEventValve eventValve,
                final String operatorName,
                final ClassLoader userCodeClassLoader,
                final int operatorParallelism) {
            this.operatorId = checkNotNull(operatorId);
            this.eventValve = checkNotNull(eventValve);
            this.operatorName = checkNotNull(operatorName);
            this.userCodeClassLoader = checkNotNull(userCodeClassLoader);
            this.operatorParallelism = operatorParallelism;
        }

        void lazyInitialize(Consumer<Throwable> globalFailureHandler, Executor schedulerExecutor) {
            this.globalFailureHandler = checkNotNull(globalFailureHandler);
            this.schedulerExecutor = checkNotNull(schedulerExecutor);
        }

        void unInitialize() {
            this.globalFailureHandler = null;
            this.schedulerExecutor = null;
        }

        boolean isInitialized() {
            return schedulerExecutor != null;
        }

        private void checkInitialized() {
            checkState(isInitialized(), "Context was not yet initialized");
        }

        void resetFailed() {
            failed = false;
        }

        @Override
        public OperatorID getOperatorId() {
            return operatorId;
        }

        @Override
        public CompletableFuture<Acknowledge> sendEvent(
                final OperatorEvent evt, final int targetSubtask) {
            checkInitialized();

            if (targetSubtask < 0 || targetSubtask >= currentParallelism()) {
                throw new IllegalArgumentException(
                        String.format(
                                "subtask index %d out of bounds [0, %d).",
                                targetSubtask, currentParallelism()));
            }

            final SerializedValue<OperatorEvent> serializedEvent;
            try {
                serializedEvent = new SerializedValue<>(evt);
            } catch (IOException e) {
                // we do not expect that this exception is handled by the caller, so we make it
                // unchecked so that it can bubble up
                throw new FlinkRuntimeException("Cannot serialize operator event", e);
            }

            return eventValve.sendEvent(serializedEvent, targetSubtask);
        }

        @Override
        public void failJob(final Throwable cause) {
            checkInitialized();
            if (failed) {
                LOG.warn(
                        "Ignoring the request to fail job because the job is already failing. "
                                + "The ignored failure cause is",
                        cause);
                return;
            }
            failed = true;

            final FlinkException e =
                    new FlinkException(
                            "Global failure triggered by OperatorCoordinator for '"
                                    + operatorName
                                    + "' (operator "
                                    + operatorId
                                    + ").",
                            cause);

            schedulerExecutor.execute(() -> globalFailureHandler.accept(e));
        }

        @Override
        public int currentParallelism() {
            return operatorParallelism;
        }

        @Override
        public ClassLoader getUserCodeClassloader() {
            return userCodeClassLoader;
        }
    }
}


text:
package org.gradoop.flink.model.impl.layouts.gve.indexed;

import org.gradoop.flink.model.api.layouts.GraphCollectionLayoutFactory;
import org.gradoop.flink.model.impl.layouts.GraphCollectionLayoutFactoryTest;
import org.gradoop.flink.util.GradoopFlinkConfig;

public class IndexedGVECollectionLayoutFactoryTest extends GraphCollectionLayoutFactoryTest {
  @Override
  protected GraphCollectionLayoutFactory getFactory() {
    GraphCollectionLayoutFactory graphCollectionLayoutFactory = new IndexedGVECollectionLayoutFactory();
    GradoopFlinkConfig config = GradoopFlinkConfig.createConfig(getExecutionEnvironment());
    config.setGraphCollectionLayoutFactory(graphCollectionLayoutFactory);
    return graphCollectionLayoutFactory;
  }

}


text:
var deleteMediaPath = document.getElementById('delete-media-path').value;
var page = document.getElementById('page').value;
var baseUrl = document.getElementById('base-url').value;
var siteId = document.getElementById('site-id').value;
var isTouch = 'ontouchstart' in document.documentElement;

$(document).ready(function() {
    $('select').selectpicker();
    $(".select .dropdown-toggle").addClass('btn-info');
    $(".dropdown-menu").addClass('dropdown-inverse');
    $(".dropdown-arrow").addClass('dropdown-arrow-inverse');
});

$(".quick-delete-action").on('click', function(){
    var id = $(this).attr('data-id');
    if(confirm('Are you sure you want to delete this?')){
        deleteMedia(id);
    }
});

if(!isTouch){
    $(".checkbox-container td").mouseover(function(){
        $(this).find('.quick-action').show();
    });
    $(".checkbox-container td").mouseout(function(){
        $(this).find('.quick-action').hide();
    });
}

$('.btn-checkbox-action').on('click', function(){
    var token = document.getElementById('token').value;
    var action = $(this).attr('data-action');
    var isChecked = checkIfNone();
    if(isChecked == 0){
        alert('please select a media item');
        return 0;
    }
    var ids = getCheckedIds();
    switch (action){
        case 'delete':
            ids.forEach(function(id){
                deleteMedia(id, token);
            }, function(){
                $("#notices").html('
Deleted
');
                $("#content-type-alert").show(0).delay(1000).fadeOut(1000);
            });
            break;
        case 'edit':
            var id = ids.length == 1 ? ids[0] : ids[1] ;
            window.location.href = baseUrl + '/app/media/'+siteId+'/'+id;
            break;
        default:
            alert('action not found');
            break;
    }
});

$(".pag-next").on('click', function(){
    page++;
    loadData(getParams());
});

$(".pag-previous").on('click', function(){
    page--;
    loadData(getParams());
});

$(".load-data-form").submit(function(event){
    event.preventDefault();
    loadData(getParams());
})

$(".load-data").on('click', function(){
    loadData(getParams());
});

function loadData(params){
    window.location = window.location.pathname + queryStringParams(params);
}

function queryStringParams(params){
    var str = '?page='+page;
    if(params.siteId){str = str+'&siteId='+encodeURIComponent(params.siteId)}
    if(params.type){str = str+'&type='+encodeURIComponent(params.type)}
    if(params.startDate){str = str+'&startDate='+encodeURIComponent(params.startDate)}
    if(params.endDate){str = str+'&endDate='+encodeURIComponent(params.endDate)}
    if(params.association){str = str+'&association='+encodeURIComponent(params.association)}
    if(params.search){str = str+'&search='+encodeURIComponent(params.search)}
    return str;
}

function getParams(){
    objParams = {};
    objParams.siteId = document.getElementById('site-id').value;
    objParams.type = document.getElementById('input-type').value;
    objParams.startDate = document.getElementById('input-start-date').value;
    objParams.endDate = document.getElementById('input-end-date').value;
    objParams.association = document.getElementById('input-association').value;
    objParams.search = document.getElementById('input-search').value;
    return objParams;
}

function deleteMedia(id, token){
    $.post(deleteMediaPath, {id: id, token:token}, function(data, textStatus, xhr) {
        if(textStatus == 'success'){
            $('#tr-' + id).hide('slow').remove();
            $("#notices").html('
Removing...
');
            $("#content-type-alert").show(0).delay(1000).fadeOut(1000);
        }else{
           alert('Deletion failed, please try again. If the problem persists please contact customer support.');
        }
    });
}


text:
<!DOCTYPE html>
<html>
	<head>
		<title>Sprite_circle</title>
		<meta charset="utf-8">
		<script type="text/javascript">
			var sprite = new Image();
			var canvas, ctx;
			var state = 0;
			var position = {'x':0,'y':0};
			var states = [
					{'left':0,'top':0,'width':200,'height':200},
					{'left':200,'top':0,'width':200,'height':200},
					{'left':400,'top':0,'width':200,'height':200},
					{'left':600,'top':0,'width':200,'height':200},
					{'left':800,'top':0,'width':200,'height':200},
					{'left':1000,'top':0,'width':200,'height':200},
					{'left':800,'top':0,'width':200,'height':200},
					{'left':600,'top':0,'width':200,'height':200},
					{'left':400,'top':0,'width':200,'height':200},
					{'left':200,'top':0,'width':200,'height':200}
				];

			var update = function(delta){
				ctx.clearRect(0, 0, canvas.width, canvas.height);
				ctx.drawImage(this.sprite, states[state].left, states[state].top, states[state].width, states[state].height, position.x, position.y, states[state].width, states[state].height);
				state++;
				state = state > states.length-1 ? 0 : state;
			};

			window.addEventListener('load', function(){
				canvas = document.getElementById('canvas');
				ctx = canvas.getContext('2d');
				sprite.addEventListener('load', function(){
					setInterval(update, 100);
				}, false);
				sprite.src = 'sprite_circle.png';
			}, false);
		</script>
	</head>
	<body>
		<canvas id="canvas" width="400" height="300" style="border:1px solid black;"></canvas>
	</body>
</html>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MusicStoreModels
{
    public partial class Album
    {
        public void UpdateWith(Album album)
        {
            if (!string.IsNullOrWhiteSpace(album.AlbumTitle))
            {
                this.AlbumTitle = album.AlbumTitle;
            }

            if (album.AlbumYear.HasValue)
            {
                this.AlbumYear = album.AlbumYear;
            }

            if (!string.IsNullOrWhiteSpace(album.Producer))
            {
                this.Producer = album.Producer;
            }
        }
    }
}


text:
/*global angular*/
(function () {
    angular
        .module('simplAdmin.catalog')
        .controller('CategoryFormCtrl', CategoryFormCtrl);

    /* @ngInject */
    function CategoryFormCtrl($q, $state, $stateParams, categoryService, translateService) {
        var vm = this,
            tableStateRef;
        vm.translate = translateService;
        vm.category = { isPublished: true };
        vm.categories = [];
        vm.products = [];
        vm.categoryId = $stateParams.id;
        vm.isEditMode = vm.categoryId > 0;

        vm.save = function save() {
            var promise;
            // ng-upload will post null as text
            vm.category.parentId = vm.category.parentId === null ? '' : vm.category.parentId;
            vm.category.description = vm.category.description === null ? '' : vm.category.description;

            if (vm.isEditMode) {
                promise = categoryService.editCategory(vm.category);
            } else {
                promise = categoryService.createCategory(vm.category);
            }

            promise
                .then(function (result) {
                        $state.go('category');
                    })
                .catch(function (response) {
                    var error = response.data;
                    vm.validationErrors = [];
                    if (error && angular.isObject(error)) {
                        for (var key in error) {
                            vm.validationErrors.push(error[key][0]);
                        }
                    } else {
                        vm.validationErrors.push('Could not add category.');
                    }
                });
        };

        vm.getProducts = function getProducts(tableState) {
            if (!vm.categoryId) {
                return;
            }

            tableStateRef = tableState;
            vm.isLoading = true;
            categoryService.getProducts(vm.categoryId, tableState).then(function (result) {
                vm.products = result.data.items;
                tableState.pagination.numberOfPages = result.data.numberOfPages;
                vm.isLoading = false;
            });
        };

        vm.editProduct = function editProduct(product) {
            product.isEditing = true;
            product.editingIsFeaturedProduct = product.isFeaturedProduct;
            product.editingDisplayOrder = product.displayOrder;
        }

        vm.saveProduct = function saveProduct(product) {
            var productCategory = {
                'id' : product.id,
                'isFeaturedProduct' : product.editingIsFeaturedProduct,
                'displayOrder' : product.displayOrder
            };
            categoryService.saveProduct(productCategory).then(function () {
                product.isEditing = false;
                product.isFeaturedProduct = product.editingIsFeaturedProduct;
                product.displayOrder = product.editingDisplayOrder;
            });
        }

        function init() {
            if (vm.isEditMode) {
                $q.all([
                        categoryService.getCategories(),
                        categoryService.getCategory(vm.categoryId)
                    ])
                    .then(function (result) {
                        var index;
                        vm.categories = result[0].data;
                        vm.category = result[1].data;

                        index = vm.categories.map(function (item) {
                            return item.id;
                        }).indexOf(vm.category.id);
                        vm.categories.splice(index, 1);
                    });
            }
            else {
                categoryService.getCategories().then(function (result) {
                    vm.categories = result.data;
                });
            }
        }

        init();
    }
})();


text:
package org.mrgeo.data;

import org.mrgeo.mapreduce.splitters.TiledInputSplit;

import java.util.List;

public class SplitIterator
{
private int splitIndex;
private List<TiledInputSplit> splits;
private SplitVisitor visitor;

public SplitIterator(List<TiledInputSplit> splits, SplitVisitor visitor)
{
  this.splits = splits;
  splitIndex = 0;
  this.visitor = visitor;
}

public TiledInputSplit next()
{
  if (splitIndex > splits.size())
  {
    return null;
  }
  while (splitIndex < splits.size())
  {
    TiledInputSplit split = splits.get(splitIndex);
    splitIndex++;
    if (visitor != null)
    {
      if (visitor.accept(split))
      {
        return split;
      }
    }
    else
    {
      return split;
    }
  }
  return null;
}
}


text:
<?php
/**
 * The Footer widget areas.
 *
 * @package Catch Themes
 * @subpackage Catch Everest
 * @since Catch Everest 1.0
 */
?>

<?php
	/* The footer widget area is triggered if any of the areas
	 * have widgets. So let's check that first.
	 *
	 * If none of the sidebars have widgets, then let's bail early.
	 */
	if (   ! is_active_sidebar( 'sidebar-2'  )
		&& ! is_active_sidebar( 'sidebar-3' )
		&& ! is_active_sidebar( 'sidebar-4'  )
	)
		return;
	// If we get this far, we have widgets. Let do this.
?>

    <div id="supplementary" <?php catcheverest_footer_sidebar_class(); ?>>
        <?php if ( is_active_sidebar( 'sidebar-2' ) ) : ?>

            <?php dynamic_sidebar( 'sidebar-2' ); ?>

        <?php endif; ?>

        <?php if ( is_active_sidebar( 'sidebar-3' ) ) : ?>

            <?php dynamic_sidebar( 'sidebar-3' ); ?>

        <?php endif; ?>

        <?php if ( is_active_sidebar( 'sidebar-4' ) ) : ?>

            <?php dynamic_sidebar( 'sidebar-4' ); ?>

        <?php endif; ?>


text:
package rappsilber.ms.statistics.generator;

import rappsilber.ms.sequence.AminoAcid;
import rappsilber.ms.sequence.Peptide;
import rappsilber.ms.sequence.ions.BIon;
import rappsilber.ms.sequence.ions.loss.BIonWaterGain;
import rappsilber.ms.sequence.ions.loss.Loss;
import rappsilber.ms.spectra.SpectraPeak;
import rappsilber.ms.spectra.annotation.SpectraPeakAnnotation;
import rappsilber.ms.spectra.annotation.SpectraPeakMatchedFragment;
import rappsilber.ms.spectra.match.MatchedBaseFragment;
import rappsilber.ms.spectra.match.MatchedFragmentCollection;
import rappsilber.ms.spectra.match.MatchedXlinkedPeptide;
import rappsilber.utils.CountOccurence;

/**
 * looks for BIons that have a gain of water - suppostly that can happen at the B(n-1) ion
 * @author Lutz Fischer <l.fischer@ed.ac.uk>
 */
public class WaterGain extends AbstractStatistic{
    //StatisticsFragementationSiteSingle

    CountOccurence<Integer> BIonOccurence = new CountOccurence<Integer>();
    CountOccurence<Integer> BIonOccurenceReverse = new CountOccurence<Integer>();
    CountOccurence<Integer> BIonOccurenceOnly = new CountOccurence<Integer>();
    CountOccurence<Integer> BIonOccurenceReverseOnly = new CountOccurence<Integer>();
    int count = 0;

    public WaterGain() {
    }

    public void countSpectraMatch(MatchedXlinkedPeptide match) {
        MatchedFragmentCollection MatchedFragments = new MatchedFragmentCollection(match.getSpectrum().getPrecurserCharge());
        for (SpectraPeak sp : match.getSpectrum().getPeaks()) {
            for (SpectraPeakMatchedFragment mf : sp.getMatchedAnnotation()) {
                MatchedFragments.add(mf.getFragment(), mf.getCharge(), sp);
                if (mf.getFragment().isClass(BIonWaterGain.class)) {
                    count++;
                }
            }
        }

        for (MatchedBaseFragment mbf : MatchedFragments) {
            for (Loss l : mbf.getLosses().keySet()) {

                SpectraPeak sp = mbf.getLosses().get(l);
                // check only, if it is the only "loss" at the BIon
                if (l instanceof BIonWaterGain && l.getParentFragment() instanceof BIon
                        //&& mbf.isBaseFragmentFound() // and a B-Ion without loss was found
                        &&  sp.hasAnnotation(SpectraPeakAnnotation.monoisotop)) { // and is the monoisotopic peak of a cluster
                        BIonOccurence.add((int)l.length());
                        BIonOccurenceReverse.add(l.getPeptide().length() - l.length());
                        if (sp.getMatchedFragments().size() == 1) {
                            BIonOccurenceOnly.add((int)l.length());
                            BIonOccurenceReverseOnly.add(l.getPeptide().length() - l.length());
                        }

                }

            }
        }
    }

    public String getTable() {
        StringBuffer sb = new StringBuffer();
        for (Integer i : BIonOccurence.getCountedObjects()) {
            sb.append("B" + i + "\t" + BIonOccurence.count(i) + "\n");
        }

        for (Integer i : BIonOccurenceReverse.getCountedObjects()) {
            sb.append("B(n - " + i + ")\t" + BIonOccurenceReverse.count(i) + "\n");
        }

        for (Integer i : BIonOccurenceOnly.getCountedObjects()) {
            sb.append("Only B" + i + "\t" + BIonOccurenceOnly.count(i) + "\n");
        }

        for (Integer i : BIonOccurenceReverseOnly.getCountedObjects()) {
            sb.append("Only B(n - " + i + ")\t" + BIonOccurenceReverseOnly.count(i) + "\n");
        }

        return sb.toString();

    }

}


text:
import {createPlugin, PatchDataWithResult, Patcher, React, Utils} from "dium";
import {Attachment} from "@dium/modules";
import {SwitchItem, MessageFooter, Embed} from "@dium/components";
import {Settings} from "./settings";
import {Hider, AccessoryType} from "./hider";
import {css} from "./styles.module.scss";

interface AttachmentProps extends Record<string, any> {
    attachment: Attachment;
    canRemoveAttachment?: boolean;
}

export default createPlugin({
    start() {
        Patcher.after(Embed.prototype as InstanceType<typeof Embed>, "render", ({result, context}) => {
            const {embed} = context.props;
            return (
                <Hider
                    type={AccessoryType.Embed}
                    placeholder={embed.provider?.name}
                >{result}</Hider>
            );
        }, {name: "Embed render"});

        Patcher.after(MessageFooter.prototype, "renderAttachments", ({result}: PatchDataWithResult<JSX.Element>) => {
            const attachments = Utils.queryTreeAll(result, (node) => node?.props?.attachment);
            for (const attachment of attachments) {
                Utils.hookFunctionComponent<AttachmentProps>(
                    attachment,
                    (result, {attachment, canRemoveAttachment}) => (
                        <Hider
                            type={AccessoryType.Attachment}
                            placeholder={attachment.filename}
                            marginCorrect={canRemoveAttachment}
                        >{result}</Hider>
                    ));
            }
        }, {name: "MessageFooter renderAttachments"});
    },
    styles: css,
    Settings,
    SettingsPanel: () => {
        const [{hideByDefault}, setSettings] = Settings.useState();

        return (
            <SwitchItem
                note="Collapse all embeds & attachments initially."
                hideBorder
                value={hideByDefault}
                onChange={(checked) => setSettings({hideByDefault: checked})}
            >Collapse by default</SwitchItem>
        );
    }
});


text:
package org.kuali.rice.krad.datadictionary.validation.charlevel;

import org.junit.Test;
import org.kuali.rice.kns.datadictionary.validation.charlevel.AnyCharacterValidationPattern;
import org.kuali.rice.krad.datadictionary.validation.ValidationTestUtils;
import org.kuali.rice.test.BaseRiceTestCase;

public class AnyCharacterValidationPatternTest extends BaseRiceTestCase {
    private AnyCharacterValidationPattern pattern;

    @Override
    public void setUp() throws Exception {
        super.setUp();

        pattern = new AnyCharacterValidationPattern();
    }

    @Test public final void testMatch_allowDefault() {
        boolean[] expected = { true, // ""
                true, // "!!!"
                true, // "[a-9]"
                true, // "^A-Z"
                true, // "abc"
                false, // "a bc"
                true, // "a_bc"
                true, // "123"
                false, // "12 3"
                true, // "12_3"
                true, // "a1b2c3"
                true, // "a1b2_c3"
                false, // "a 1b2c3"
                false, // "a 1b2_c3"
                true, //"foo.bar"
                true, //"foo.bar_baz"
                false, //".bar_foo baz"
        };

        ValidationTestUtils.assertPatternMatches(pattern, expected);
    }

    @Test public final void testMatch_allowWhitespace() {
        boolean[] expected = { true, // ""
                true, // "!!!"
                true, // "[a-9]"
                true, // "^A-Z"
                true, // "abc"
                true, // "a bc"
                true, // "a_bc"
                true, // "123"
                true, // "12 3"
                true, // "12_3"
                true, // "a1b2c3"
                true, // "a1b2_c3"
                true, // "a 1b2c3"
                true, // "a 1b2_c3"
                true, //"foo.bar"
                true, //"foo.bar_baz"
                true, //".bar_foo baz"
        };

        pattern.setAllowWhitespace(true);
        ValidationTestUtils.assertPatternMatches(pattern, expected);
    }
}


text:
/**
 * Created by Michael Ritter on 15.12.2015.
 */
package net.dv8tion.jda.entities.impl;

import net.dv8tion.jda.JDA;
import net.dv8tion.jda.entities.Message;
import net.dv8tion.jda.entities.User;
import net.dv8tion.jda.handle.EntityBuilder;
import org.json.JSONException;
import org.json.JSONObject;

import java.time.OffsetDateTime;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class MessageImpl implements Message
{
    private final String id;
    private final JDAImpl api;
    private List<User> mentionedUsers = new LinkedList<>();
    private boolean mentionsEveryone = false;
    private boolean isTTS = false;
    private OffsetDateTime time;
    private OffsetDateTime editedTime = null;
    private User author;
    private String channelId;
    private boolean isPrivate;
    private String content;
    private String subContent = null;

    public MessageImpl(String id, JDAImpl api)
    {
        this.id = id;
        this.api = api;
    }

    @Override
    public JDA getJDA()
    {
        return api;
    }

    @Override
    public String getId()
    {
        return id;
    }

    @Override
    public List<User> getMentionedUsers()
    {
        return Collections.unmodifiableList(mentionedUsers);
    }

    @Override
    public boolean mentionsEveryone()
    {
        return mentionsEveryone;
    }

    @Override
    public OffsetDateTime getTime()
    {
        return time.plusSeconds(0L);
    }

    @Override
    public boolean isEdited()
    {
        return editedTime != null;
    }

    @Override
    public OffsetDateTime getEditedTimestamp()
    {
        return editedTime.plusSeconds(0L);
    }

    @Override
    public User getAuthor()
    {
        return author;
    }

    @Override
    public String getContent()
    {
        if (subContent == null)
        {
            String tmp = content;
            for (User user : mentionedUsers)
            {
                tmp = tmp.replace("<@" + user.getId() + ">", "@" + user.getUsername());
            }
            subContent = tmp;
        }
        return subContent;
    }

    @Override
    public String getRawContent()
    {
        return content;
    }

    @Override
    public String getChannelId()
    {
        return channelId;
    }

    @Override
    public boolean isPrivate()
    {
        return isPrivate;
    }

    @Override
    public boolean isTTS()
    {
        return isTTS;
    }

    @Override
    public Message updateMessage(String newContent)
    {
        try
        {
            JSONObject response = api.getRequester().patch("https://discordapp.com/api/channels/" + channelId + "/messages/" + getId(), new JSONObject().put("content", newContent));
            return new EntityBuilder(api).createMessage(response);
        }
        catch (JSONException ex)
        {
            ex.printStackTrace();
            return null;
        }
    }

    @Override
    public void deleteMessage()
    {
        api.getRequester().delete("https://discordapp.com/api/channels/" + channelId + "/messages/" + getId());
    }

    public MessageImpl setMentionedUsers(List<User> mentionedUsers)
    {
        this.mentionedUsers = mentionedUsers;
        return this;
    }

    public MessageImpl setMentionsEveryone(boolean mentionsEveryone)
    {
        this.mentionsEveryone = mentionsEveryone;
        return this;
    }

    public MessageImpl setTTS(boolean TTS)
    {
        isTTS = TTS;
        return this;
    }

    public MessageImpl setTime(OffsetDateTime time)
    {
        this.time = time;
        return this;
    }

    public MessageImpl setEditedTime(OffsetDateTime editedTime)
    {
        this.editedTime = editedTime;
        return this;
    }

    public MessageImpl setAuthor(User author)
    {
        this.author = author;
        return this;
    }

    public MessageImpl setIsPrivate(boolean isPrivate)
    {
        this.isPrivate = isPrivate;
        return this;
    }

    public MessageImpl setChannelId(String channelId)
    {
        this.channelId = channelId;
        return this;
    }

    public MessageImpl setContent(String content)
    {
        this.content = content;
        return this;
    }

    public void acknowledge()
    {
        api.getRequester().post("https://discordapp.com/api/channels/"+channelId+"/messages/"+id+"/ack", new JSONObject());
    }
}


text:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using DG.Tweening;

public class FadeScreen : MonoBehaviour
{
	Image img;
	private float duration = .5f;

	void Awake()
	{
		img = GetComponent<Image>();
		FadeIn(1, 1, 1, 1);
	}

	public void FadeOut(int red, int green, int blue, int alpha)
	{
		img.color = new Color(red, green, blue, alpha);
		img.DOFade(1, duration);
	}

	public void FadeIn(int red, int green, int blue, int alpha)
	{
		img.color = new Color(red, green, blue, alpha);
		img.DOFade(0, duration);
	}
}


text:
#include "thread.hpp"
#include "../time/time.hpp"
#include "../common/compat.hpp"

namespace ThreadStatic
{
	static DWORD WINAPI EntryPoint(LPVOID data)
	{
		sprawl::threading::Thread* thread = reinterpret_cast<sprawl::threading::Thread*>(data);
		sprawl::threading::RunThread(thread);
		return 0;
	}
}

/*static*/ sprawl::threading::ThreadDestructionBehavior sprawl::threading::Thread::ms_defaultDestructionBehavior = sprawl::threading::ThreadDestructionBehavior::Abort;

int64_t sprawl::threading::Handle::GetUniqueId() const
{
	return GetThreadId(m_thread);
}

void sprawl::threading::Thread::Start()
{
	m_handle.GetNativeHandle() = CreateThread( nullptr, 0, &ThreadStatic::EntryPoint, this, 0, nullptr);
	if(m_handle.GetNativeHandle() != INVALID_HANDLE_VALUE)
	{
		if(m_threadName != nullptr)
		{
			const DWORD MS_VC_EXCEPTION = 0x406D1388;

#pragma pack(push,8)
			struct THREADNAME_INFO
			{
				DWORD dwType; // Must be 0x1000.
				LPCSTR szName; // Pointer to name (in user addr space).
				DWORD dwThreadID; // Thread ID (-1=caller thread).
				DWORD dwFlags; // Reserved for future use, must be zero.
			};
#pragma pack(pop)

			THREADNAME_INFO info;
			info.dwType = 0x1000;
			info.szName = m_threadName;
			info.dwThreadID = GetThreadId(m_handle.GetNativeHandle());
			info.dwFlags = 0;

			__try
			{
				RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info);
			}
			__except(EXCEPTION_EXECUTE_HANDLER)
			{
			}
		}
	}
}

void sprawl::threading::Thread::PlatformJoin()
{
	WaitForSingleObject(m_handle.GetNativeHandle(), INFINITE);
}

void sprawl::threading::Thread::PlatformDetach()
{
	CloseHandle(m_handle.GetNativeHandle());
}

sprawl::threading::Handle sprawl::this_thread::GetHandle()
{
	return sprawl::threading::Handle(GetCurrentThread());
}

sprawl::threading::Thread::~Thread()
{
	if(m_destructionBehavior == ThreadDestructionBehavior::Default)
	{
		m_destructionBehavior = ms_defaultDestructionBehavior;
	}

	if(Joinable())
	{
#if SPRAWL_EXCEPTIONS_ENABLED
		if(m_exception)
		{
			try
			{
				std::rethrow_exception(m_exception);
			}
			catch(std::exception& e)
			{
				fprintf(stderr, "Thread %" SPRAWL_I64FMT "d destroyed without being joined after thread was terminated with a std::exception. e.what(): %s\n", GetHandle().GetUniqueId(), e.what());
			}
			catch(...)
			{
				fprintf(stderr, "Thread %" SPRAWL_I64FMT "d destroyed without being joined after thread was terminated with an exception of unknown type.\n", GetHandle().GetUniqueId());
			}
			fflush(stderr);
			std::terminate();
		}
#endif
		switch(m_destructionBehavior)
		{
		case ThreadDestructionBehavior::Abort:
		case ThreadDestructionBehavior::Default:
		default:
			std::terminate();
			break;
		case ThreadDestructionBehavior::Detach:
			PlatformDetach();
			break;
		case ThreadDestructionBehavior::Join:
			PlatformJoin();
			break;
		}
	}
	CloseHandle(m_handle.GetNativeHandle());
}

void sprawl::this_thread::Sleep(uint64_t nanoseconds)
{
	::Sleep(nanoseconds / sprawl::time::Resolution::Milliseconds);
}

void sprawl::this_thread::SleepUntil(uint64_t nanosecondTimestamp)
{
	Sleep(nanosecondTimestamp - sprawl::time::Now(sprawl::time::Resolution::Nanoseconds));
}

void sprawl::this_thread::Yield()
{
	SwitchToThread();
}


text:
require 'rspec_say/version'
require 'rspec_say/say_formatter'

module RspecSay

end

RSpecSay = SayFormatter


text:
package org.apache.camel.spi;

import org.apache.camel.Expression;
import org.apache.camel.Predicate;

/**
 * Represents a language to be used for {@link Expression} or {@link Predicate} instances
 */
public interface Language {

    /**
     * Creates a predicate based on only the given string input
     *
     * @param  expression the expression as a string input
     * @return            the created predicate
     */
    Predicate createPredicate(String expression);

    /**
     * Creates an expression based on only the given string input
     *
     * @param  expression the expression as a string input
     * @return            the created expression
     */
    Expression createExpression(String expression);

    /**
     * Creates an expression based on the input with properties
     *

     * This is used for languages that have been configured with custom properties most noticeable for
     * xpath/xquery/tokenizer languages that have several options.
     *
     * @param  expression the expression
     * @param  properties configuration properties (optimized as object array with hardcoded positions for properties)
     * @return            the created predicate
     */
    default Predicate createPredicate(String expression, Object[] properties) {
        return createPredicate(expression);
    }

    /**
     * Creates an expression based on the input with properties
     *

     * This is used for languages that have been configured with custom properties most noticeable for
     * xpath/xquery/tokenizer languages that have several options.
     *
     * @param  expression the expression
     * @param  properties configuration properties (optimized as object array with hardcoded positions for properties)
     * @return            the created expression
     */
    default Expression createExpression(String expression, Object[] properties) {
        return createExpression(expression);
    }
}