text:
UnderscoreX
===========

This is a set of Class and decorator to parse many type of argument.

This structure is intended for The developper developping pass-thru and conviviable method to
intercept attribut on demande by passing information from **kwargs or mutiple-string-chained argument.

=========
    This allow to build and easy model assuming you had readed the example. It offer a easy chaining method
    Thru decorator to parse incoming information from **kwargs or any multi-chained string. Once you have
    defined a correct dictrionary of Attentend Attribute and Messages dedicated to inform the developper.
    It contains a mechanism to push into warning or error the missing attribute informaitons. Rather to
    code individually all the missing attribute and condition, and exception class is provided as example.

Installing
==========
  Under Development.

  You can download the latest versions released from <<No pypi for the moment, crude develpt and
  in correct stuff will cause problem and rejection, but maxistedeams will release it >>
  or download the development version straight from the Github repository hosted by me at:
  git://github.com/priendeau/UnderscoreX.git

Documentation
=============
  Is currently lacking, about every method is documented in the source. But future prototype will
  become move and more verbosis and Final realse will include test-case and a lot of documentation.

::
		Example
		------------
		Generic Exception class model:

        Basics
        ------
        We need 2 Class to store attribute:

        class ObjectGenericWarningHolder( object ):

          def __init__( self ):
            print "Add Current Object Attribute %s" % self.__class__.__name__

        class ObjectGenericAttrHolder( object ):

          def __init__( self ):
            print "Add Current Object Attribute %s" % self.__class__.__name__

        We Need a Generic Exception class like this one.

        class ExceptionGenericAttrMissing( Exception ):

          msg                             ='__GENERIC_EXCEPTION_MESSAGES__'
          AttrCurrentExceptionHandled     = None
          HadDecoderTypeList              = False

          def __Init__Attr( self , value ):
            self.AttrCurrentExceptionHandled = value
            DictListTemplateKey="%sList" % ( value )
            IsListTemplateKey="Had%sList" % ( value )
            if hasattr( self, IsListTemplateKey  ):
              if getattr( self, IsListTemplateKey ) == True:
                Exception.__init__( self, self.MsgDict[DictListTemplateKey] % ( self.AttrCurrentExceptionHandled ,
                                                                        getattr( self, DictListTemplateKey ) ) )
              else:
                Exception.__init__( self, self.MsgDict[self.AttrCurrentExceptionHandled]  % ( self.AttrCurrentExceptionHandled ) )

          @_XDecoratorWrapper.Kargs2Attr( ObjectWarningHolder )
          def __init__( self, **Kargs ):
            if hasattr( self, 'ListAttrFuncAccess' ):
              print "Available message for following Attr:[ %s ]" % ( self.ListAttrFuncAccess )
            self.RaisedExceptionByAttr = False
            for ExceptionByAttr in self.ListAttrFuncAccess:
              if hasattr( self, ExceptionByAttr ):
                self.RaisedExceptionByAttr = True
                getattr( self, "__Init__Attr")( ExceptionByAttr )

        ###
        ### Main class:
        ###

        class GenericTest( object ):

          MsgDict = {
            'AppsName'        :'Internal Value AppsName not used, You should at least Specified an AppsName Value.',
            'ActionHelper'    :'Internal Value ActionHelper not used, You should at least Specified an ActionHelper Value.',
            'HelperSwitch'    :'Internal Value HelperSwitch not used, You should at least Specified an HelperSwitch Value.',
          }

          OptionListDiscovery=list()
          TempOptionList=list()
          ErrorHandler = iterpipes.CalledProcessError

          ListAttrFuncAccess        = [ 'AppsName', 'ActionHelper', 'HelperSwitch' ]
          parser = OptionParser()

          def __start_cmdline_parser__( self ):

            self.parser.add_option("-A", "--AppsName",
                              dest="StrAppsName",
                              help="Add AppsName in your Class")
            self.parser.add_option("-J", "--ActionHelper",
                              dest="StrActionHelper",
                              help="Add ActionHelper in your Class")
            self.parser.add_option("-S", "--HelperSwitch",
                              dest="StrHelperSwitch",
                              help="Add HelperSwitch in your Class ")

          @_XDecoratorWrapper.Kargs2AttrPreException( ObjectIterAppsFilter )
          def __init__( self , **Kargs ):
            self.__start_cmdline_parser__()
            (self.options, self.args ) = self.parser.parse_args()
            self.ErrorRaiser( )
        ### ...

          @_XDecoratorWrapper.ObjectClassRaiser( ObjectGenericAttrHolder , ExceptionGenericAttrMissing )
          def ErrorRaiser( self ):
            print "Inspecting Missing Attribute."

        ### Some Instantiation statement:

        if __name__.__eq__( '__main__' ):
          _XDecoratorWrapper.ErrorClassReceivedAttrListName = 'ListAttrFuncAccess'
          ExceptionGenericAttrMissing.ListAttrFuncAccess    = ItertAppsFilter.ListAttrFuncAccess
          ExceptionGenericAttrMissing.MsgDict               = ItertAppsFilter.MsgDict
          Ainstance=GenericTest( AppsName=None, ActionHelper=None, HelperSwitch=None )

        And We have Correct basic model of Attribute filtering thru the **kargs and will raise any Warning or exception
        upon definition of your class inside the Object Raiser inside _XDecoratorWrapper :
        --------
        @_XDecoratorWrapper.ObjectClassRaiser( __ANY_EXCEPTION_OR_WARNING_OBJECT__ , ExceptionGenericAttrMissing )
        def ErrorRaiser( self ):
         pass
        --------


text:
using MasterInstaller.Components;
using MasterInstaller.Components.InstallableComponents.FRBDK;
using MasterInstaller.Components.MainComponents.Completed;
using MasterInstaller.Components.MainComponents.ComponentInstallation;
using MasterInstaller.Components.MainComponents.CustomSetup;
using MasterInstaller.Components.MainComponents.Introduction;
using MasterInstaller.Components.MainComponents.VisualStudioInformation;
using MasterInstaller.Managers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MasterInstaller
{
    public class MainFlow
    {
        public InstallForm MainForm { get; internal set; }

        public void StartFlow()
        {
            var component = new IntroductionComponent();
            MainForm.SetComponent(component);

            component.NextClicked += delegate
            {
                GoToVisualStudioInfo();
            };

        }

        private void GoToVisualStudioInfo()
        {
            var component = new VisualStudioInfoComponent();

            component.NextClicked += delegate
            {
                GoToComponentSelection();
            };

            MainForm.SetComponent(component);

        }

        private void GoToComponentSelection()
        {
            var component = new CustomSetupComponent();
            component.NextClicked += HandleComponentSelection;
            MainForm.SetComponent(component);
        }

        private void HandleComponentSelection(object sender, EventArgs args)
        {
            var component = sender as CustomSetupComponent;

            GoToInstallComponents();
        }

        private void GoToInstallComponents()
        {
            var component = new ComponentInstallationComponent();

            component.NextClicked += delegate
            {
                GoToFrbdkAssociation();
            };

            MainForm.SetComponent(component);
        }

        private void GoToFrbdkAssociation()
        {
            // We don't ask, we just do:
            FileAssociationManager.SetAllFileAssociations();

            GoToEnd();

        }

        private void GoToEnd()
        {

            var component = new CompletedComponent();

            component.NextClicked += delegate
            {
                // exit?
                MainForm.Close();
            };

            MainForm.SetComponent(component);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
title: Kernels
published: 2016-12-29
modified: 2016-12-29
tags: kernels, RKHS
type: notes
showTOC: True
---

Mostly from Percy Liang's 229T notes.

# Kernels

If $w=\sumo in \al_i \phi(x^{(i)})$ then $\an{w,\phi(x)} = \sumo in \al_i \an{\phi(x^{(i)}), \phi(x)}$.

# Equivalences

The following are equivalent (although multiple feature maps can correspond to the same kernel/RKHS):

* Feature map $\phi:X\to H$.
* Symmetric, positive (semi)definite kernel $k:X\times X\to \R$. (for all $S$, $(k(x_i,x_j))_{i,j\in S}$ is PSD.)
* RKHS $\{f:X\to \R\}, \ved_H$.

Proof:

* Feature map to kernel: $k(x,x') = \an{\phi(x), \phi(x')}$.
* RKHS to kernel: Riesz representation (see below). $L_x(f) = \an{R_x,f}$.
* Kernel to RKHS: Moore-Aronszajn. $f=\sumo in \al_i k(x_i,x)$, $\an{f,g} - \sumo in \sumo j{n'} \al_i\be_j k(x_i,x_j')$. (See below.)

# RKHS

A [reproducing kernel Hilbert space (RKHS)](https://en.wikipedia.org/wiki/Reproducing_kernel_Hilbert_space) is a Hilbert space of functions $X\to \R$ in which point evaluation $L_x[f] = f(x)$ is a continuous linear functional. (Equivalently, it is bounded: $f(x)\le M_x\ve{f}_H$.)

* $L^2$ is not a RKHS---it consists of equivalence classes of functions.
* $H=\set{f\in L_2(\R)}{\Supp(\wh f)\subeq [-a,a]}$ is RKHS. Here $K_x(y) = \fc{\sin(a(y-x))}{\pi(y-x)}$ (bandlimited Dirac delta).

**Theorem** A Hilbert space of functions is a RKHS iff for every $x\in X$, there exists $K_x$ such that $g(x) = \an{g, K_x}$.[^f1]

*Proof*. $\Leftarrow$: inner product is continuous. $\Rightarrow$: Riesz representation.

[^f1]: Letting $f_x=\delta_x$ is cheating---we want actual functions, not distributions.

Note $K_x(y) = \an{K_x,K_y}=:K(x,y)$. $K$ is symmetric and positive definite. (Think of $K$ as $X_0^\R\times X_0^\R\to \R$ where $X_0^\R$ is the set of functions $X\to \R$ nonzero only at a finite number of $x$'s. I.e. formal span of $X$.)

**Theorem (Moore-Aronszajn)**. Suppose $K$ is a symmetric, positive definite kernel on a set $X$. Then there is a unique Hilbert space of functions on $X$ for which $K$ is a reproducing kernel.

*Proof*. Extend $K$ by bilinearity to $\spn(X)$. Take the completion. (Extend to functions $f=\sumo i{\iy} a_i K_{x_i}(x)$ where $\sumo i{\iy} a_i^2 K(x_i,x_i)$.)

(Question: how to realize this inner product as an integral?)

See also: Mercer's theorem

# Learning

[Representer theorem](https://en.wikipedia.org/wiki/Representer_theorem) states that every function in an RKHS that minimises an empirical risk function can be written as a linear combination of the kernel function evaluated at the training points.

If
$$
f^*\in \amin_{f\in H} L(\{(x_i,y_i,f(x_i))\}) + Q(\ve{f}_H^2)
$$
where $Q:[0,\iy)\to \R$ strictly increasing is a regularizer, then
$$
f^*\in \spn(\set{k(x_i, \cdot)}{i\in [n]}).
$$

Example: kernel ridge regression $\al = (K+\la I)^{-1}Y$.

# Fourier properties

$k:X\times X\to \R$, $X\subeq \R^b$ is shift-invariant if $k(x,x') = h(x-x')$. Let $t=x-x'$.

**Bochner's theorem**. Let $k(x,x') = h(x-x')$ be a continuous shift-invariant kernel ($x\in \R^b$). There exists a unique finite *nonnegative* measure $\mu$ (spectral measure) such that
$$
h(t) = \int e^{-i\an{t,\om}}\mu(d\om).
$$
($h$ is the characteristic function of $\mu$. For $\mu(d\om)=s(\om)d\om$, call $s$ the spectral density.)
(See probability notes.)

# Efficient computation

* Random features: We will write the kernel function as an integral, and using Monte Carlo approximations of this integral. These approximations are of the kernel function and are data-independent.
* Nystrom method: We will sample a subset of the n points and use these points to approximate the kernel matrix. These approximations are of the kernel matrix and are data-dependent.

Ex. when points are clustered into $m$ clusters, kernel matrix looks like block diagonal with $m$ blocks $J$, so rank $m$ approximation is effective.

## Random features

Draw $\om_i\sim \mu$, and estimate
$$
\wh k(x,x') = \rc m \sumo im \phi_{\om_i}(x)\ol{\phi_{\om_i}(x)}.
$$

**Theorem**. Let
\begin{align}
\mathcal F &= \set{x\mapsto \int \al(\om)\phi_\om(x)\mu(d\om)}{\forall \om, |\al(\om)|\le C}\\
\wh{\mathcal F} &= \set{x\mapsto \rc m\sumo im \al(\om_i)\phi_{\om_i}(x)\mu(d\om)}{\forall \om, |\al(\om)|\le C}
\end{align}
where $\om_i\sim \mu$. Let $\an{f,g}=\EE_{x\sim p^*}[fg]$. Then
$$
\Pj\pa{
\exists \wh f\in \wh{\mathcal F},
\ve{\wh f- f^*}\le \fc{C}{\sqrt m}
\pa{1+\sqrt{2\ln(1/\de)}}
}.
$$

*Proof*. McDiarmid and Jensen. (p. 133-5, omitted.)

(Q: what about generalization guarantee? See p. 134)

For other kernels, note
$$\an{x,x'}=\E[\an{\om, x}\an{\om,x'}].$$
For $\an{x,x'}^p$, take $p$ independent draws and multiply together. For general $f$, expand in Taylor series.

Comparison to neural nets: "the random features view of kernels defines a function class where $\om_{1:m}$ is chosen randomly rather than optimized, while $\alpha_{1:m}$ are optimized. The fact that random features approximates a kernel suggests that even the random initialization is quite sensible starting point."

For $\phi_\om(x) = \one_{\om^Tx\ge 0}(\om^Tx)^q$, as $m\to \iy$, get the kernel
\begin{align}
k(x,x') &= 2\int\phi_\om(x)\phi_\om(x')p(\om)d\om\\
&= \rc\pi \ve{x}^q\ve{x'}^q J_q\ub{\pa{\cos^{-1}\pf{x^Tx'}{\ve{x}\ve{x'}}}}{\te}\\
J_0(\te) &= \pi - \te\\
J_1(\te) &= \sin\te + (\pi - \te)\cos\te.
\end{align}
(Bessel function?) Decouples magnitude from angle.
(Cho/Saul 2009)

## Nystrom

$$K \approx \matt{K_{II}}{K_{IJ}}{K_{JI}}{K_{JI}K_{II}^{+}K_{IJ}}.$$

$K_{JJ} - K_{JI}K_{II}^{+}K_{IJ}$ is the Schur complement.

Drineas/Mahoney: Choose $I$ by sampling $i$ with probability $\fc{K_{ii}}{\sumo jn K_{jj}}$. (p. 138)

# Universality

Let $X$ be locally compact Hausdorff. $k$ is a $c_0$-universal kernel if $H$ with reproducing kernel $k$ is dense in $C_0(X)$ (continuous bounded functions wrt uniform ($L^{\iy}$) norm).

Carmeli2010: Let $k$ be shift-invariant with spectral measure $\mu$. If $\Supp(\mu) = \R^b$, then $k$ is universal.

# RKHS embedding of probability distributions

Kernels can be used to represent and answer questions about probability distributions without having to explicitly estimate them.

**Maximum mean discrepancy**
$$
D(P,Q,F) := \sup_{f\in\mathcal F}
\pa{
\EE_{x\sim P}[f(x)] - \EE_{x\sim Q}[f(x)]
}.
$$

If $\mathcal F=C_0(X)$, then $D(P,Q,\mathcal F)=0\implies P=Q$. Better: Can let $\mathcal F = \set{f\in H}{\ve{f}_H\le 1}$ where $k$ is universal. (Check proof p. 140)


text:
package net.sourceforge.safr.core.integration.sample;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import net.sourceforge.safr.core.annotation.Filter;
import net.sourceforge.safr.core.annotation.Secure;
import net.sourceforge.safr.core.annotation.SecureAction;
import net.sourceforge.safr.core.annotation.SecureObject;

/**
 * @author Martin Krasser
 */
@SecureObject
public class DomainObjectA {

    // -------------------------------------------------------------------
    //  parameter annotation
    // -------------------------------------------------------------------

    public void m01a(
            @Secure(SecureAction.UPDATE) String p1,
            /* not annotated */ String p2) {}
    public void m01b(
            /* not annotated */ String p1,
            @Secure(SecureAction.UPDATE) String p2) {}
    public void m01c(
            @Secure(SecureAction.UPDATE) String p1,
            @Secure(SecureAction.UPDATE) String p2) {}
    public void m01d(
            @Secure({SecureAction.UPDATE, SecureAction.CREATE}) String p1,
            @Secure(SecureAction.DELETE) String p2) {}

    // -------------------------------------------------------------------
    //  parameter annotation inheritance
    // -------------------------------------------------------------------

    public void m02a( // subclass inherits annotations
            @Secure(SecureAction.UPDATE) String p1,
            String p2) {}
    public void m02b( // subclass overrides annotations
            @Secure(SecureAction.UPDATE) String p1,
            String p2) {}
    public void m02c( // subclass defines annotations
            String p1,
            String p2) {}
    public void m02d( // subclass overrides annotations (different location)
            @Secure(SecureAction.UPDATE) String p1,
            String p2) {}

    // -------------------------------------------------------------------
    //  method annotation inheritance (@Secure)
    // -------------------------------------------------------------------

    @Secure(SecureAction.CREATE)
    public void m03a() {}

    @Secure(SecureAction.CREATE)
    public void m03b() {}

    // -------------------------------------------------------------------
    //  method annotation inheritance (@Filter)
    // -------------------------------------------------------------------

    // -------------------------------------------------------------------
    //  combination of annotation inheritance
    // -------------------------------------------------------------------

    @Filter
    public String m09a(String p1) {
        return "x";
    }

    @Filter
    public String m09b(String p1) {
        return "x";
    }

    @Filter(nullifyResult=false)
    public String m09c(String p1) {
        return p1;
    }

    // -------------------------------------------------------------------
    //  method annotation (@Secure)
    // -------------------------------------------------------------------

    @Secure
    public void m10a() {}
    @Secure(SecureAction.NONE)
    public void m10b() {}
    @Secure(SecureAction.EXECUTE)
    public void m10c() {}
    @Secure(SecureAction.CREATE)
    public void m10d() {}
    @Secure({SecureAction.NONE,SecureAction.EXECUTE,SecureAction.CREATE})
    public void m10e() {}

    // -------------------------------------------------------------------
    //  method annotation (@Filter)
    // -------------------------------------------------------------------

    @Filter
    public Collection<String> m20a(Collection<String> c) {
        return c;
    }

    @Filter(copyResultCollection=false)
    public Collection<String> m20b(Collection<String> c) {
        return c;
    }

    @Filter
    public int m21a() {
        return 1;
    }

    // -------------------------------------------------------------------
    //  all annotations
    // -------------------------------------------------------------------

    @Filter @Secure({SecureAction.EXECUTE,SecureAction.UPDATE})
    public List<String> m30a(
            @Secure({SecureAction.CREATE,SecureAction.READ})String p1,
            @Secure(SecureAction.DELETE)String p2) {
        ArrayList<String> result = new ArrayList<String>();
        result.add("x");
        result.add("y");
        return result;
    }

}


text:
import { ActivatedRouteSnapshot } from './router_state';
/**
 * @description
 *
 * Represents the detached route tree.
 *
 * This is an opaque value the router will give to a custom route reuse strategy
 * to store and retrieve later on.
 *
 * @publicApi
 */
export declare type DetachedRouteHandle = {};
/**
 * @description
 *
 * Provides a way to customize when activated routes get reused.
 *
 * @publicApi
 */
export declare abstract class RouteReuseStrategy {
    /** Determines if this route (and its subtree) should be detached to be reused later */
    abstract shouldDetach(route: ActivatedRouteSnapshot): boolean;
    /**
     * Stores the detached route.
     *
     * Storing a `null` value should erase the previously stored value.
     */
    abstract store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle | null): void;
    /** Determines if this route (and its subtree) should be reattached */
    abstract shouldAttach(route: ActivatedRouteSnapshot): boolean;
    /** Retrieves the previously stored route */
    abstract retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null;
    /** Determines if a route should be reused */
    abstract shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean;
}
/**
 * Does not detach any subtrees. Reuses routes as long as their route config is the same.
 */
export declare class DefaultRouteReuseStrategy implements RouteReuseStrategy {
    shouldDetach(route: ActivatedRouteSnapshot): boolean;
    store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void;
    shouldAttach(route: ActivatedRouteSnapshot): boolean;
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle | null;
    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean;
}


text:
`git submodule update --init --recursive`

## Add a package
```
cd ~/.vim/pack/plugins/start
git submodule add <repo>
```

## Update packages
`git submodule update --remote --merge`

## Remove a package
```
cd ~/.vim/pack/plugins/start/
git submodule deinit <plugin>
rm -rf $DOTFILES/.git/modules/vim-plugins/start/<plugin>
```


text:
"""
Buffer protocol support.
"""
from rpython.rtyper.lltypesystem import lltype, llmemory
from rpython.rtyper.lltypesystem.lloperation import llop
from rpython.rtyper.lltypesystem.rstr import STR
from rpython.rtyper.lltypesystem.rlist import LIST_OF
from rpython.rtyper.annlowlevel import llstr
from rpython.rlib.objectmodel import specialize
from rpython.rlib import jit
from rpython.rlib.rgc import (resizable_list_supporting_raw_ptr,
                              nonmoving_raw_ptr_for_resizable_list,
                              ll_for_resizable_list)
from rpython.rlib.signature import signature
from rpython.rlib import types
from rpython.rlib import rawstorage

ALLOW_UNALIGNED_ACCESS = rawstorage.misaligned_is_fine

@specialize.ll()
def is_alignment_correct(TYPE, index):
    if ALLOW_UNALIGNED_ACCESS:
        return True
    try:
        rawstorage._check_alignment(TYPE, index)
    except rawstorage.AlignmentError:
        return False
    else:
        return True

class CannotRead(Exception):
    """
    Exception raised by Buffer.typed_read in case it is not possible to
    accomplish the request. This might be because it is not supported by the
    specific type of buffer, or because of alignment issues.
    """

class CannotWrite(Exception):
    """
    Raised by Buffer.typed_write in case it is not possible to accomplish the
    request
    """

class Buffer(object):
    """
    Base class for buffers of bytes.

    Most probably, you do NOT want to use this as a lone base class, but
    either inherit from RawBuffer or GCBuffer, so that you automatically get
    the proper implementation of typed_read and typed_write.
    """
    _attrs_ = ['readonly']
    _immutable_ = True

    def getlength(self):
        """Return the size in bytes."""
        raise NotImplementedError

    def __len__(self):
        res = self.getlength()
        assert res >= 0
        return res

    def as_str(self):
        "Returns an interp-level string with the whole content of the buffer."
        # May be overridden.
        return self.getslice(0, self.getlength(), 1, self.getlength())

    def getitem(self, index):
        "Returns the index'th character in the buffer."
        raise NotImplementedError   # Must be overriden.  No bounds checks.

    def __getitem__(self, i):
        return self.getitem(i)

    def getslice(self, start, stop, step, size):
        # May be overridden.  No bounds checks.
        return ''.join([self.getitem(i) for i in range(start, stop, step)])

    @signature(types.any(), types.int(), types.int(), returns=types.str())
    def __getslice__(self, start, stop):
        return self.getslice(start, stop, 1, stop - start)

    def setitem(self, index, char):
        "Write a character into the buffer."
        raise NotImplementedError   # Must be overriden.  No bounds checks.

    def __setitem__(self, i, char):
        return self.setitem(i, char)

    def setslice(self, start, string):
        # May be overridden.  No bounds checks.
        for i in range(len(string)):
            self.setitem(start + i, string[i])

    @jit.look_inside_iff(lambda self, index, count:
                         jit.isconstant(count) and count <= 8)
    def setzeros(self, index, count):
        for i in range(index, index+count):
            self.setitem(i, '\x00')

    @specialize.ll_and_arg(1)
    def typed_read(self, TP, byte_offset):
        """
        Read the value of type TP starting at byte_offset. No bounds checks
        """
        raise CannotRead

    @specialize.ll_and_arg(1)
    def typed_write(self, TP, byte_offset, value):
        """
        Write the value of type TP at byte_offset. No bounds checks
        """
        raise CannotWrite

class RawBuffer(Buffer):
    """
    A buffer which is baked by a raw, non-movable memory area. It implementes
    typed_read and typed_write in terms of get_raw_address(), llop.raw_load,
    llop.raw_store.

    NOTE: this assumes that get_raw_address() is cheap. Do not use this as a
    base class if get_raw_address() is potentially costly, like for example if
    you call rgc.nonmoving_raw_ptr_for_resizable_list
    """
    _immutable_ = True

    @specialize.ll_and_arg(1)
    def typed_read(self, TP, byte_offset):
        """
        Read the value of type TP starting at byte_offset. No bounds checks
        """
        if not is_alignment_correct(TP, byte_offset):
            raise CannotRead
        ptr = self.get_raw_address()
        return llop.raw_load(TP, ptr, byte_offset)

    @specialize.ll_and_arg(1)
    def typed_write(self, TP, byte_offset, value):
        """
        Write the value of type TP at byte_offset. No bounds checks
        """
        if self.readonly or not is_alignment_correct(TP, byte_offset):
            raise CannotWrite
        ptr = self.get_raw_address()
        value = lltype.cast_primitive(TP, value)
        return llop.raw_store(lltype.Void, ptr, byte_offset, value)

class GCBuffer(Buffer):
    """
    Base class for a buffer which is baked by a GC-managed memory area. You
    MUST also decorate the class with @GCBuffer.decorate: it implements
    typed_read and typed_write in terms of llop.gc_load_indexed and
    llop.gc_store_indexed.
    """
    _attrs_ = ['readonly', 'value']
    _immutable_ = True

    @staticmethod
    def decorate(targetcls):
        """
        Create and attach specialized versions of typed_{read,write}. We need to
        do this becase the JIT codewriters mandates that base_ofs is an
        RPython constant.
        """
        if targetcls.__bases__ != (GCBuffer,):
            raise ValueError("@GCBuffer.decorate should be used only on "
                             "GCBuffer subclasses")

        base_ofs = targetcls._get_gc_data_offset()
        scale_factor = llmemory.sizeof(lltype.Char)

        @specialize.ll_and_arg(1)
        def typed_read(self, TP, byte_offset):
            if not is_alignment_correct(TP, byte_offset):
                raise CannotRead
            lldata = self._get_gc_data()
            byte_offset += self._get_gc_data_extra_offset()
            return llop.gc_load_indexed(TP, lldata, byte_offset,
                                        scale_factor, base_ofs)

        @specialize.ll_and_arg(1)
        def typed_write(self, TP, byte_offset, value):
            if self.readonly or not is_alignment_correct(TP, byte_offset):
                raise CannotWrite
            lldata = self._get_gc_data()
            byte_offset += self._get_gc_data_extra_offset()
            value = lltype.cast_primitive(TP, value)
            return llop.gc_store_indexed(lltype.Void, lldata, byte_offset, value,
                                         scale_factor, base_ofs)

        targetcls.typed_read = typed_read
        targetcls.typed_write = typed_write
        return targetcls

    @staticmethod
    def _get_gc_data_offset(self):
        raise NotImplementedError

    def _get_gc_data_extra_offset(self):
        return 0

    def _get_gc_data(self):
        raise NotImplementedError

    @specialize.ll_and_arg(1)
    def typed_read(self, TP, byte_offset):
        raise NotImplementedError("You MUST decorate this class with "
                                  "@GCBuffer.decorate")

    @specialize.ll_and_arg(1)
    def typed_write(self, TP, byte_offset, value):
        raise NotImplementedError("You MUST decorate this class with "
                                  "@GCBuffer.decorate")

def get_gc_data_for_list_of_chars(data):
    ll_data = ll_for_resizable_list(data)
    ll_items = ll_data.items
    return lltype.cast_opaque_ptr(llmemory.GCREF, ll_items)

def get_gc_data_offset_for_list_of_chars():
    LIST = LIST_OF(lltype.Char)
    return llmemory.itemoffsetof(LIST.items.TO, 0)

@GCBuffer.decorate
class ByteBuffer(GCBuffer):
    _immutable_ = True

    def __init__(self, n):
        self.data = resizable_list_supporting_raw_ptr(['\0'] * n)
        self.readonly = False

    def getlength(self):
        return len(self.data)

    def getitem(self, index):
        return self.data[index]

    def setitem(self, index, char):
        self.data[index] = char

    def get_raw_address(self):
        return nonmoving_raw_ptr_for_resizable_list(self.data)

    def _get_gc_data(self):
        return get_gc_data_for_list_of_chars(self.data)

    @staticmethod
    def _get_gc_data_offset():
        return get_gc_data_offset_for_list_of_chars()

@GCBuffer.decorate
class StringBuffer(GCBuffer):
    _attrs_ = ['readonly', 'value']
    _immutable_ = True

    def __init__(self, value):
        assert value  is not None
        self.value = value
        self.readonly = 1

    def getlength(self):
        return len(self.value)

    def as_str(self):
        return self.value

    def getitem(self, index):
        return self.value[index]

    def getslice(self, start, stop, step, size):
        if size == 0:
            return ""
        if step == 1:
            assert 0 <= start <= stop
            if start == 0 and stop == len(self.value):
                return self.value
            return self.value[start:stop]
        return Buffer.getslice(self, start, stop, step, size)

    def get_raw_address(self):
        from rpython.rtyper.lltypesystem import rffi
        # may still raise ValueError on some GCs
        return rffi.get_raw_address_of_string(self.value)

    @staticmethod
    def _get_gc_data_offset():
        return (llmemory.offsetof(STR, 'chars') +
                llmemory.itemoffsetof(STR.chars, 0))

    def _get_gc_data(self):
        lls = llstr(self.value)
        return lltype.cast_opaque_ptr(llmemory.GCREF, lls)

class SubBuffer(Buffer):
    _attrs_ = ['buffer', 'offset', 'size', 'readonly']
    _immutable_ = True

    @signature(types.any(), types.instance(Buffer), types.int(), types.int(),
               returns=types.none())
    def __init__(self, buffer, offset, size):
        self.readonly = buffer.readonly
        if isinstance(buffer, SubBuffer):     # don't nest them
            # we want a view (offset, size) over a view
            # (buffer.offset, buffer.size) over buffer.buffer.
            # Note that either '.size' can be -1 to mean 'up to the end'.
            at_most = buffer.getlength() - offset
            if size > at_most or size < 0:
                if at_most < 0:
                    at_most = 0
                size = at_most
            offset += buffer.offset
            buffer = buffer.buffer
        #
        self.buffer = buffer
        self.offset = offset
        self.size = size

    def getlength(self):
        at_most = self.buffer.getlength() - self.offset
        if 0 <= self.size <= at_most:
            return self.size
        elif at_most >= 0:
            return at_most
        else:
            return 0

    def getitem(self, index):
        return self.buffer.getitem(self.offset + index)

    def getslice(self, start, stop, step, size):
        if start == stop:
            return ''     # otherwise, adding self.offset might make them
                          # out of bounds
        return self.buffer.getslice(self.offset + start, self.offset + stop,
                                    step, size)

    def setitem(self, index, char):
        self.buffer.setitem(self.offset + index, char)

    def setslice(self, start, string):
        if len(string) == 0:
            return        # otherwise, adding self.offset might make 'start'
                          # out of bounds
        self.buffer.setslice(self.offset + start, string)

    def get_raw_address(self):
        from rpython.rtyper.lltypesystem import rffi
        ptr = self.buffer.get_raw_address()
        return rffi.ptradd(ptr, self.offset)

    @specialize.ll_and_arg(1)
    def typed_read(self, TP, byte_offset):
        return self.buffer.typed_read(TP, byte_offset + self.offset)

    @specialize.ll_and_arg(1)
    def typed_write(self, TP, byte_offset, value):
        return self.buffer.typed_write(TP, byte_offset + self.offset, value)


text:
require 'thor'
require 'yaml'

module Redmine
  module Cli
    class NoConfigFileError < StandardError
    end

    class << self

      def config
        begin
          generic_conf '.redmine'
        rescue Errno::ENOENT
          raise NoConfigFileError
          exit 1
        end
      end

      def cache
        begin
          generic_conf '.redmine_cache'
        rescue Errno::ENOENT
          @cache = Thor::CoreExt::HashWithIndifferentAccess.new
        end
      end

      private

      def generic_conf(config_file)
        # Using Ruby Magic(tm) to get the caller's function name to use for
        # setting up instance variables/accessors for generic config files.
        config_name = caller[0][/`.*'/][1..-2]

        if !File.file? config_file
          config_file = File.expand_path "~/#{config_file}"
        end

        contents = YAML.load_file config_file
        if contents
          config ||= Thor::CoreExt::HashWithIndifferentAccess.new(YAML.load_file(config_file))
        else
          config ||= Thor::CoreExt::HashWithIndifferentAccess.new
        end
        self.instance_variable_set("@#{config_name}", config)
      end

    end
  end
end


text:
"use strict";

const vm = require( 'vm' );

const time = require( './time.js' );

// Hormone class is exteneded by HormoneSink and HormoneSource class
// The specialised classes just houses the constructor. The class methods are
// implemented here.

class Hormone {

	get freshness() {

		let reqFreshness = this._definition.data.freshness;
		if( ! reqFreshness ) return true;

		let now = time.now();

		return ( this._timestamp - now ) / 1000 + reqFreshness;

	}

	get isFresh() {

		let freshness = this.freshness;

		// If freshness is boolean, the number of seconds the hormone will remain
		// fresh cannot be obtained
		if( typeof freshness == 'boolean') return freshness;

		return ( freshness >= 0 );

	}

	get error() {

		let def = this._definition.data;

		// If we do not find a check script, just return 0 -> no error
		if( ! def.check ) return 0;

		// If the error hasn't been calculated before, run check script
		if( ! this._error ) {

			// Create a new vm
			let check = new vm.Script( def.check );

			// Create new context
			let sandbox = { err: 0 };
			let data = this._data;
			for( let d in data ) {
				// Read data from hormone
				sandbox[ d ] = data[ d ];
			}
			vm.createContext( sandbox );

			// Run script
			check.runInContext( sandbox );

			// Store error in instance;
			if( sandbox.err !== undefined ) this._error = parseFloat( sandbox.err );

		}

		return this._error;

	}

	get payload() { return this._payload; }

	get data() { return this._data; }

	get definition() { return this._definition; }

	get timestamp() { return this._timestamp; }

}

module.exports = Hormone;


text:
;(function () { // eslint-disable-line no-extra-semi
  "use strict";

  const m          = require("mithril"),
        Stream     = require("mithril/stream"),
        _          = require("lodash"),
        CrudMixins = require("models/mixins/crud_mixins"),
        Errors     = require("models/mixins/errors").Errors;

  function splitter(string) {
    return _.compact(_.map(string.split(","), _.trim));
  }

  function EmailSettings(resourceUrl, errors) {
    this.email               = Stream();
    this.enableNotifications = Stream();
    this.checkinAliases      = Stream();
    this.etag                = Stream();

    let savedEmail, savedEnableNotifications, savedCheckinAliases;

    const payload = {
      email:          this.email,
      emailMe:        this.enableNotifications,
      checkinAliases: this.checkinAliases.map(splitter)
    };

    this.toJSON   = function serialize() {
      return payload;
    };
    this.fromJSON = (data) => {
      savedEmail               = this.email(data.email);
      savedEnableNotifications = this.enableNotifications(data.email_me);
      savedCheckinAliases      = this.checkinAliases(data.checkin_aliases.join(", "));

      return this;
    };

    this.load = () => {
      this.refresh().always(() => m.redraw());
    };

    this.reset = () => {
      this.email(savedEmail);
      this.enableNotifications(savedEnableNotifications);
      this.checkinAliases(savedCheckinAliases);
    };

    this.config = (attrs, updateCallback) => {
      return _.assign(attrs, {
        action: resourceUrl, method: "POST", onsubmit: (e) => {
          e.preventDefault();
          errors(null);

          this.update().then((data) => {
            updateCallback(e, data);
          }, (message) => {
            errors(message.replace(/^Failed to add user\. Validations failed\. /, "")); // Strip the localized message orefix
          }).always(() => m.redraw());
        }
      });
    };

    // just stub this out; the only thing that needs validation is email, and we rely on the default
    // input[type="email"] pattern for client-side validation
    this.validate = () => new Errors();

    CrudMixins.AllOperations.call(this, ["refresh", "update"], {
      type:    this,
      resourceUrl,
      version: "v1"
    }, {update: {method: "PATCH"}});
  }

  module.exports = EmailSettings;
})();


text:
function CustomBuffer(existingBuffer) {
    var buffer = existingBuffer || new Buffer(48);
    var offset = 0;

    this.writeVarInt = function(val) {
        while (true) {
            if ((val & 0xFFFFFF80) == 0) {
                this.writeUByte(val);

                return;
            }

            this.writeUByte(val & 0x7F | 0x80);

            val = val >>> 7;
        }
    };

    this.writeString = function(string) {
        this.writeVarInt(string.length);

        if (offset + string.length >= buffer.length) {
            Buffer.concat([buffer, new Buffer(string.length)]);
        }

        buffer.write(string, offset, string.length, "UTF-8");

        offset += string.length;
    };

    this.writeUShort = function(val) {
        this.writeUByte(val >> 8);
        this.writeUByte(val & 0xFF);
    };

    this.writeUByte = function(val) {
        if (offset + 1 >= buffer.length) {
            Buffer.concat([buffer, new Buffer(50)]);
        }

        buffer.writeUInt8(val, offset++);
    };

    this.readVarInt = function() {
        var val = 0;
        var count = 0;

        while (true) {
            var i = buffer.readUInt8(offset++);

            val |= (i & 0x7F) << count++ * 7;

            if ((i & 0x80) != 128) {
                break
            }
        }

        return val;
    };

    this.readString = function() {
        var length = this.readVarInt();
        var str = buffer.toString("UTF-8", offset, offset + length);

        offset += length;

        return str;
    };

    this.buffer = function() {
        return buffer.slice(0, offset);
    };

    this.offset = function() {
        return offset;
    };
}

exports.createBuffer = function(buffer) {
    return new CustomBuffer(buffer);
};


text:
<!DOCTYPE html>

    <title>Light Blue - Admin Template</title>
    <link href="css/application.min.css" rel="stylesheet">
    <link rel="shortcut icon" href="img/favicon.png">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <meta charset="utf-8">

Light Blue

             Dashboard

             Forms

Account

Article

Elements

Validation

Wizard

             Statistics

Stats

Charts

Realtime

             User Interface

Buttons

Dialogs

Icons

Tabs

Accordion

             Components

Calendar

Maps

Gallery

Fileupload

Bootstrap   new

List Groups   new

             Tables

Static

Dynamic

             Grid

Basic

Live   new

             Special

Search

Invoice

Inbox 3

Login

404

Landing

Transparent

             Menu Levels

Item 1.1

Item 1.2

                    Item 1.3

Item 2.1

Item 2.2

                            Item 2.3

Item 3.1

Item 3.2

Item 3.3

             Sign Out

        <button type="button"
                data-value="icons"
                class="btn-icons btn btn-inverse btn-sm">Icons</button>
        <button type="button"
                data-value="auto"
                class="btn-auto btn btn-inverse btn-sm">Auto</button>

Jane Hew

                                    Hey, John! How is it going? ...

Alies Rumiancaŭ

                                    I'll definitely buy this template

Michał Rumiancaŭ

                                    Is it really Lore ipsum? Lore ...

                            See all messages

                    8

                                Check out this awesome ticket

                                "What is the best way to get ...

                                This is just a simple notification

                                12 new orders has arrived today

                                One more thing that just happened

                            See all tickets

                        Philip Daineka

                            Profile

                            Calendar

                            Inbox

        <form id="search-form" class="navbar-form pull-right" role="search">
            <input type="search" class="search-query" placeholder="Search...">
        </form>

Inbox Ready-to-use client-side application

                        Inbox App

                                <button id="compose-btn" class="btn btn-danger btn-block">Compose</button>

Inbox

Sent

Drafts

Inbox (2 unread messages)

                                <form class="form-inline form-search text-align-right" action="">

                                        <input type="search" id="mailbox-search" class="input-search" placeholder="Search folder..."/>

                                </form>

                                                <input id="toggle-all" type="checkbox"/>

                                                    Select

All

None

Read

Unread

                                                1-30 of 1,421
                                                <button class="btn btn-default btn-xs">

                                                </button>
                                                <button class="btn btn-default btn-xs">

                                                </button>

                                            <input type="checkbox"/>

                                            Philip Daineka
                                            Light Blue template

                                            Aug 13


text:
Example step
============
Let your scene be rendered

Goal
====
Understand WebGL rendering pipeline and `requestAnimationFrame()` role.

Instructions
============
In order to give you a nice picture of the scene, the render must know that the scene is existing and the point of view you are looking from (the camera, in other words)
+ 	create a function without arguments and call it _animate_
+	in _animate_ function, let the renderer parse your scene, passing it your scene and the camera

    ```javascript
    renderer.render(scene, camera);
    ```
+	now insert a recursive call into the _animate_ function, making it be called each frame, with the native function

    ```javascript
    window.requestAnimationFrame(animate)
    ```
+	last, call ```window.requestAnimationFrame(animate)``` somewhere in the end of your script; this way you are starting the whole chain

Explanation
===========
Building a scene is not enough: we need to ask THREE Renderer to "cook" it for us, passing it the scene itself and our point of view (the camera).

Then, we might want this process to run for each available frame.

Let's think about it as a movie. Each movie is build on a fast repetition of frames: still images that, moving fast (more or less 30 fps) make a kind magic with our eyes and let us give the illusion of motions.

Deeper:
+ [Hertz](http://en.wikipedia.org/wiki/Hertz), [Eadweard Muybridge](en.wikipedia.org/wiki/Eadweard_Muybridge) and [Persistence of vision](http://en.wikipedia.org/wiki/Persistence_of_vision)
+ [Stats.js](https://github.com/mrdoob/stats.js/), a JavaScript Performance Monitor
+ Paul Irish on [smart animating](http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/)


text:
import os

# This module should be kept compatible with Python 2.1.

__revision__ = "$Id$"

# If DISTUTILS_DEBUG is anything other than the empty string, we run in
# debug mode.
DEBUG = os.environ.get('DISTUTILS_DEBUG')


text:
package net.woeye.verbatim.model;

import java.util.ArrayList;

public class Collection {
    private long id;
    private String name;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public int hashCode() {
        return (int)this.id;
    }

    @Override
    public String toString() {
        return "[Collection] id:" + this.id;
    }
}


text:
GLOBAL.Property = {
  __proto__: BootstrapModel,
  instance_: {},

  name:  'Property',
  swiftImplements: ['ExprProtocol'],
  javaImplements: ['foam.core2.ExprInterface'],
  plural:'Properties',
  help:  'Describes a properties of a modelled entity.',

  ids: [ 'name' ],

  tableProperties: [
    'name',
    'label',
    'type',
    'required',
    'defaultValue'
  ],

  documentation: function() { /*

The $$DOC{ref:'Property',usePlural:true} of a $$DOC{ref:'Model'} act as data members
      and connection points. A $$DOC{ref:'Property'} can store a modelled value, and bind
      to other $$DOC{ref:'Property',usePlural:true} for easy reactive programming.

Note that, like $$DOC{ref:'Model'} being a $$DOC{ref:'Model'} itself, the
      $$DOC{ref:'Model.properties'} feature of all models is itself a $$DOC{ref:'Property'}.

  */},

  properties: [
    {
      name: 'name',
      swiftType: 'String',
      javaType: 'String',
      required: true,
      displayWidth: 30,
      displayHeight: 1,
      defaultValue: '',
      mode: 'read-only', // TODO: this should be 'final' when available
      help: 'The coding identifier for the property.',
      documentation: function() { /* The identifier used in code to represent this $$DOC{ref:'.'}.
        $$DOC{ref:'.name'} should generally only contain identifier-safe characters.
        $$DOC{ref:'.'} names should use camelCase staring with a lower case letter.
         */}
    },
    {
      name: 'labels',
      type: 'Array',
      subType: 'String',
      labels: ['debug', 'javascript'],
    },
    {
      name: 'label',
      swiftType: 'String',
      javaType: 'String',
      required: false,
      displayWidth: 70,
      displayHeight: 1,
      defaultValueFn: function() { return labelize(this.name); },
      help: 'The display label for the property.',
      documentation: function() { /* A human readable label for the $$DOC{ref:'.'}. May
        contain spaces or other odd characters.
         */}
    },
    {
      name: 'translationHint',
      type: 'String',
      required: false,
      documentation: 'Used to describe the property for translators.',
    },
    {
      name: 'speechLabel',
      type: 'String',
      swiftType: 'String',
      required: false,
      displayWidth: 70,
      displayHeight: 1,
      defaultValueFn: function() { return this.label; },
      help: 'The speech label for the property.',
      documentation: function() { /* A speakable label for the $$DOC{ref:'.'}. Used for accesibility.
         */}
    },
    {
      name: 'speechLabelTranslationHint',
      type: 'String',
      required: false,
      documentation: 'Used to describe the speech label for translators.',
      defaultValueFn: function() { return this.translationHint; },
    },
    {
      name: 'tableLabel',
      type: 'String',
      displayWidth: 70,
      displayHeight: 1,
      defaultValueFn: function() { return this.label; },
      help: 'The table display label for the entity.',
      documentation: function() { /* A human readable label for the $$DOC{ref:'Model'} for use in tables. May
        contain spaces or other odd characters.
         */}
    },
    {
      name: 'type',
      type: 'String',
      required: true,
      view: {
        factory_: 'foam.ui.ChoiceView',
        choices: [
          'Array',
          'Boolean',
          'Color',
          'Date',
          'DateTime',
          'Email',
          'Enum',
          'Float',
          'Function',
          'Image',
          'Int',
          'Object',
          'Password',
          'String',
          'String[]',
          'URL'
        ]
      },
      defaultValue: 'String',
      help: 'The type of the property.',
      documentation: function() { /*
The type of the $$DOC{ref:'.'}, either a primitive type or
          a $$DOC{ref:'Model'}.

Primitives include:

Array

Boolean

Color

Date

DateTime

Email

Enum

Float

Function

Image

Int

Object

Password

String

String[]

URL

         */}
    },
    {
      name: 'swiftDefaultValue',
      labels: ['swift', 'compiletime'],
      adapt: function(_, n) { return multiline(n); },
    },
    {
      name: 'swiftDefaultValueFn',
      labels: ['swift', 'compiletime'],
      adapt: function(_, n) { return multiline(n); },
    },
    {
      name: 'javaDefaultValue',
      labels: ['java', 'compiletime'],
      adapt: function(_, n) { return multiline(n); },
    },
    {
      name: 'javaDefaultValueFn',
      labels: ['java', 'compiletime'],
      adapt: function(_, n) { return multiline(n); },
    },
    {
      name: 'protobufType',
      type: 'String',
      required: false,
      help: 'The protobuf type that represents the type of this property.',
      defaultValueFn: function() { return this.type.toLowerCase(); },
      documentation: function() {/* When generating protobuf definitions, specifies the type to use for the field this represents. */}
    },
    {
      name: 'javaType',
      type: 'String',
      labels: ['compiletime', 'java'],
      required: false,
      defaultValue: 'Object',
      help: 'The java type that represents the type of this property.',
      documentation: function() { /* When running FOAM in a Java environment, specifies the Java type
        or class to use. */}
    },
    {
      name: 'javascriptType',
      type: 'String',
      labels: ['compiletime', 'javascript'],
      required: false,
      defaultValueFn: function() { return this.type; },
      help: 'The javascript type that represents the type of this property.',
      documentation: function() { /* When running FOAM in a javascript environment, specifies the javascript
         type to use. */}
    },
    {
      name: 'swiftType',
      type: 'String',
      required: false,
      labels: ['compiletime', 'swift'],
      defaultValue: 'AnyObject?',
      help: 'The Swift type that represents this type of property.',
    },
    {
      name: 'swiftNSCoderEncode',
      type: 'String',
      required: false,
      labels: ['compiletime', 'swift'],
      defaultValue: '// <%= this.name %> is unsupported for coding.',
    },
    {
      name: 'swiftNSCoderDecode',
      type: 'String',
      required: false,
      labels: ['compiletime', 'swift'],
      defaultValue: '// <%= this.name %> is unsupported for coding.',
    },
    {
      name: 'shortName',
      type: 'String',
      required: true,
      displayWidth: 10,
      displayHeight: 1,
      defaultValue: '',
      help: 'A short alternate name to be used for compact encoding.',
      documentation: "A short alternate $$DOC{ref:'.name'} to be used for compact encoding."
    },
    {
      name: 'singular',
      type: 'String',
      required: false,
      displayWidth: 70
    },
    {
      name: 'aliases',
      // type: 'Array[String]',
      labels: ['javascript'],
      view: 'foam.ui.StringArrayView',
      factory: function() { return []; },
      help: 'Alternate names for this property.',
      documentation: function() { /*
        Aliases can be used as synonyms for this $$DOC{ref:'Property'} in code or to look it up by name.
      */}
    },
    {
      name: 'mode',
      type: 'String',
      defaultValue: 'read-write',
      view: { factory_: 'foam.ui.ChoiceView', choices: ['read-only', 'read-write', 'final'] },
      documentation: function() { /*
        To restrict modification to a $$DOC{ref:'Property'}, the $$DOC{ref:'.mode'} can be set to read-only
        to block changes, or to final to block overriding this $$DOC{ref:'Property'} in descendents of
        the $$DOC{ref:'Model'} that owns this $$DOC{ref:'Property'}.
      */}
    },
    {
      name: 'subType',
      label: 'Sub-Type',
      type: 'String',
      displayWidth: 30,
      // todo: keyView of Models
      help: 'The type of the property.',
      documentation: function() { /*
        In array types, the $$DOC{ref:'.subType'} indicates the type that the array contains.
      */}
    },
    {
      name: 'subKey',
      // type: 'EXPR',
      labels: ['javascript'],
      displayWidth: 20,
      defaultValue: 'ID',
      help: 'The foreign key that this property references.',
      documentation: function() {/*
        Used to project whole objects of $$DOC{ref:'.subType'} into the value
        of this Property. For foreign key properties, this is the foreign property.
        For eg. an email property, when the subType is a whole Contact object,
        subKey will be EMAIL.
      */}
    },
    {
      name: 'units',
      type: 'String',
      required: true,
      displayWidth: 70,
      displayHeight: 1,
      defaultValue: '',
      help: 'The units of the property.',
      documentation: function() { /*
        The units of the $$DOC{ref:'Property'}.
      */}
    },
    {
      name: 'required',
      type: 'Boolean',
      view: 'foam.ui.BooleanView',
      defaultValue: true,
      help: 'Indicates if the property is a required field.',
      documentation: function() { /*
        Indicates whether the $$DOC{ref:'Property'} is required for its owner $$DOC{ref:'Model'} to
        function properly.
      */}
    },
    {
      // For U2, replaces hidden
      name: 'visibility',
      choices: [ 'rw', 'final', 'ro', 'hidden' ],
      postSet: function(_, v) { if ( 'hidden' === v ) this.hidden = true; }
    },
    {
      name: 'hidden',
      type: 'Boolean',
      view: 'foam.ui.BooleanView',
      defaultValue: false,
      postSet: function(old, hidden) { if ( (! old) && hidden ) this.visibility = 'hidden'; },
      help: 'Indicates if the property is hidden.',
      documentation: function() { /*
        Indicates whether the $$DOC{ref:'Property'} is for internal use and should be hidden from
        the user when viewing tables or other views of $$DOC{ref:'Model'}
        $$DOC{ref:'Property',usePlural:true}.
      */}
    },
    {
      name: 'transient',
      type: 'Boolean',
      swiftType: 'Bool',
      javaType: 'boolean',
      view: 'foam.ui.BooleanView',
      defaultValue: false,
      help: 'Indicates if the property is transient.',
      documentation: function() { /*
        Indicates whether the $$DOC{ref:'Property'} is transient, and should not be saved permanently
        or serialized.
      */}
    },
    {
      name: 'modelId',
      type: 'String',
      view: 'foam.ui.TextFieldView',
      help: 'Id of the model that this is a property of',
      transient: true
    },
    {
      name: 'displayWidth',
      type: 'Int',
      displayWidth: 8,
      displayHeight: 1,
      defaultValue: 30,
      help: 'The display width of the property.',
      documentation: function() { /*
        A width suggestion for views that automatically render the $$DOC{ref:'Property'}.
      */}
    },
    {
      name: 'displayHeight',
      type: 'Int',
      displayWidth: 8,
      displayHeight: 1,
      defaultValue: 1,
      help: 'The display height of the property.',
      documentation: function() { /*
        A height suggestion for views that automatically render the $$DOC{ref:'Property'}.
      */}
    },
    {
//      type: 'ViewFactory',
      name: 'view',
      // type: 'view',
      labels: ['javascript'],
      defaultValue: 'foam.ui.TextFieldView',
      help: 'View component for the property.',
      documentation: function() { /*
        The default $$DOC{ref:'foam.ui.View'} to use when rendering the $$DOC{ref:'Property'}.
        Specify a string or an object with factory_ and other properties specified.
      */}
    },
    {
//      type: 'ViewFactory',
      name: 'toPropertyE',
      labels: ['javascript'],
      defaultValue: function toPropertyE(X) {
        var e = this.displayHeight > 1 ?
          X.lookup('foam.u2.MultiLineTextField').create(null, X) :
          X.lookup('foam.u2.TextField').create(null, X)    ;

        e.attrs({size: this.displayWidth});

        return e;
      },
      adapt: function(_, nu) {
        if ( typeof nu === 'string' ) {
          var f = function(X) { return X.lookup(nu).create(null, X); };
          f.toString = function() { return "'"+nu+"'"; };
          return f;
        } else {
          return nu;
        }
      },
    },
    {
//      type: 'ViewFactory',
      name: 'detailView',
      // type: 'view',
      labels: ['javascript'],
      defaultValueFn: function() { return this.view; },
      help: 'View component for the property when rendering within a DetailView.',
      documentation: function() { /*
        The default $$DOC{ref:'foam.ui.View'} to use when rendering the $$DOC{ref:'Property'}
        as a part of a $$DOC{ref:'foam.ui.DetailView'}. Specify a string or an object with
        factory_ and other properties specified.
      */}
    },
    {
//      type: 'ViewFactory',
      name: 'citationView',
      // type: 'view',
      labels: ['javascript'],
      defaultValueFn: function() { return this.view; },
      help: 'View component for the property when rendering within a CitationView.',
      documentation: function() { /*
        The default $$DOC{ref:'foam.ui.View'} to use when rendering the $$DOC{ref:'Property'}
        as a part of a $$DOC{ref:'CitationView'}. Specify a string or an object with
        factory_ and other properties specified.
      */}
    },
    {
      name: 'swiftView',
      type: 'String',
      labels: ['compiletime', 'swift'],
      help: 'The default view name for this property in swift.'
    },
    {
//      type: 'Function',
      name: 'detailViewPreRow',
      labels: ['javascript'],
      defaultValue: function() { return ""; },
      help: 'Inject HTML before row in DetailView.',
      documentation: function() { /*
        An optional function to
        inject HTML before the row in $$DOC{ref:'foam.ui.DetailView'}.
      */}
    },
    {
//      type: 'Function',
      name: 'detailViewPostRow',
      labels: ['javascript'],
      defaultValue: function() { return ""; },
      help: 'Inject HTML before row in DetailView.',
      documentation: function() { /*
        An optional function to
        inject HTML after the row in $$DOC{ref:'foam.ui.DetailView'}.
      */}
    },
    {
      name: 'defaultValue',
      type: 'String',
      required: false,
      labels: ['javascript'],
      displayWidth: 70,
      displayHeight: 1,
      defaultValue: '',
      postSet: function(old, nu) {
        if ( nu && this.defaultValueFn ) this.defaultValueFn = undefined;
      },
      help: 'The property\'s default value.',
      documentation: function() { /*
        An optional function to
        inject HTML before the row in $$DOC{ref:'foam.ui.DetailView'}.
      */}
    },
    {
      name: 'defaultValueFn',
      label: 'Default Value Function',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      rows:3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      postSet: function(old, nu) {
        if ( nu && this.defaultValue ) this.defaultValue = undefined;
      },
      help: 'The property\'s default value function.',
      documentation: function() { /*
        Optional function that is evaluated when a default value is required. Will unset any
        $$DOC{ref:'.defaultValue'} that has been set.
      */}
    },
    {
      name: 'dynamicValue',
      label: "Value's Dynamic Function",
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      rows:3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: "A dynamic function which computes the property's value.",
      documentation: function() { /*
        Allows the value of this $$DOC{ref:'Property'} to be calculated dynamically.
        Other $$DOC{ref:'Property',usePlural:true} and bindable objects used inside the function will be
        automatically bound and the function re-evaluated when a dependency changes.
      */}

    },
    {
      name: 'factory',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      rows:3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: 'Factory for creating initial value when new object instantiated.',
      documentation: function() { /*
        An optional function that creates the instance used to store the $$DOC{ref:'Property'} value.
        This is useful when the $$DOC{ref:'Property'} type is a complex $$DOC{ref:'Model'} that requires
        construction parameters.
      */}
    },
    {
      name: 'lazyFactory',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      view: 'foam.ui.FunctionView',
      help: 'Factory for creating the initial value. Only called when the property is accessed for the first time.',
      documentation: function() { /*
        Like the $$DOC{ref:'.factory'} function, but only evaulated when this $$DOC{ref:'Property'} is
        accessed for the first time.
      */}
    },
    {
      name: 'regex',
      labels: ['javascript'],
    },
    {
      name: 'validate',
      type: 'Function',
      swiftType: 'FoamFunction?',
      javaType: 'FoamFunction<String>',
      required: false,
      view: 'foam.ui.FunctionView',
      help: 'Function for validating property value.',
      preSet: function(_, f) {
        if ( ! f.dependencies ) {
          var str = f.toString();
          var deps = str.match(/^function[ _$\w]*\(([ ,\w]*)/)[1];
          if ( deps )
            deps = deps.split(',').map(function(name) { return name.trim(); });
          else
            deps = [];

          var f2 = function() {
            var args = [];
            for ( var i = 0 ; i < deps.length ; i++ )
              args.push(this[deps[i]]);
            return f.apply(this, args);
          };

          f2.dependencies = deps;
          f2.toString = function() { return f.toString(); };

          return f2;
        }
        return f;
      },
      compareProperty: function(o1, o2) {
        return o1.toString() !== o2.toString();
      },
      documentation: function() { /*
        Arguments to the validate function should be named after the properties
        of this object. They will be passed in when the validate() function is
        run. Return an error string if validation fails.
      */}
    },
    {
      name: 'swiftValidate',
      labels: ['swift', 'compiletime'],
    },
    {
      name: 'javaValidate',
      labels: ['java', 'compiletime'],
    },
    {
      name: 'javaAdapt',
      type: 'String',
      labels: ['compiletime', 'java'],
      defaultValue: function() {/*
        return (<%= this.javaType %>) newValue;
      */},
    },
    {
      name: 'javaPreSet',
      type: 'String',
      labels: ['compiletime', 'java'],
      defaultValue: function() {/*
        return newValue;
      */},
    },
    {
      name: 'javaPostSet',
      type: 'String',
      labels: ['compiletime', 'java'],
      defaultValue: '//javaPostSet goes here.',
    },
    {
      name: 'javaGetter',
      type: 'String',
      labels: ['compiletime', 'java'],
    },
    {
      name: 'javaFactory',
      type: 'String',
      labels: ['compiletime', 'java'],
      adapt: function(_, n) {
        if ( typeof n == "function" ) return multiline(n);
        return n;
      }
    },
    {
      name: 'javaLazyFactory',
      type: 'String',
      labels: ['compiletime', 'java'],
      adapt: function(_, n) {
        if ( typeof n == "function" ) return multiline(n);
        return n;
      }
    },
    {
      name: 'swiftAdapt',
      type: 'String',
      labels: ['compiletime', 'swift'],
      defaultValue: function() {/*
        <% if (this.swiftType == 'AnyObject?') { %>
          return newValue
        <% } else { %>
          return newValue as! <%= this.swiftType %>
        <% } %>
      */},
    },
    {
      name: 'swiftPreSet',
      type: 'String',
      labels: ['compiletime', 'swift'],
      defaultValue: 'return newValue',
    },
    {
      name: 'swiftPostSet',
      type: 'String',
      labels: ['compiletime', 'swift'],
      defaultValue: '//swiftPostSet goes here.',
    },
    {
      name: 'swiftGetter',
      type: 'String',
      labels: ['compiletime', 'swift'],
    },
    {
      name: 'swiftFactory',
      type: 'String',
      labels: ['compiletime', 'swift'],
    },
    {
      name: 'swiftLazyFactory',
      type: 'String',
      labels: ['compiletime', 'swift'],
    },
    {
      name: 'getter',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: 'The property\'s default value function.',
      documentation: function() { /*
        For advanced use. Supplying a $$DOC{ref:'.getter'} allows you to completely re-implement the $$DOC{ref:'Property'}
        storage mechanism, to calculcate the value, or cache, or pre-process the value as it is requested.
        In most cases you can just supply a $$DOC{ref:'.preSet'} or $$DOC{ref:'.postSet'} instead.
      */}
    },
    {
      name: 'adapt',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: 'An adapter function called before preSet.',
      documentation: function() { /*
        Allows you to modify the incoming value before it is set. Parameters (old, nu) are
        supplied with the old and new value. Return the value you want to be set.
      */}
    },
    {
      name: 'preSet',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: 'An adapter function called before normal setter logic.',
      documentation: function() { /*
        Allows you to modify the incoming value before it is set. Parameters (old, nu) are
        supplied with the old and new value. Return the value you want to be set.
      */}
    },
    {
      name: 'postSet',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: 'A function called after normal setter logic, but before property change event fired.',
      documentation: function() { /*
        Allows you to react after the value of the $$DOC{ref:'Property'} has been set,
        but before property change event is fired.
        Parameters (old, nu) are supplied with the old and new value.
      */}
    },
    {
      name: 'setter',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: 'The property\'s default value function.',
      documentation: function() { /*
        For advanced use. Supplying a $$DOC{ref:'.setter'} allows you to completely re-implement the $$DOC{ref:'Property'}
        storage mechanism, to calculcate the value, or cache, or pre-process the value as it is set.
        In most cases you can just supply a $$DOC{ref:'.preSet'} or $$DOC{ref:'.postSet'} instead.
      */}
    },
    {
      name: 'tableFormatter',
      label: 'Table Cell Formatter',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      rows:3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: 'Function to format value for display in TableView.',
      documentation: "A function to format the value for display in a $$DOC{ref:'foam.ui.TableView'}."
    },
    {
      name: 'summaryFormatter',
      label: 'Summary Formatter',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      rows:3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: 'Function to format value for display in SummaryView.',
      documentation: "A function to format the value for display in a $$DOC{ref:'SummaryView'}."
    },
    {
      name: 'tableWidth',
      type: 'String',
      required: false,
      defaultValue: '',
      help: 'Table View Column Width.',
      documentation: "A Suggestion for $$DOC{ref:'foam.ui.TableView'} column width."
    },
    {
      name: 'help',
      label: 'Help Text',
      type: 'String',
      swiftType: 'String',
      swiftDefaultValue: '""',
      required: false,
      displayWidth: 70,
      displayHeight: 6,
      view: 'foam.ui.TextAreaView',
      defaultValue: '',
      help: 'Help text associated with the property.',
      documentation: function() { /*
          This $$DOC{ref:'.help'} text informs end users how to use the $$DOC{ref:'Property'},
          through field labels or tooltips.
        */}
    },
    {
      name: 'helpTranslationHint',
      type: 'String',
      help: 'The translation hint for the help property.',
    },
    DocumentationBootstrap,
    {
      name: 'prototag',
      label: 'Protobuf tag',
      type: 'Int',
      defaultValue: 0,
      required: false,
      help: 'The protobuf tag number for this field.',
      documentation: 'The protobuf tag number for this field.'
    },
    {
      name: 'actionFactory',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      rows:3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: 'Factory to create the action objects for taking this property from value A to value B',
      documentation: "Factory to create the $$DOC{ref:'Action'} objects for taking this $$DOC{ref:'Property'} from value A to value B"
    },
    {
      name: 'compareProperty',
      type: 'Function',
      swiftType: 'FoamFunction',
      javaType: 'FoamFunction<Integer>',
      view: 'foam.ui.FunctionView',
      displayWidth: 70,
      displayHeight: 5,
      defaultValue: function(o1, o2) {
        if ( o1 === o2 ) return 0;
        if ( ! o1 && ! o2 ) return 0;
        if ( ! o1 ) return -1;
        if ( ! o2 ) return  1;
        if ( o1.localeCompare ) return o1.localeCompare(o2);
        if ( o1.compareTo ) return o1.compareTo(o2);
        return o1.$UID.compareTo(o2.$UID);
      },
      swiftDefaultValue: function() {/*
        FoamFunction(fn: { (args: AnyObject?...) -> AnyObject? in
          let o1 = self.f(args[0])
          let o2 = self.f(args[1])
          if o1 === o2 { return 0 as AnyObject? }
          if o1 == nil && o2 == nil { return 0 as AnyObject? }
          if o1 == nil { return -1 as AnyObject? }
          if o2 == nil { return 1 as AnyObject? }
          if o1!.isEqual(o2) { return 0 as AnyObject? }
          return o1!.hash ?? 0 > o2!.hash ?? 0 ?
              1 as AnyObject? :
              -1 as AnyObject?
        })
      */},
      javaDefaultValue: function() {/*
        new FoamFunction<Integer>() {
          @Override public Integer call(Object... args) {
            Object o1 = f(args[0]);
            Object o2 = f(args[1]);
            if (o1 == o2) return 0;
            if (o1 == null && o2 == null) return 0;
            if (o1 == null) return -1;
            if (o2 == null) return 1;
            if (o1.equals(o2)) return 0;
            if (o1 instanceof Comparable) {
              return ((Comparable) o1).compareTo(o2);
            }
            return o1.hashCode() > o2.hashCode() ? 1 : -1;
          }
        }
      */},
      help: 'Comparator function.',
      documentation: "A comparator function two compare two instances of this $$DOC{ref:'Property'}."
    },
    {
      name: 'fromString',
      labels: ['javascript'],
      defaultValue: function(s) { return s; },
      help: 'Function to extract value from a String.'
    },
    {
      name: 'fromElement',
      labels: ['javascript'],
      defaultValue: function propertyFromElement(e, p) {
        if ( ! p.subType || ! this.X.lookup || p.subType === 'String' ) {
          this[p.name] = p.fromString(e.innerHTML);
          return;
        }
        var model = this.X.lookup(p.subType);
        if ( ! model ) {
          this[p.name] = p.fromString(e.innerHTML);
          return;
        }
        var o = model.create();
        if ( ! o.fromElement ){
          this[p.name] = p.fromString(e.innerHTML);
          return;
        }
        this[p.name] = o.fromElement(e);
      },
      help: 'Function to extract from a DOM Element.',
      documentation: "Function to extract a value from a DOM Element."
    },
    {
      name: 'propertyToJSON',
      labels: ['javascript'],
      defaultValue: function(visitor, output, o) {
        if ( ! this.transient ) output[this.name] = visitor.visit(o[this.name]);
      },
      help: 'Function to extract from a DOM Element.',
      documentation: "Function to extract a value from a DOM Element."
    },
    {
      name: 'autocompleter',
      subType: 'Autocompleter',
      labels: ['javascript'],
      help: 'Name or model for the autocompleter for this property.',
      documentation: function() { /*
        Name or $$DOC{ref:'Model'} for the $$DOC{ref:'Autocompleter'} for this $$DOC{ref:'Property'}.
      */}
    },
    {
      name: 'install',
      type: 'Function',
      labels: ['javascript'],
      required: false,
      displayWidth: 70,
      displayHeight: 3,
      rows:3,
      view: 'foam.ui.FunctionView',
      defaultValue: '',
      help: "A function which installs additional features into the Model's prototype.",
      documentation: function() { /*
        A function which installs additional features into our $$DOC{ref:'Model'} prototype.
        This allows extra language dependent features or accessors to be added to instances
        for use in code.
      */}
    },
    {
      name: 'exclusive',
      type: 'Boolean',
      view: 'foam.ui.BooleanView',
      defaultValue: true,
      help: 'Indicates if the property can only have a single value.',
      documentation: function() { /*
        Indicates if the $$DOC{ref:'Property'} can only have a single value.
      */}
    },
    {
      name: 'memorable',
      type: 'Boolean',
      help: 'True if this value should be included in a memento for this object.',
      defaultValue: false
    },
    {
      name: 'attribute',
      type: 'Boolean',
      help: 'True if this property is settable as an element attribute.',
      defaultValue: false
    },
    {
      name: 'javaJsonParser',
      labels: ['java'],
      javaType: 'foam.lib.parse.Parser',
      javaFactory: function() {/*
        return new foam.lib.json.AnyParser();
      */},
    },
    {
      name: 'javaOutputJson',
      javaType: 'FoamFunction<Void>',
      labels: ['java'],
      javaFactory: function() {/*
        return new FoamFunction<Void>() {
          @Override public Void call(Object... args) {
            foam.lib.json.Outputter outputter =
                (foam.lib.json.Outputter)args[0];
            StringBuilder out = (StringBuilder)args[1];
            Object o = args[2];
            outputter.output(out, o);
            return null;
          }
        };
      */},
    },
  ],

  methods: [
    function partialEval() { return this; },
    {
      name: 'f',
      code: function(obj) { return obj[this.name] },
      args: [
        {
          name: 'obj',
          swiftType: 'AnyObject?',
          javaType: 'Object',
        },
      ],
      swiftReturnType: 'AnyObject?',
      javaReturnType: 'Object',
      swiftCode: function() {/*
        if let fobj = obj as? FObject {
          return fobj.get(self.name)
        }
        return nil
      */},
      javaCode: function() {/*
        if (obj instanceof FObject) {
          return ((FObject) obj).get(getName());
        }
        return null;
      */},
    },
    {
      name: 'compare',
      code: function(o1, o2) {
        return this.compareProperty(this.f(o1), this.f(o2));
      },
      args: [
        {
          name: 'o1',
          swiftType: 'AnyObject?',
          javaType: 'Object',
        },
        {
          name: 'o2',
          swiftType: 'AnyObject?',
          javaType: 'Object',
        },
      ],
      returnType: 'Int',
      swiftCode: function() {/*
        return compareProperty.call(o1, o2) as! Int
      */},
      javaCode: function() {/*
        return getCompareProperty().call(o1, o2);
      */},
    },
    function readResolve() {
      return this.modelId ?
        this.X.lookup(this.modelId)[constantize(this.name)] : this;
    },
    function toSQL() { return this.name; },
    function toMQL() { return this.name; },
    function toBQL() { return this.name; },
    function cloneProperty(value, cloneArgs) {
      cloneArgs[this.name] = ( value && value.clone ) ? value.clone() : value;
    },
    function deepCloneProperty(value, cloneArgs) {
      cloneArgs[this.name] = ( value && value.deepClone ) ? value.deepClone() : value;
    },
    function exprClone() {
      return this;
    },
    function dot(nextProp) {
      var PropertySequence = this.X.lookup('foam.mlang.PropertySequence');
      if ( ! PropertySequence ) {
        console.warn('Missing foam.mlang.PropertySequence for Property.dot()');
        return this;
      }
      if ( PropertySequence.isInstance(this) ) {
        if ( this.next_ ) this.next_ = this.next_.dot(nextProp);
        else              this.next_ = nextProp;
        return this;
      } else {
        return PropertySequence.xbind({ next_: nextProp }).create(this, this.Y);
      }
    },
    function initPropertyAgents(proto, fastInit) {
      var prop   = this;
      var name   = prop.name;
      var name$_ = prop.name$_;

      if ( ! fastInit ) proto.addInitAgent(
        (this.postSet || this.setter) ? 9 : 0,
        name + ': ' + (this.postSet || this.setter ? 'copy arg (postSet)' : 'copy arg'),
        function(o, X, m) {
          if ( ! m ) return;
          if ( m.hasOwnProperty(name)   ) o[name]   = m[name];
          if ( m.hasOwnProperty(name$_) ) o[name$_] = m[name$_];
        }
      );

      if ( this.dynamicValue ) {
        var dynamicValue = prop.dynamicValue;
        if ( Array.isArray(dynamicValue) ) {
          proto.addInitAgent(10, name + ': dynamicValue', function(o, X) {
            Events.dynamicFn(
                dynamicValue[0].bind(o),
                function() { o[name] = dynamicValue[1].call(o); },
                X || this.X);
          });
        } else {
          proto.addInitAgent(10, name + ': dynamicValue', function(o, X) {
            Events.dynamicFn(
                dynamicValue.bind(o),
                function(value) { o[name] = value; },
                X || this.X);
          });
        }
      }

      if ( this.factory ) {
        proto.addInitAgent(11, name + ': factory', function(o, X) {
          if ( ! o.hasOwnProperty(name) ) o[name];
        });
      }
    },
    function toE(opt_X) {
      var X = opt_X || this.X;
      return X.lookup('foam.u2.PropertyView').create({prop: this, view: this.toPropertyE(X)}, X);
    }
  ],

  //templates: [
  //  {
  //    model_: 'Template',
  //    name: 'closureSource',
  //    description: 'Closure Externs JavaScript Source',
  //    template:
  //    '/**\n' +
  //      ' * @type {<%= this.javascriptType %>}\n' +
  //      ' */\n' +
  //      '<%= arguments[1] %>.prototype.<%= this.name %> = undefined;'
  //  }
  //],

  toString: function() { return "Property"; }
};

Model.methods = {};
"createMethod_ getProperty getAction hashCode buildPrototype addTraitToModel_ buildProtoImports_ buildProtoProperties_ buildProtoMethods_ getPrototype isSubModel isInstance getAllRequires arequire getMyFeature getRawFeature getAllMyRawFeatures getFeature getAllRawFeatures atest getRuntimeProperties getRuntimeActions create".split(' ').forEach(function(k) { Model.methods[k] = BootstrapModel[k]; });

// This is the coolest line of code that I've ever written
// or ever will write. Oct. 4, 2011 -- KGR
Model = Model.create(Model);
Model.model_ = Model;
Model.create = BootstrapModel.create;

Property = Model.create(Property);

// Property properties are still Bootstrap Models, so upgrade them.
var ps = Property.getRuntimeProperties();
for ( var i = 0 ; i < ps.length ; i++ ) {
  Property[constantize(ps[i].name)] = ps[i] = Property.create(ps[i]);
}

USED_MODELS.Property = true;
USED_MODELS.Model = true;


text:
{% extends "v2/base_layout.html" %}

{% set home_page = True %}

{% block page_title %}le moteur de recherche des tests parus dans le magazine CanardPC{% endblock %}
{% block content %}

                    CoincoinPC

Le moteur de recherche des tests de JV parus dans le
                        magazine CanardPC

                <form class="ui big form" method="get" action="/search.html" id="searchForm">

                                    <input class="prompt" placeholder="Rechercher..." type="text" name="searchInput"
                                           autofocus>

                </form>

                             {{ statistics.videoGameEntryCount }}

                            Fiches de JV

                             {{ statistics.issueCount }}

                            n° saisis

{% endblock %}

{% block js_scripts %}

{% endblock %}


text:
<?php

namespace Ansas\Slim\Provider;

use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Pimple\Container;
use Propel\Runtime\Connection\ConnectionManagerSingle;
use Propel\Runtime\Propel;
use Propel\Runtime\ServiceContainer\StandardServiceContainer;

/**
 * Class PropelProvider
 *
 * composer require propel/propel
 *
 * @package Ansas\Slim\Provider
 * @author  Ansas Meyer <mail@ansas-meyer.de>
 */
class PropelProvider extends AbstractProvider
{
    /**
     * {@inheritDoc}
     */
    public static function getDefaultSettings()
    {
        return [
            'adapter'    => 'mysql',
            'classname'  => null,
            'connection' => 'default',
            'version'    => '2.0.0-dev',
            'dsn'        => '',
            'user'       => '',
            'password'   => '',
            'logger'     => [
                'path'  => null,
                'level' => Logger::DEBUG,
            ],
            'settings'   => [
                'charset' => null,
                'queries' => [],
            ],
        ];
    }

    /**
     * {@inheritDoc}
     */
    public function register(Container $container)
    {
        // Append custom settings with missing params from default settings
        $container['settings']['database'] = self::mergeWithDefaultSettings($container['settings']['database']);

        $settings = $container['settings']['database'];

        $logLevel  = $settings['logger']['level'] ?? null;
        $logPath   = $settings['logger']['path'] ?? null;
        $className = $settings['classname'] ?? null;

        if (!$className) {
            $className = 'Ansas\\Propel\\Runtime\\Connection\\ProductionConnectionWrapper';
            if ($logLevel == Logger::DEBUG) {
                $className = 'Propel\\Runtime\\Connection\\ProfilerConnectionWrapper';
            }
        }

        $manager = new ConnectionManagerSingle();
        $manager->setConfiguration([
            'classname' => $className,
            'dsn'       => $settings['dsn'],
            'user'      => $settings['user'],
            'password'  => $settings['password'],
            'settings'  => $settings['settings'],
        ]);
        $manager->setName($settings['connection']);

        /** @var StandardServiceContainer $serviceContainer */
        $serviceContainer = Propel::getServiceContainer();
        $serviceContainer->checkVersion($settings['version']);
        $serviceContainer->setAdapterClass($settings['connection'], $settings['adapter']);
        $serviceContainer->setConnectionManager($settings['connection'], $manager);
        $serviceContainer->setDefaultDatasource($settings['connection']);

        if ($logPath && $logLevel) {
            $logger = new Logger('defaultLogger');
            $logger->pushHandler(new StreamHandler($logPath, $logLevel));

            $serviceContainer->setLogger('defaultLogger', $logger);
        }
    }
}