text:
package io.airlift.http.server;

import com.google.common.base.Preconditions;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Locale;

class TimingFilter
        implements Filter
{
    public static final String FIRST_BYTE_TIME = TimingFilter.class.getName() + ".FIRST_BYTE_TIME";

    @Override
    public void init(FilterConfig filterConfig)
            throws ServletException
    {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
            throws IOException, ServletException
    {
        TimedResponse response = new TimedResponse((HttpServletResponse) servletResponse);
        try {
            chain.doFilter(servletRequest, response);
        }
        finally {
            Long firstByteTime = response.getFirstByteTime();
            if (firstByteTime != null) {
                servletRequest.setAttribute(FIRST_BYTE_TIME, firstByteTime);
            }
        }
    }

    @Override
    public void destroy()
    {
    }

    private static class TimedResponse extends HttpServletResponseWrapper
    {
        private TimedServletOutputStream outputStream;
        private TimedPrintWriter printWriter;

        private TimedResponse(HttpServletResponse response)
        {
            super(response);
        }

        @Override
        public ServletOutputStream getOutputStream()
                throws IOException
        {
            Preconditions.checkState(printWriter == null, "getWriter() has already been called");
            if (outputStream == null) {
                outputStream = new TimedServletOutputStream(super.getOutputStream());
            }
            return outputStream;
        }

        @Override
        public PrintWriter getWriter()
                throws IOException
        {
            Preconditions.checkState(outputStream == null, "getOutputStream() has already been called");
            if (printWriter == null) {
                printWriter = new TimedPrintWriter(super.getWriter());
            }
            return printWriter;
        }

        public Long getFirstByteTime()
        {
            if (outputStream != null) {
                return outputStream.getFirstByteTime();
            }
            if (printWriter != null) {
                return printWriter.getFirstByteTime();
            }
            return null;
        }
    }

    private static class TimedServletOutputStream extends ServletOutputStream
    {
        private final ServletOutputStream delegate;
        private Long firstByteTime;

        private TimedServletOutputStream(ServletOutputStream delegate)
        {
            this.delegate = delegate;
        }

        public Long getFirstByteTime()
        {
            return firstByteTime;
        }

        private void recordFirstByteTime()
        {
            if (firstByteTime == null) {
                firstByteTime = System.currentTimeMillis();
            }
        }

        @Override
        public void write(int b)
                throws IOException
        {
            recordFirstByteTime();
            delegate.write(b);
        }

        @Override
        public void write(byte[] b)
                throws IOException
        {
            recordFirstByteTime();
            delegate.write(b);
        }

        @Override
        public void print(String s)
                throws IOException
        {
            recordFirstByteTime();
            delegate.print(s);
        }

        @Override
        public void write(byte[] b, int off, int len)
                throws IOException
        {
            recordFirstByteTime();
            delegate.write(b, off, len);
        }

        @Override
        public void print(boolean b)
                throws IOException
        {
            recordFirstByteTime();
            delegate.print(b);
        }

        @Override
        public void print(char c)
                throws IOException
        {
            recordFirstByteTime();
            delegate.print(c);
        }

        @Override
        public void print(int i)
                throws IOException
        {
            recordFirstByteTime();
            delegate.print(i);
        }

        @Override
        public void print(long l)
                throws IOException
        {
            recordFirstByteTime();
            delegate.print(l);
        }

        @Override
        public void print(float f)
                throws IOException
        {
            recordFirstByteTime();
            delegate.print(f);
        }

        @Override
        public void print(double d)
                throws IOException
        {
            recordFirstByteTime();
            delegate.print(d);
        }

        @Override
        public void println()
                throws IOException
        {
            recordFirstByteTime();
            delegate.println();
        }

        @Override
        public void println(String s)
                throws IOException
        {
            recordFirstByteTime();
            delegate.println(s);
        }

        @Override
        public void println(boolean b)
                throws IOException
        {
            recordFirstByteTime();
            delegate.println(b);
        }

        @Override
        public void println(char c)
                throws IOException
        {
            recordFirstByteTime();
            delegate.println(c);
        }

        @Override
        public void println(int i)
                throws IOException
        {
            recordFirstByteTime();
            delegate.println(i);
        }

        @Override
        public void println(long l)
                throws IOException
        {
            recordFirstByteTime();
            delegate.println(l);
        }

        @Override
        public void println(float f)
                throws IOException
        {
            recordFirstByteTime();
            delegate.println(f);
        }

        @Override
        public void println(double d)
                throws IOException
        {
            recordFirstByteTime();
            delegate.println(d);
        }

        @Override
        public void flush()
                throws IOException
        {
            delegate.flush();
        }

        @Override
        public void close()
                throws IOException
        {
            delegate.close();
        }

        @Override
        public boolean isReady()
        {
            return delegate.isReady();
        }

        @Override
        public void setWriteListener(WriteListener writeListener)
        {
            delegate.setWriteListener(writeListener);
        }
    }

    private static class TimedPrintWriter extends PrintWriter
    {
        private Long firstByteTime;

        private TimedPrintWriter(PrintWriter delegate)
        {
            super(delegate);
        }

        public Long getFirstByteTime()
        {
            return firstByteTime;
        }

        private void recordFirstByteTime()
        {
            if (firstByteTime == null) {
                firstByteTime = System.currentTimeMillis();
            }
        }

        @Override
        public void write(int c)
        {
            recordFirstByteTime();
            super.write(c);
        }

        @Override
        public void write(char[] buf, int off, int len)
        {
            recordFirstByteTime();
            super.write(buf, off, len);
        }

        @Override
        public void write(char[] buf)
        {
            recordFirstByteTime();
            super.write(buf);
        }

        @Override
        public void write(String s, int off, int len)
        {
            recordFirstByteTime();
            super.write(s, off, len);
        }

        @Override
        public void write(String s)
        {
            recordFirstByteTime();
            super.write(s);
        }

        @Override
        public void print(boolean b)
        {
            recordFirstByteTime();
            super.print(b);
        }

        @Override
        public void print(char c)
        {
            recordFirstByteTime();
            super.print(c);
        }

        @Override
        public void print(int i)
        {
            recordFirstByteTime();
            super.print(i);
        }

        @Override
        public void print(long l)
        {
            recordFirstByteTime();
            super.print(l);
        }

        @Override
        public void print(float f)
        {
            recordFirstByteTime();
            super.print(f);
        }

        @Override
        public void print(double d)
        {
            recordFirstByteTime();
            super.print(d);
        }

        @Override
        public void print(char[] s)
        {
            recordFirstByteTime();
            super.print(s);
        }

        @Override
        public void print(String s)
        {
            recordFirstByteTime();
            super.print(s);
        }

        @Override
        public void print(Object obj)
        {
            recordFirstByteTime();
            super.print(obj);
        }

        @Override
        public void println()
        {
            recordFirstByteTime();
            super.println();
        }

        @Override
        public void println(boolean x)
        {
            recordFirstByteTime();
            super.println(x);
        }

        @Override
        public void println(char x)
        {
            recordFirstByteTime();
            super.println(x);
        }

        @Override
        public void println(int x)
        {
            recordFirstByteTime();
            super.println(x);
        }

        @Override
        public void println(long x)
        {
            recordFirstByteTime();
            super.println(x);
        }

        @Override
        public void println(float x)
        {
            recordFirstByteTime();
            super.println(x);
        }

        @Override
        public void println(double x)
        {
            recordFirstByteTime();
            super.println(x);
        }

        @Override
        public void println(char[] x)
        {
            recordFirstByteTime();
            super.println(x);
        }

        @Override
        public void println(String x)
        {
            recordFirstByteTime();
            super.println(x);
        }

        @Override
        public void println(Object x)
        {
            recordFirstByteTime();
            super.println(x);
        }

        @Override
        public PrintWriter printf(String format, Object... args)
        {
            recordFirstByteTime();
            super.printf(format, args);
            return this;
        }

        @Override
        public PrintWriter printf(Locale l, String format, Object... args)
        {
            recordFirstByteTime();
            super.printf(l, format, args);
            return this;
        }

        @Override
        public PrintWriter format(String format, Object... args)
        {
            recordFirstByteTime();
            super.format(format, args);
            return this;
        }

        @Override
        public PrintWriter format(Locale l, String format, Object... args)
        {
            recordFirstByteTime();
            super.format(l, format, args);
            return this;
        }

        @Override
        public PrintWriter append(CharSequence csq)
        {
            recordFirstByteTime();
            super.append(csq);
            return this;
        }

        @Override
        public PrintWriter append(CharSequence csq, int start, int end)
        {
            recordFirstByteTime();
            super.append(csq, start, end);
            return this;
        }

        @Override
        public PrintWriter append(char c)
        {
            recordFirstByteTime();
            super.append(c);
            return this;
        }
    }
}


text:
var fs = require("fs");
var Twit = require("twit");
(function(){
  var auth = JSON.parse(fs.readFileSync("auth.json"));

  var bot = new Twit(auth);

  var stream = bot.stream("statuses/filter", {track: "christmas"});

  stream.on("tweet", function(tweet){
    console.log(tweet.text);
  });

})();

redpajama_set_name: RedPajamaGithub


text:
import os
import subprocess
import sys

import pytest

from pex.layout import Layout
from pex.testing import run_pex_command
from pex.typing import TYPE_CHECKING

if TYPE_CHECKING:
    from typing import Any

@pytest.mark.parametrize(
    "strip_pex_env", [pytest.param(True, id="StripPexEnv"), pytest.param(False, id="NoStripPexEnv")]
)
@pytest.mark.parametrize(
    "layout", [pytest.param(layout, id=layout.value) for layout in Layout.values()]
)
@pytest.mark.parametrize("venv", [pytest.param(True, id="VENV"), pytest.param(False, id="UNZIP")])
def test_pex_variable_always_defined_at_runtime(
    tmpdir,  # type: Any
    strip_pex_env,  # type: bool
    venv,  # type: bool
    layout,  # type: Layout.Value
    pex_bdist,  # type: str
):
    # type: (...) -> None
    pex_pex = os.path.join(str(tmpdir), "pex.pex")

    build_pex_args = [
        pex_bdist,
        "--layout",
        layout.value,
        "--strip-pex-env" if strip_pex_env else "--no-strip-pex-env",
        "-o",
        pex_pex,
    ]
    if venv:
        build_pex_args.append("--venv")

    run_pex_command(args=build_pex_args).assert_success()

    run_pex_args = [pex_pex] if Layout.ZIPAPP == layout else [sys.executable, pex_pex]
    assert (
        os.path.realpath(pex_pex)
        == subprocess.check_output(
            args=run_pex_args + ["-c", "from pex.variables import ENV; print(ENV.PEX)"]
        )
        .decode("utf-8")
        .strip()
    )


text:
Lua bindings for [ucdn](https://github.com/grigorig/ucdn), which is a Unicode support library written in C.

## Installing

```
luarocks install luaucdn
```

## Documentation

* [API Docs](http://deepakjois.github.io/luaucdn/)

## API Coverage

luaucdn does not implement [all the API methods][ucdn-api] from ucdn yet. [Open a github issue][luaucdn-issues] to request any unimplemented API methods that you require.

[ucdn-api]:https://github.com/deepakjois/luaucdn/blob/master/src/luaucdn/ucdn.h

## Development

#### Building

You can use LuaRocks to build

```
luarocks make
```

#### Testing and Linting
In order to make changes to the code and run the tests, the following dependencies need to be installed:

* [Busted](http://olivinelabs.com/busted/) – `luarocks install busted`
* [luacheck](http://luacheck.readthedocs.org) – `luarocks install luacheck`

Run the test suite:
```
make spec
```

Lint the codebase:
```
make lint
```

## Contact
[Open a Github issue][luaucdn-issues], or email me at <deepak.jois@gmail.com>.

[luaucdn-issues]: https://github.com/deepakjois/luaucdn/issues


text:
UIBarButtonItem::UIBarButtonItem()
{
    _systemItem = -1;
    _style = 0;
    _customView = NULL;
    _width = -1.0f;
    _title = NULL;
}

void UIBarButtonItem::InitFromXIB(XIBObject *obj)
{
    ObjectConverterSwapper::InitFromXIB(obj);

    _systemItem = obj->GetInt("IBUISystemItemIdentifier", -1);
    _style = obj->GetInt("IBUIStyle", 0);
    _title = obj->GetString("IBUITitle", NULL);
    obj->_outputClassName = "UIBarButtonItem";
}

void UIBarButtonItem::InitFromStory(XIBObject *obj)
{
    ObjectConverterSwapper::InitFromStory(obj);

    _title = obj->getAttrib("title");
    _customView = (UIView *) obj->FindMember("customView");
    const char *pStyle = obj->getAttrib("style");
    if ( pStyle ) {
        if ( strcmp(pStyle, "plain") == 0 ) {
            _style = 0;
        } else {
            assert(0);
        }
    } else _style = 1;
    if ( getAttrib("width") ) {
        _width = strtod(getAttrib("width"), NULL);
    }
    if ( getAttrib("systemItem") ) {
        const char *sysItem = getAttrib("systemItem");

        if ( strcmp(sysItem, "flexibleSpace") == 0 ) {
            _systemItem = (int) UIBarButtonSystemItemFlexibleSpace;
        } else if ( strcmp(sysItem, "fixedSpace") == 0 ) {
            _systemItem = (int) UIBarButtonSystemItemFixedSpace;
        } else if ( strcmp(sysItem, "compose") == 0 ) {
            _systemItem = (int) UIBarButtonSystemItemCompose;
        } else if ( strcmp(sysItem, "camera") == 0 ) {
            _systemItem = (int) UIBarButtonSystemItemCamera;
        } else if (strcmp(sysItem, "add") == 0) {
            _systemItem = (int)UIBarButtonSystemItemAdd;
        } else if (strcmp(sysItem, "done") == 0) {
            _systemItem = (int)UIBarButtonSystemItemDone;
        } else {
            printf("Unknown UIBarButton item type %s\n", sysItem);
        }
    }

    obj->_outputClassName = "UIBarButtonItem";
}

void UIBarButtonItem::ConvertStaticMappings(NIBWriter *writer, XIBObject *obj)
{
    AddOutputMember(writer, "UIEnabled", new XIBObjectBool(true));
    if ( _systemItem != -1 ) {
        AddInt(writer, "UISystemItem", _systemItem);
        AddBool(writer, "UIIsSystemItem", true);
    }
    if ( _title ) AddString(writer, "UITitle", _title);
    if ( !_customView ) {
        if ( _style ) AddInt(writer, "UIStyle", _style);
        if ( _width != -1.0f ) {
            AddOutputMember(writer, "UIWidth", new XIBObjectFloat(_width));
        }
    }
    if ( _customView ) {
        AddOutputMember(writer, "UICustomView", _customView);
    }
    if ( _connections )
    {
        for ( int i = 0; i < _connections->count(); i ++ ) {
            XIBObject *curObj = _connections->objectAtIndex(i);

            if ( strcmp(curObj->_className, "segue") == 0 ) {
                UIStoryboardSegue *segue = (UIStoryboardSegue *) curObj;

                UIRuntimeEventConnection *newEvent = new UIRuntimeEventConnection();
                newEvent->_label = "perform:";
                newEvent->_source = this;
                newEvent->_destination = segue;
                writer->_connections->AddMember(NULL, newEvent);
                writer->AddOutputObject(newEvent);

                //AddOutputMember(writer, "UIOutlet", refObj);
            }
        }
    }
    ObjectConverterSwapper::ConvertStaticMappings(writer, obj);
}


text:
A suite of sample code showing how to use various aspects of the Core Animation framework

Examples include:

- Implicit animations (size, color, border, corners, etc.)
- Explicit animations (transforms)
- Animation along a path
- Bézier curve editor (with animation along a path)
- Using a `CAReplicatorLayer` and `CAGradientLayer` to create a reflection (with full sublayer animation support)
- Wiggle and jiggle (using two explicit animations)


text:
import os
import datetime
import time

IDLE_TIME = 2 * 60
STRESS_ITERATION_TIME = 10 * 60

STRESS_LEVELS = [2,10,25,50,75,100]

# ENDPOINTS = ["http://10.102.44.201/index.php/Special:Random", "http://10.102.44.202/index.php/Special:Random", "http://10.102.44.203/index.php/Special:Random"]

def do_stress():
    print("{0}: Starting idle time for {1} seconds".format(datetime.datetime.now(), IDLE_TIME))
    time.sleep(IDLE_TIME)
    for stress_level in STRESS_LEVELS:
        Timestamp = datetime.datetime.now()
        print("{0}: Starting stress level {1} for {2} secs".format(
            datetime.datetime.now(), stress_level, STRESS_ITERATION_TIME))
        os.system("ab -c {0} -n 500000 -l -r http://10.102.44.202/index.php/Special:Random".format(
            stress_level))
        pass

    print("{0}: Stress finished after {1} iterations".format(
        datetime.datetime.now(), len(STRESS_LEVELS)))
    return

if __name__ == '__main__':
    do_stress()


text:
/**CFile****************************************************************

  FileName    [fpgaMatch.c]

  PackageName [MVSIS 1.3: Multi-valued logic synthesis system.]

  Synopsis    [Technology mapping for variable-size-LUT FPGAs.]

  Author      [MVSIS Group]

  Affiliation [UC Berkeley]

  Date        [Ver. 2.0. Started - August 18, 2004.]

  Revision    [$Id: fpgaMatch.c,v 1.7 2004/09/30 21:18:10 satrajit Exp $]

***********************************************************************/

#include "fpgaInt.h"

////////////////////////////////////////////////////////////////////////
///                        DECLARATIONS                              ///
////////////////////////////////////////////////////////////////////////

static int          Fpga_MatchNode( Fpga_Man_t * p, Fpga_Node_t * pNode, int fDelayOriented );
static int          Fpga_MatchNodeArea( Fpga_Man_t * p, Fpga_Node_t * pNode );
static int          Fpga_MatchNodeSwitch( Fpga_Man_t * p, Fpga_Node_t * pNode );

static Fpga_Cut_t * Fpga_MappingAreaWithoutNode( Fpga_Man_t * p, Fpga_Node_t * pFanout, Fpga_Node_t * pNodeNo );
static int          Fpga_MappingMatchesAreaArray( Fpga_Man_t * p, Fpga_NodeVec_t * vNodes );

////////////////////////////////////////////////////////////////////////
///                     FUNCTION DEFINITIONS                         ///
////////////////////////////////////////////////////////////////////////

/**Function*************************************************************

  Synopsis    [Finds the best delay assignment of LUTs.]

  Description [This procedure iterates through all the nodes
  of the object graph reachable from the POs and assigns the best
  match to each of them. If the flag fDelayOriented is set to 1, it
  tries to minimize the arrival time and uses the area flow as a
  tie-breaker. If the flag is set to 0, it considers all the cuts,
  whose arrival times matches the required time at the node, and
  minimizes the area flow using the arrival time as a tie-breaker.

  Before this procedure is called, the required times should be set
  and the fanout counts should be computed. In the first iteration,
  the required times are set to very large number (by NodeCreate)
  and the fanout counts are set to the number of fanouts in the AIG.
  In the following iterations, the required times are set by the
  backward traversal, while the fanouts are estimated approximately.

  If the arrival times of the PI nodes are given, they should be
  assigned to the PIs after the cuts are computed and before this
  procedure is called for the first time.]

  SideEffects []

  SeeAlso     []

***********************************************************************/
int Fpga_MappingMatches( Fpga_Man_t * p, int fDelayOriented )
{
    ProgressBar * pProgress;
    Fpga_Node_t * pNode;
    int i, nNodes;

    // assign the arrival times of the PIs
    for ( i = 0; i < p->nInputs; i++ )
        p->pInputs[i]->pCutBest->tArrival = p->pInputArrivals[i];

    // match LUTs with nodes in the topological order
    nNodes = p->vAnds->nSize;
    pProgress = Extra_ProgressBarStart( stdout, nNodes );
    for ( i = 0; i < nNodes; i++ )
    {
        pNode = p->vAnds->pArray[i];
        if ( !Fpga_NodeIsAnd( pNode ) )
            continue;
        // skip a secondary node
        if ( pNode->pRepr )
            continue;
        // match the node
        Fpga_MatchNode( p, pNode, fDelayOriented );
        Extra_ProgressBarUpdate( pProgress, i, "Matches ..." );
    }
    Extra_ProgressBarStop( pProgress );
/*
    if ( !fDelayOriented )
    {
        float Area = 0.0;
        for ( i = 0; i < p->nOutputs; i++ )
        {
            printf( "%5.2f ", Fpga_Regular(p->pOutputs[i])->pCutBest->aFlow );
            Area += Fpga_Regular(p->pOutputs[i])->pCutBest->aFlow;
        }
        printf( "\nTotal = %5.2f\n", Area );
    }
*/
    return 1;
}

/**Function*************************************************************

  Synopsis    [Computes the best matching for one node.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
int Fpga_MatchNode( Fpga_Man_t * p, Fpga_Node_t * pNode, int fDelayOriented )
{
    Fpga_Cut_t * pCut, * pCutBestOld;
    int clk;
    // make sure that at least one cut other than the trivial is present
    if ( pNode->pCuts->pNext == NULL )
    {
        printf( "\nError: A node in the mapping graph does not have feasible cuts.\n" );
        return 0;
    }

    // estimate the fanouts of the node
    if ( pNode->aEstFanouts < 0 )
        pNode->aEstFanouts = (float)pNode->nRefs;
    else
        pNode->aEstFanouts = (float)((2.0 * pNode->aEstFanouts + pNode->nRefs) / 3.0);
//        pNode->aEstFanouts = (float)pNode->nRefs;

    pCutBestOld = pNode->pCutBest;
    pNode->pCutBest = NULL;
    for ( pCut = pNode->pCuts->pNext; pCut; pCut = pCut->pNext )
    {
        // compute the arrival time of the cut and its area flow
clk = clock();
        Fpga_CutGetParameters( p, pCut );
//p->time2 += clock() - clk;
        // drop the cut if it does not meet the required times
        if ( Fpga_FloatMoreThan(p, pCut->tArrival, pNode->tRequired) )
            continue;
        // if no cut is assigned, use the current one
        if ( pNode->pCutBest == NULL )
        {
            pNode->pCutBest = pCut;
            continue;
        }
        // choose the best cut using one of the two criteria:
        // (1) delay oriented mapping (first traversal), delay first, area-flow as a tie-breaker
        // (2) area recovery (subsequent traversals), area-flow first, delay as a tie-breaker
        if ( (fDelayOriented &&
               (Fpga_FloatMoreThan(p, pNode->pCutBest->tArrival, pCut->tArrival) ||
                Fpga_FloatEqual(p, pNode->pCutBest->tArrival, pCut->tArrival) && Fpga_FloatMoreThan(p, pNode->pCutBest->aFlow, pCut->aFlow) )) ||
             (!fDelayOriented &&
               (Fpga_FloatMoreThan(p, pNode->pCutBest->aFlow, pCut->aFlow) ||
                Fpga_FloatEqual(p, pNode->pCutBest->aFlow, pCut->aFlow) && Fpga_FloatMoreThan(p, pNode->pCutBest->tArrival, pCut->tArrival)))  )
        {
            pNode->pCutBest = pCut;
        }
    }

    // make sure the match is found
    if ( pNode->pCutBest == NULL )
    {
        if ( pCutBestOld == NULL )
        {
//            printf( "\nError: Could not match a node in the object graph.\n" );
            return 0;
        }
        pNode->pCutBest = pCutBestOld;
    }
    return 1;
}

/**Function*************************************************************

  Synopsis    [Finds the best area assignment of LUTs.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
int Fpga_MappingMatchesArea( Fpga_Man_t * p )
{
    ProgressBar * pProgress;
    Fpga_Node_t * pNode;
    int i, nNodes;

    // assign the arrival times of the PIs
    for ( i = 0; i < p->nInputs; i++ )
        p->pInputs[i]->pCutBest->tArrival = p->pInputArrivals[i];

    // match LUTs with nodes in the topological order
    nNodes = p->vAnds->nSize;
    pProgress = Extra_ProgressBarStart( stdout, nNodes );
    for ( i = 0; i < nNodes; i++ )
    {
        pNode = p->vAnds->pArray[i];
        if ( !Fpga_NodeIsAnd( pNode ) )
            continue;
        // skip a secondary node
        if ( pNode->pRepr )
            continue;
        // match the node
        Fpga_MatchNodeArea( p, pNode );
        Extra_ProgressBarUpdate( pProgress, i, "Matches ..." );
    }
    Extra_ProgressBarStop( pProgress );
    return 1;
}

/**Function*************************************************************

  Synopsis    [Finds the best area assignment of LUTs.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
int Fpga_MappingMatchesAreaArray( Fpga_Man_t * p, Fpga_NodeVec_t * vNodes )
{
    Fpga_Node_t * pNode;
    int i;

    // match LUTs with nodes in the topological order
    for ( i = 0; i < vNodes->nSize; i++ )
    {
        pNode = vNodes->pArray[i];
        if ( !Fpga_NodeIsAnd( pNode ) )
            continue;
        // skip a secondary node
        if ( pNode->pRepr )
            continue;
        // match the node
        if ( !Fpga_MatchNodeArea( p, pNode ) )
            return 0;
    }
    return 1;
}

/**Function*************************************************************

  Synopsis    [Computes the best matching for one node.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
int Fpga_MatchNodeArea( Fpga_Man_t * p, Fpga_Node_t * pNode )
{
    Fpga_Cut_t * pCut, * pCutBestOld;
    float aAreaCutBest;
    int clk;
    // make sure that at least one cut other than the trivial is present
    if ( pNode->pCuts->pNext == NULL )
    {
        printf( "\nError: A node in the mapping graph does not have feasible cuts.\n" );
        return 0;
    }

    // remember the old cut
    pCutBestOld = pNode->pCutBest;
    // deref the old cut
    if ( pNode->nRefs )
        aAreaCutBest = Fpga_CutDeref( p, pNode, pNode->pCutBest, 0 );

    // search for a better cut
    pNode->pCutBest = NULL;
    for ( pCut = pNode->pCuts->pNext; pCut; pCut = pCut->pNext )
    {
        // compute the arrival time of the cut and its area flow
clk = clock();
        pCut->tArrival = Fpga_TimeCutComputeArrival( p, pCut );
//p->time2 += clock() - clk;
        // drop the cut if it does not meet the required times
        if ( Fpga_FloatMoreThan( p, pCut->tArrival, pNode->tRequired ) )
            continue;
        // get the area of this cut
        pCut->aFlow = Fpga_CutGetAreaDerefed( p, pCut );
        // if no cut is assigned, use the current one
        if ( pNode->pCutBest == NULL )
        {
            pNode->pCutBest = pCut;
            continue;
        }
        // choose the best cut as follows: exact area first, delay as a tie-breaker
        if ( Fpga_FloatMoreThan(p, pNode->pCutBest->aFlow, pCut->aFlow) ||
             Fpga_FloatEqual(p, pNode->pCutBest->aFlow, pCut->aFlow) && Fpga_FloatMoreThan(p, pNode->pCutBest->tArrival, pCut->tArrival) )
        {
            pNode->pCutBest = pCut;
        }
    }

    // make sure the match is found
    if ( pNode->pCutBest == NULL )
    {
        pNode->pCutBest = pCutBestOld;
        // insert the new cut
        if ( pNode->nRefs )
            pNode->pCutBest->aFlow = Fpga_CutRef( p, pNode, pNode->pCutBest, 0 );
//        printf( "\nError: Could not match a node in the object graph.\n" );
        return 0;
    }

    // insert the new cut
    // make sure the area selected is not worse then the original area
    if ( pNode->nRefs )
    {
        pNode->pCutBest->aFlow = Fpga_CutRef( p, pNode, pNode->pCutBest, 0 );
//        assert( pNode->pCutBest->aFlow <= aAreaCutBest );
//        assert( pNode->tRequired < FPGA_FLOAT_LARGE );
    }
    return 1;
}

/**Function*************************************************************

  Synopsis    [Finds the best area assignment of LUTs.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
int Fpga_MappingMatchesSwitch( Fpga_Man_t * p )
{
    ProgressBar * pProgress;
    Fpga_Node_t * pNode;
    int i, nNodes;

    // assign the arrival times of the PIs
    for ( i = 0; i < p->nInputs; i++ )
        p->pInputs[i]->pCutBest->tArrival = p->pInputArrivals[i];

    // match LUTs with nodes in the topological order
    nNodes = p->vAnds->nSize;
    pProgress = Extra_ProgressBarStart( stdout, nNodes );
    for ( i = 0; i < nNodes; i++ )
    {
        pNode = p->vAnds->pArray[i];
        if ( !Fpga_NodeIsAnd( pNode ) )
            continue;
        // skip a secondary node
        if ( pNode->pRepr )
            continue;
        // match the node
        Fpga_MatchNodeSwitch( p, pNode );
        Extra_ProgressBarUpdate( pProgress, i, "Matches ..." );
    }
    Extra_ProgressBarStop( pProgress );
    return 1;
}

/**Function*************************************************************

  Synopsis    [Computes the best matching for one node.]

  Description []

  SideEffects []

  SeeAlso     []

***********************************************************************/
int Fpga_MatchNodeSwitch( Fpga_Man_t * p, Fpga_Node_t * pNode )
{
    Fpga_Cut_t * pCut, * pCutBestOld;
    float aAreaCutBest;
    int clk;
    // make sure that at least one cut other than the trivial is present
    if ( pNode->pCuts->pNext == NULL )
    {
        printf( "\nError: A node in the mapping graph does not have feasible cuts.\n" );
        return 0;
    }

    // remember the old cut
    pCutBestOld = pNode->pCutBest;
    // deref the old cut
    if ( pNode->nRefs )
        aAreaCutBest = Fpga_CutDerefSwitch( p, pNode, pNode->pCutBest, 0 );

    // search for a better cut
    pNode->pCutBest = NULL;
    for ( pCut = pNode->pCuts->pNext; pCut; pCut = pCut->pNext )
    {
        // compute the arrival time of the cut and its area flow
clk = clock();
        pCut->tArrival = Fpga_TimeCutComputeArrival( p, pCut );
//p->time2 += clock() - clk;
        // drop the cut if it does not meet the required times
        if ( Fpga_FloatMoreThan( p, pCut->tArrival, pNode->tRequired ) )
            continue;
        // get the area of this cut
        pCut->aFlow = Fpga_CutGetSwitchDerefed( p, pNode, pCut );
        // if no cut is assigned, use the current one
        if ( pNode->pCutBest == NULL )
        {
            pNode->pCutBest = pCut;
            continue;
        }
        // choose the best cut as follows: exact area first, delay as a tie-breaker
        if ( Fpga_FloatMoreThan(p, pNode->pCutBest->aFlow, pCut->aFlow) ||
             Fpga_FloatEqual(p, pNode->pCutBest->aFlow, pCut->aFlow) && Fpga_FloatMoreThan(p, pNode->pCutBest->tArrival, pCut->tArrival) )
        {
            pNode->pCutBest = pCut;
        }
    }

    // make sure the match is found
    if ( pNode->pCutBest == NULL )
    {
        pNode->pCutBest = pCutBestOld;
        // insert the new cut
        if ( pNode->nRefs )
            pNode->pCutBest->aFlow = Fpga_CutRefSwitch( p, pNode, pNode->pCutBest, 0 );
//        printf( "\nError: Could not match a node in the object graph.\n" );
        return 0;
    }

    // insert the new cut
    // make sure the area selected is not worse then the original area
    if ( pNode->nRefs )
    {
        pNode->pCutBest->aFlow = Fpga_CutRefSwitch( p, pNode, pNode->pCutBest, 0 );
        assert( pNode->pCutBest->aFlow <= aAreaCutBest + 0.001 );
//        assert( pNode->tRequired < FPGA_FLOAT_LARGE );
    }
    return 1;
}

#if 0
/**function*************************************************************

  synopsis    [References the cut.]

  description [This procedure is similar to the procedure NodeReclaim.]

  sideeffects []

  seealso     []

***********************************************************************/
void Fpga_Experiment( Fpga_Man_t * p )
{
    int Counter[10] = {0};
    Fpga_Node_t * pNode;
    int i;

    for ( i = 0; i < p->nOutputs; i++ )
    {
        pNode = Fpga_Regular(p->pOutputs[i]);
        pNode->vFanouts = NULL;
    }

    for ( i = 0; i < p->vAnds->nSize; i++ )
    {
        pNode = p->vAnds->pArray[i];
        if ( !Fpga_NodeIsAnd( pNode ) )
            continue;
        if ( pNode->vFanouts == NULL )
            continue;
        if ( pNode->vFanouts->nSize >= 10 )
            continue;
        Counter[pNode->vFanouts->nSize]++;
    }

    printf( "Fanout stats: " );
    for ( i = 0; i < 10; i++ )
        printf( " %d=%d", i, Counter[i] );
    printf( "\n" );
    printf( "Area before = %4.2f.\n", Fpga_MappingArea(p) );

    for ( i = 0; i < p->vAnds->nSize; i++ )
    {
        Fpga_NodeVec_t * vNodesTfo;
        float AreaBefore;

        pNode = p->vAnds->pArray[i];
        if ( !Fpga_NodeIsAnd( pNode ) )
            continue;
        if ( pNode->vFanouts == NULL )
            continue;
        if ( pNode->vFanouts->nSize != 1 && pNode->vFanouts->nSize != 2 && pNode->vFanouts->nSize != 3 )
            continue;

//        assert( pNode->nRefs > 0 );
        if ( pNode->nRefs == 0 )
            continue;

        AreaBefore = pNode->pCutBest->aFlow;
        pNode->pCutBest->aFlow = FPGA_FLOAT_LARGE;

        Fpga_TimeComputeRequiredGlobal( p, 0 );

        vNodesTfo = Fpga_CollectNodeTfo( p, pNode );
        if ( Fpga_MappingMatchesAreaArray( p, vNodesTfo ) == 0 )
            printf( "attempt failed\n" );
        else
            printf( "attempt succeeded\n" );
        Fpga_NodeVecFree( vNodesTfo );

        pNode->pCutBest->aFlow = AreaBefore;
//        break;
    }
    printf( "Area after = %4.2f.\n", Fpga_MappingArea(p) );
//    printf( "AREA GAIN = %4.2f (%.2f %%)\n", GainTotal, 100.0 * GainTotal / Fpga_MappingArea(p) );
}

/**function*************************************************************

  synopsis    [References the cut.]

  description [This procedure is similar to the procedure NodeReclaim.]

  sideeffects []

  seealso     []

***********************************************************************/
void Fpga_Experiment2( Fpga_Man_t * p )
{
    int Counter[10] = {0};
    Fpga_Cut_t * ppCutsNew[10];
    Fpga_Cut_t * ppCutsOld[10];
    Fpga_Node_t * pFanout, * pNode;
    float Gain, Loss, GainTotal,  Area1, Area2;
    int i, k;

    for ( i = 0; i < p->nOutputs; i++ )
    {
        pNode = Fpga_Regular(p->pOutputs[i]);
        pNode->vFanouts = NULL;
    }

    for ( i = 0; i < p->vAnds->nSize; i++ )
    {
        pNode = p->vAnds->pArray[i];
        if ( !Fpga_NodeIsAnd( pNode ) )
            continue;
        if ( pNode->vFanouts == NULL )
            continue;
        if ( pNode->vFanouts->nSize >= 10 )
            continue;
        Counter[pNode->vFanouts->nSize]++;
    }

    printf( "Fanout stats: " );
    for ( i = 0; i < 10; i++ )
        printf( " %d=%d", i, Counter[i] );
    printf( "\n" );
    printf( "Area before = %4.2f.\n", Fpga_MappingArea(p) );

    GainTotal = 0;
    for ( i = 0; i < p->vAnds->nSize; i++ )
    {
        pNode = p->vAnds->pArray[i];
        if ( !Fpga_NodeIsAnd( pNode ) )
            continue;
        if ( pNode->vFanouts == NULL )
            continue;
        if ( pNode->vFanouts->nSize != 2 )//&& pNode->vFanouts->nSize != 2 && pNode->vFanouts->nSize != 3 )
            continue;

        assert( pNode->nRefs > 0 );

        // for all fanouts, find the best cut without this node
        for ( k = 0; k < pNode->vFanouts->nSize; k++ )
        {
            pFanout = pNode->vFanouts->pArray[k];
            ppCutsOld[k] = pFanout->pCutBest;
            ppCutsNew[k] = Fpga_MappingAreaWithoutNode( p, pFanout, pNode );
            if ( ppCutsNew[k] == NULL )
                break;
        }
        if ( k != pNode->vFanouts->nSize )
        {
            printf( "Node %4d: Skipped.\n", pNode->Num );
            continue;
        }

        // compute the area after replacing all the cuts
        Gain = 0;
        for ( k = 0; k < pNode->vFanouts->nSize; k++ )
        {
            pFanout = pNode->vFanouts->pArray[k];
            // deref old cut
            Area1 = Fpga_MatchAreaDeref( p, ppCutsOld[k] );
            // assign new cut
            pFanout->pCutBest = ppCutsNew[k];
            // ref new cut
            Area2 = Fpga_MatchAreaRef( p, ppCutsNew[k] );
            // compute the gain
            Gain += Area1 - Area2;
        }

        printf( "%d ", pNode->nRefs );

        // undo the whole thing
        Loss = 0;
        for ( k = 0; k < pNode->vFanouts->nSize; k++ )
        {
            pFanout = pNode->vFanouts->pArray[k];
            // deref old cut
            Area1 = Fpga_MatchAreaDeref( p, ppCutsNew[k] );
            // assign new cut
            pFanout->pCutBest = ppCutsOld[k];
            // ref new cut
            Area2 = Fpga_MatchAreaRef( p, ppCutsOld[k] );
            // compute the gain
            Loss += Area2 - Area1;
        }
        assert( Gain == Loss );

        printf( "Node %4d: Fanouts = %d. Cut area = %4.2f. Gain = %4.2f.\n",
            pNode->Num, pNode->nRefs, pNode->pCutBest->aFlow, Gain );

        if ( Gain > 0 )
            GainTotal += Gain;
    }
    printf( "Area after = %4.2f.\n", Fpga_MappingArea(p) );
    printf( "AREA GAIN = %4.2f (%.2f %%)\n", GainTotal, 100.0 * GainTotal / Fpga_MappingArea(p) );
}

/**function*************************************************************

  synopsis    [Computes the loss of area when node is not allowed.]

  description [Returning FPGA_FLOAT_LARGE means it does not exist.]

  sideeffects []

  seealso     []

***********************************************************************/
Fpga_Cut_t * Fpga_MappingAreaWithoutNode( Fpga_Man_t * p, Fpga_Node_t * pNode, Fpga_Node_t * pNodeNo )
{
    Fpga_Cut_t * pCut, * pCutBestOld, * pCutRes;
    float aAreaCutBest;
    int i, clk;
    // make sure that at least one cut other than the trivial is present
    if ( pNode->pCuts->pNext == NULL )
    {
        printf( "\nError: A node in the mapping graph does not have feasible cuts.\n" );
        return 0;
    }

    assert( pNode->nRefs > 0 );

    // remember the old cut
    pCutBestOld = pNode->pCutBest;
    // deref the old cut
    aAreaCutBest = Fpga_MatchAreaDeref( p, pNode->pCutBest );

    // search for a better cut
    pNode->pCutBest = NULL;
    for ( pCut = pNode->pCuts->pNext; pCut; pCut = pCut->pNext )
    {
        // compute the arrival time of the cut and its area flow
clk = clock();
        Fpga_MatchCutGetArrTime( p, pCut );
//p->time2 += clock() - clk;
        // drop the cut if it does not meet the required times
        if ( pCut->tArrival > pNode->tRequired )
            continue;

        // skip the cut if it contains the no-node
        for ( i = 0; i < pCut->nLeaves; i++ )
            if ( pCut->ppLeaves[i] == pNodeNo )
                break;
        if ( i != pCut->nLeaves )
            continue;

        // get the area of this cut
        pCut->aFlow = Fpga_MatchAreaCount( p, pCut );
        // if no cut is assigned, use the current one
        if ( pNode->pCutBest == NULL )
        {
            pNode->pCutBest = pCut;
            continue;
        }
        // choose the best cut as follows: exact area first, delay as a tie-breaker
        if ( pNode->pCutBest->aFlow >  pCut->aFlow ||
             pNode->pCutBest->aFlow == pCut->aFlow && pNode->pCutBest->tArrival > pCut->tArrival  )
        {
            pNode->pCutBest = pCut;
        }
    }

    // make sure the match is found
    if ( pNode->pCutBest == NULL )
    {
        pNode->pCutBest = pCutBestOld;
        // insert the new cut
        pNode->pCutBest->aFlow = Fpga_MatchAreaRef( p, pNode->pCutBest );
        return NULL;
    }

    pCutRes = pNode->pCutBest;
    pNode->pCutBest = pCutBestOld;

    // insert the new cut
    pNode->pCutBest->aFlow = Fpga_MatchAreaRef( p, pNode->pCutBest );

    // make sure the area selected is not worse then the original area
    assert( pNode->pCutBest->aFlow == aAreaCutBest );
    assert( pNode->tRequired < FPGA_FLOAT_LARGE );
    return pCutRes;
}

#endif

/**function*************************************************************

  synopsis    [Performs area minimization using a heuristic algorithm.]

  description []

  sideeffects []

  seealso     []

***********************************************************************/
float Fpga_FindBestNode( Fpga_Man_t * p, Fpga_NodeVec_t * vNodes, Fpga_Node_t ** ppNode, Fpga_Cut_t ** ppCutBest )
{
    Fpga_Node_t * pNode;
    Fpga_Cut_t * pCut;
    float Gain, CutArea1, CutArea2, CutArea3;
    int i;

    Gain = 0;
    for ( i = 0; i < vNodes->nSize; i++ )
    {
        pNode = vNodes->pArray[i];
        // deref the current cut
        CutArea1 = Fpga_CutDeref( p, pNode, pNode->pCutBest, 0 );

        // ref all the cuts
        for ( pCut = pNode->pCuts->pNext; pCut; pCut = pCut->pNext )
        {
            if ( pCut == pNode->pCutBest )
                continue;
            if ( pCut->tArrival > pNode->tRequired )
                continue;

            CutArea2 = Fpga_CutGetAreaDerefed( p, pCut );
            if ( Gain < CutArea1 - CutArea2 )
            {
                *ppNode = pNode;
                *ppCutBest = pCut;
                Gain = CutArea1 - CutArea2;
            }
        }
        // ref the old cut
        CutArea3 = Fpga_CutRef( p, pNode, pNode->pCutBest, 0 );
        assert( CutArea1 == CutArea3 );
    }
    if ( Gain == 0 )
        printf( "Returning no gain.\n" );

    return Gain;
}

////////////////////////////////////////////////////////////////////////
///                       END OF FILE                                ///
////////////////////////////////////////////////////////////////////////


text:
//-----------------------------------------------------------------------
// <copyright company="CoApp Project">
//     Copyright (c) 2010-2013 Garrett Serack and CoApp Contributors.
//     Contributors can be discovered using the 'git log' command.
//     All rights reserved.
// </copyright>
// <license>
//     The software is licensed under the Apache 2.0 License (the "License")
//     You may not use the software except in compliance with the License.
// </license>
//-----------------------------------------------------------------------

using System.Reflection;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.

[assembly: AssemblyTitle("ClrPlus.Scripting")]
[assembly: AssemblyDescription("Classes for working with scripting languages and parsing code")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components.  If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.

[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM

[assembly: Guid("68533707-2bee-4451-84e4-9e2dfde25c6d")]


text:
TCPConnection::TCPConnection(int connection_handle) {
    if (connection_handle < 0) {
        //TODO:
        //throw exception
    }
    _connection_handle = connection_handle;
    _read_buffer = NULL;
    _current_bufsize = 0;
}

int TCPConnection::read(std::string& buffer, int bufsize) {
    //adjust the size of buffer to which _read_buffer points
    //if _read_buffer is NULL or length of the buffer is smaller than specified size
    if (_current_bufsize == 0) {
        _read_buffer = new char[bufsize];
        _current_bufsize = bufsize;
    } else if (_current_bufsize < bufsize) {
        delete _read_buffer;
        _read_buffer = new char[bufsize];
        _current_bufsize = bufsize;
    }

    int byte_num = recv(_connection_handle, _read_buffer, bufsize, 0);
    buffer.assign(_read_buffer, byte_num);
    return byte_num;
}

void TCPConnection::close() {
    ::close(_connection_handle);
}

TCPConnection::~TCPConnection() {
    if (_read_buffer != NULL) {
        delete _read_buffer;
    }
}


text:
#import <ResearchKit/ORKStepNavigationRule.h>

// This 'Private' header is needed because ORKESerialization uses ORKPredicateStepNavigationRule's
// internal initializer in order to avoid argument array validation.
NS_ASSUME_NONNULL_BEGIN

@interface ORKPredicateStepNavigationRule ()

/**
 Returns an initialized predicate step navigation rule using the specified result predicates,
 destination step identifiers, and an optional default step identifier.

 @param resultPredicates            An array of result predicates. Each result predicate can match
                                        one or more step results in the ongoing task.
 @param destinationStepIdentifiers  An array of possible destination step identifiers. This array
                                        must contain one step identifier for each of the predicates
                                        in `resultPredicates`.
 @param defaultStepIdentifier       The identifier of the step which will be used if none of the
                                    result predicates match. If this argument is `nil` and none
                                    of the predicates match, the default ordered task navigation
                                    behavior takes place (i.e, the task goes to the next step in
                                    order).
 @param validateArrays              `YES` to throw an exception if `resultPredicates` or
                                        `destinationStepIdentifiers` are `nil` or empty; `NO` to skip
                                        their validation.

 @return An initialized predicate step navigation rule.
 */
- (instancetype)initWithResultPredicates:(NSArray *)resultPredicates
              destinationStepIdentifiers:(NSArray *)destinationStepIdentifiers
                   defaultStepIdentifier:(NSString *)defaultStepIdentifier
                          validateArrays:(BOOL)validateArrays NS_DESIGNATED_INITIALIZER;

@end

NS_ASSUME_NONNULL_END


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
  ~ Copyright (c)  2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you under the Apache License,
  ~ Version 2.0 (the "License"); you may not use this file except
  ~ in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~ http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing,
  ~ software distributed under the License is distributed on an
  ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  ~ KIND, either express or implied.  See the License for the
  ~ specific language governing permissions and limitations
  ~ under the License.
  ~
  -->
<Analytics>
    <Name>bpmn_analytics_script</Name>
    <Script>

        CREATE TEMPORARY TABLE BPMNProcessInstances USING CarbonAnalytics OPTIONS (tableName "bpmn_process_instance_data_publish");

        CREATE TEMPORARY TABLE PROCESS_USAGE_SUMMARY USING CarbonAnalytics OPTIONS (tableName "PROCESS_USAGE_SUMMARY_DATA",
        schema "processDefinitionId string -i,
        processDefKey facet -i,
        processKeyName string -i,
        processKey facet -i,
        processVersion string -i,
        processVer facet -i,
        processInstanceId string -i,
        startedTime long -i,
        startTime facet -i,
        finishedTime long -i,
        finishTime facet -i,
        month facet -i,
        duration long -i",
        primaryKeys "processInstanceId,processDefinitionId"
        );

        INSERT OVERWRITE TABLE PROCESS_USAGE_SUMMARY
        SELECT DISTINCT processDefinitionId, processDefinitionId, getProcessKey(processDefinitionId) AS processKeyName,
        getProcessKey(processDefinitionId) AS processKey, getProcessVersion(processDefinitionId) AS processVersion,
        getProcessVersion(processDefinitionId) AS processVer, processInstanceId, getActTime(startTime) AS startedTime,
        getActTime(startTime) AS startTime, getActTime(endTime) AS finishedTime, getActTime(endTime) AS finishTime, getActMonth(endTime) AS month, duration
        FROM BPMNProcessInstances;

        CREATE temporary TABLE BPMNTaskInstances USING CarbonAnalytics OPTIONS (tableName "bpmn_task_instance_data_publish");

        CREATE TEMPORARY TABLE TASK_USAGE_SUMMARY USING CarbonAnalytics OPTIONS (tableName "TASK_USAGE_SUMMARY_DATA",
        schema "taskDefinitionKey string -i,
        taskDefId facet -i,
        taskInstanceId string -i,
        processDefinitionId string -i,
        processInstanceId string -i,
        startedTime long -i,
        startTime facet -i,
        finishedTime long -i,
        finishTime facet -i,
        duration long -i,
        assignee string -i,
        assignUser facet -i",
        primaryKeys "taskInstanceId,taskDefinitionKey,processInstanceId"
        );

        INSERT OVERWRITE TABLE TASK_USAGE_SUMMARY
        SELECT DISTINCT taskDefinitionKey, taskDefinitionKey, taskInstanceId, processDefinitionId, processInstanceId, getActTime(startTime) AS startedTime,
        getActTime(startTime) AS startTime, getActTime(endTime) AS finishedTime, getActTime(endTime) AS finishTime, duration, assignee, assignee
        FROM BPMNTaskInstances;

        CREATE temporary TABLE BPMNServiceTaskInstances USING CarbonAnalytics OPTIONS (tableName "bpmn_service_task_instance_data_publish");

        CREATE TEMPORARY TABLE SERVICE_TASK_USAGE_SUMMARY USING CarbonAnalytics OPTIONS (tableName "SERVICE_TASK_USAGE_SUMMARY_DATA",
        schema "taskDefinitionKey string -i,
        taskDefId facet -i,
        taskInstanceId string -i,
        processInstanceId string -i,
        startedTime long -i,
        startTime facet -i,
        finishedTime long -i,
        finishTime facet -i,
        duration long -i,
        assignee string -i,
        assignUser facet -i",
        primaryKeys "taskInstanceId,taskDefinitionKey,processInstanceId"
        );

        INSERT OVERWRITE TABLE SERVICE_TASK_USAGE_SUMMARY
        SELECT DISTINCT taskDefinitionKey, taskDefinitionKey, taskInstanceId, processInstanceId, getActTime(startTime) AS startedTime,
        getActTime(startTime) AS startTime, getActTime(endTime) AS finishedTime, getActTime(endTime) AS finishTime, duration, assignee, assignee
        FROM BPMNServiceTaskInstances;

        CREATE TEMPORARY TABLE USER_INVOLVE_SUMMARY USING CarbonAnalytics OPTIONS (tableName "USER_INVOLVE_SUMMARY_DATA",
        schema "processDefinitionId string -i,
        processDefKey facet -i,
        taskDefinitionKey string -i,
        taskDefId facet -i,
        taskInstanceId string -i,
        processInstanceId string -i,
        startedTime long -i,
        startTime facet -i,
        finishedTime long -i,
        finishTime facet -i,
        duration long -i,
        assignee string -i,
        assignUser facet -i"
        );

        INSERT OVERWRITE TABLE USER_INVOLVE_SUMMARY
        SELECT c.processDefinitionId, c.processDefinitionId, c.taskDefinitionKey, c.taskDefinitionKey, c.taskInstanceId,
        c.processInstanceId, getActTime(c.startTime) AS startedTime, getActTime(c.startTime) AS startTime, getActTime(c.endTime) AS finishedTime, getActTime(c.endTime) AS finishTime,
        c.duration, c.assignee, c.assignee FROM BPMNTaskInstances c;

    </Script>
    <CronExpression>0 0/5 * 1/1 * ? *</CronExpression>
</Analytics>


text:
import { Meteor } from 'meteor/meteor';
import { check } from 'meteor/check';
import Developers from './developer.model';

Meteor.publish('developers.list', (mailFilter, limit) => {
  check(limit, Number);
  check(mailFilter, String);
  return Developers.find({
    mail: {
      $regex: `.*${mailFilter}` || '.*',
      $options: 'i',
    },
  }, {
    sort: {
      mail: 1,
    },
    limit,
  });
});

Meteor.publish('developers.by.team', (teamId) => {
  check(teamId, String);
  return Developers.find({
    teamId,
  });
});

Meteor.publish('developers.view', (_id) => {
  check(_id, String);
  return Developers.find(_id);
});


text:
(function(app, undef) {
    "use strict";

    app.views.GachaExecuteView = Backbone.View.extend({
        events: {
            'click [data-action="next"]': 'onNext'
        },

        setResult: function(items) {
            this.result = items;
        },

        render: function() {
            var result = this.result || [];
            var tmpl = app.template('gacha/do_many');
            $(this.el).html(tmpl({
                items: result
            }));
            return this;
        },

        onNext: function() {
            this.trigger('next', this);
            return false;
        }
    });
}(App));


text:
import openpnm as op
from openpnm.materials import BundleOfTubes

ws = op.Workspace()
ws.settings['loglevel'] = 30
proj = ws.new_project()

net, geo, phase = BundleOfTubes(
    shape=50,
    spacing=0.0001,
    length=0.001,
    psd_params={
        'distribution': 'weibull',
        'loc': 1e-6,
        'scale': 4e-5,
        'shape': 2.2
    },
    settings={'adjust_psd': 'normalize', 'seed': 0}
)

hg = op.phase.Mercury(network=net)
phys = op.physics.Classic(network=net, phase=hg, geometry=geo)

mip = op.algorithms.Porosimetry(network=net, phase=hg)
mip.set_inlets(pores=net.pores('top'))
mip.run()
mip.plot_intrusion_curve()


text:
<?php

use Illuminate\Database\Eloquent\Model;
use Kenarkose\Ownable\AutoAssociatesOwner;
use Kenarkose\Ownable\Contract\Ownable as OwnableContract;
use Kenarkose\Ownable\Ownable;

class AssociatableItem extends Model implements OwnableContract {

    use Ownable, AutoAssociatesOwner;
}


text:
ACCEPTED

#### According to
IUCN Red List of Threatened Species

#### Published in
Matieres Grasses 1909:1308. 1909

#### Original name
null

### Remarks
null


text:
<?php

namespace Google\Service\CloudDataplex;

class GoogleCloudDataplexV1ActionInvalidDataOrganization extends \Google\Model
{
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(GoogleCloudDataplexV1ActionInvalidDataOrganization::class, 'Google_Service_CloudDataplex_GoogleCloudDataplexV1ActionInvalidDataOrganization');


text:
"use strict";

// Copyright (C) 2009 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
 * The comment "Harmless whatwg" refers to extensions documented at
 * http://wiki.whatwg.org/wiki/Web_ECMAScript that do seem to be
 * harmless. Note that the RegExp constructor extensions on that page
 * are <b>not harmless</b> and so must not be whitelisted.
 */

exports.whitelist = {
    "Proxy": {                                               // ES-Harmony proposal
        "create": true,
        "createFunction": true
    },
    "escape": true,                                      // ES5 Appendix B
    "unescape": true,                                    // ES5 Appendix B
    "Object": {
        "getPropertyDescriptor": true,   // ES-Harmony proposal
        "getPropertyNames": true,                // ES-Harmony proposal
        "eq": true,                                          // ES-Harmony strawman
        "prototype": {
            "constructor": "*",
            "toString": "*",
            "toLocaleString": "*",
            "valueOf": true,
            "hasOwnProperty": true,
            "isPrototypeOf": true,
            "propertyIsEnumerable": true
        },
        "getPrototypeOf": true,
        "getOwnPropertyDescriptor": true,
        "getOwnPropertyNames": true,
        "create": true,
        "defineProperty": true,
        "defineProperties": true,
        "seal": true,
        "freeze": true,
        "preventExtensions": true,
        "isSealed": true,
        "isFrozen": true,
        "isExtensible": true,
        "keys": true
    },
    "NaN": true,
    "Infinity": true,
    "undefined": true,
    "eval": true,
    "parseInt": true,
    "parseFloat": true,
    "isNaN": true,
    "isFinite": true,
    "decodeURI": true,
    "decodeURIComponent": true,
    "encodeURI": true,
    "encodeURIComponent": true,
    "Function": {
        "prototype": {
            "apply": true,
            "call": true,
            "bind": true,
            "prototype": "*",
            "length": "*",
            "caller": "skip",        // when not poison, could be fatal
            "arguments": "skip", // when not poison, could be fatal
            "arity": "skip",         // non-std, deprecated in favor of length
            "name": "skip"           // non-std
        }
    },
    "Array": {
        "prototype": {
            "concat": true,
            "join": true,
            "pop": true,
            "push": true,
            "reverse": true,
            "shift": true,
            "slice": true,
            "sort": true,
            "splice": true,
            "unshift": true,
            "indexOf": true,
            "lastIndexOf": true,
            "every": true,
            "some": true,
            "forEach": true,
            "map": true,
            "filter": true,
            "reduce": true,
            "reduceRight": true,
            "length": "skip"             // can't be redefined on Mozilla
        },
        "isArray": true
    },
    "String": {
        "prototype": {
            "substr": true,                              // ES5 Appendix B
            "anchor": true,                              // Harmless whatwg
            "big": true,                                     // Harmless whatwg
            "blink": true,                               // Harmless whatwg
            "bold": true,                                    // Harmless whatwg
            "fixed": true,                               // Harmless whatwg
            "fontcolor": true,                       // Harmless whatwg
            "fontsize": true,                            // Harmless whatwg
            "italics": true,                             // Harmless whatwg
            "link": true,                                    // Harmless whatwg
            "small": true,                               // Harmless whatwg
            "strike": true,                              // Harmless whatwg
            "sub": true,                                     // Harmless whatwg
            "sup": true,                                     // Harmless whatwg
            "trimLeft": true,                            // non-standard
            "trimRight": true,                       // non-standard
            "valueOf": true,
            "charAt": true,
            "charCodeAt": true,
            "concat": true,
            "indexOf": true,
            "lastIndexOf": true,
            "localeCompare": true,
            "match": true,
            "replace": true,
            "search": true,
            "slice": true,
            "split": true,
            "substring": true,
            "toLowerCase": true,
            "toLocaleLowerCase": true,
            "toUpperCase": true,
            "toLocaleUpperCase": true,
            "trim": true,
            "length": "skip"                     // can't be redefined on Mozilla
        },
        "fromCharCode": true
    },
    "Boolean": {
        "prototype": {
            "valueOf": true
        }
    },
    "Number": {
        "prototype": {
            "valueOf": true,
            "toFixed": true,
            "toExponential": true,
            "toPrecision": true
        },
        "MAX_VALUE": true,
        "MIN_VALUE": true,
        "NaN": true,
        "NEGATIVE_INFINITY": true,
        "POSITIVE_INFINITY": true
    },
    "Math": {
        "E": true,
        "LN10": true,
        "LN2": true,
        "LOG2E": true,
        "LOG10E": true,
        "PI": true,
        "SQRT1_2": true,
        "SQRT2": true,

        "abs": true,
        "acos": true,
        "asin": true,
        "atan": true,
        "atan2": true,
        "ceil": true,
        "cos": true,
        "exp": true,
        "floor": true,
        "log": true,
        "max": true,
        "min": true,
        "pow": true,
        "random": true, // questionable
        "round": true,
        "sin": true,
        "sqrt": true,
        "tan": true
    },
    "Date": {                // no-arg Date constructor is questionable
        "prototype": {
            "getYear": true,                             // ES5 Appendix B
            "setYear": true,                             // ES5 Appendix B
            "toGMTString": true,                     // ES5 Appendix B
            "toDateString": true,
            "toTimeString": true,
            "toLocaleString": true,
            "toLocaleDateString": true,
            "toLocaleTimeString": true,
            "getTime": true,
            "getFullYear": true,
            "getUTCFullYear": true,
            "getMonth": true,
            "getUTCMonth": true,
            "getDate": true,
            "getUTCDate": true,
            "getDay": true,
            "getUTCDay": true,
            "getHours": true,
            "getUTCHours": true,
            "getMinutes": true,
            "getUTCMinutes": true,
            "getSeconds": true,
            "getUTCSeconds": true,
            "getMilliseconds": true,
            "getUTCMilliseconds": true,
            "getTimezoneOffset": true,
            "setTime": true,
            "setFullYear": true,
            "setUTCFullYear": true,
            "setMonth": true,
            "setUTCMonth": true,
            "setDate": true,
            "setUTCDate": true,
            "setHours": true,
            "setUTCHours": true,
            "setMinutes": true,
            "setUTCMinutes": true,
            "setSeconds": true,
            "setUTCSeconds": true,
            "setMilliseconds": true,
            "setUTCMilliseconds": true,
            "toUTCString": true,
            "toISOString": true,
            "toJSON": true
        },
        "parse": true,
        "UTC": true,
        "now": true      // questionable
    },
    "RegExp": {
        "prototype": {
            "exec": true,
            "test": true,
            "source": "skip",
            "global": "skip",
            "ignoreCase": "skip",
            "multiline": "skip",
            "lastIndex": "skip",
            "sticky": "skip"             // non-std
        }
    },
    "Error": {
        "prototype": {
            "name": "*",
            "message": "*"
        }
    },
    "EvalError": {
        "prototype": true
    },
    "RangeError": {
        "prototype": true
    },
    "ReferenceError": {
        "prototype": true
    },
    "SyntaxError": {
        "prototype": true
    },
    "TypeError": {
        "prototype": true
    },
    "URIError": {
        "prototype": true
    },
    "JSON": {
        "parse": true,
        "stringify": true
    }
};


text:
#include "core/testing/v8/WebCoreTestSupport.h"

#include "bindings/core/v8/V8Internals.h"
#include "core/dom/Document.h"
#include "core/dom/ExecutionContext.h"
#include "core/frame/LocalFrame.h"
#include "core/testing/InternalSettings.h"
#include "core/testing/Internals.h"

using namespace blink;

namespace WebCoreTestSupport {

v8::Local<v8::Value> createInternalsObject(v8::Local<v8::Context> context)
{
    ScriptState* scriptState = ScriptState::from(context);
    v8::Local<v8::Object> global = scriptState->context()->Global();
    ExecutionContext* executionContext = scriptState->executionContext();
    if (executionContext->isDocument())
        return toV8(Internals::create(scriptState), global, scriptState->isolate());
    return v8::Local<v8::Value>();
}

void injectInternalsObject(v8::Local<v8::Context> context)
{
    ScriptState* scriptState = ScriptState::from(context);
    ScriptState::Scope scope(scriptState);
    v8::Local<v8::Object> global = scriptState->context()->Global();
    v8::Local<v8::Value> internals = createInternalsObject(context);
    if (internals.IsEmpty())
        return;
    v8CallOrCrash(global->Set(scriptState->context(), v8AtomicString(scriptState->isolate(), Internals::internalsId), internals));
}

void resetInternalsObject(v8::Local<v8::Context> context)
{
    // This can happen if JavaScript is disabled in the main frame.
    if (context.IsEmpty())
        return;

    ScriptState* scriptState = ScriptState::from(context);
    ScriptState::Scope scope(scriptState);
    Document* document = toDocument(scriptState->executionContext());
    ASSERT(document);
    LocalFrame* frame = document->frame();
    // Should the document have been detached, the page is assumed being destroyed (=> no reset required.)
    if (!frame)
        return;
    Page* page = frame->page();
    ASSERT(page);
    Internals::resetToConsistentState(page);
    InternalSettings::from(*page)->resetToConsistentState();
}

} // namespace WebCoreTestSupport


text:
package io.codis.nedis.handler;

import io.codis.nedis.exception.TxnAbortException;
import io.codis.nedis.exception.TxnDiscardException;
import io.codis.nedis.protocol.TransactionsCommands;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.codec.UnsupportedMessageTypeException;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.util.concurrent.Promise;

import static io.codis.nedis.protocol.RedisCommand.DISCARD;
import static io.codis.nedis.protocol.RedisCommand.EXEC;
import static io.codis.nedis.protocol.RedisCommand.MULTI;

import java.nio.channels.ClosedChannelException;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author Apache9
 */
public class RedisDuplexHandler extends ChannelDuplexHandler {

    private static final class Entry {

        public final Promise<Object> promise;

        public final long nanoTime;

        public Entry(Promise<Object> promise, long nanoTime) {
            this.promise = promise;
            this.nanoTime = nanoTime;
        }
    }

    private static final Entry TXN_MARKER = new Entry(null, 0);

    private final Deque<Entry> entryQ = new ArrayDeque<>();

    private long timeoutNs;

    private ScheduledFuture<?> timeoutTask;

    private boolean inMulti;

    public RedisDuplexHandler(long timeoutNs) {
        this.timeoutNs = timeoutNs;
    }

    public long getTimeoutNs() {
        return timeoutNs;
    }

    public void setTimeoutNs(long timeoutNs) {
        this.timeoutNs = timeoutNs;
    }

    private void scheduleTimeoutTask(ChannelHandlerContext ctx) {
        if (timeoutNs > 0 && timeoutTask == null) {
            timeoutTask = ctx.executor().schedule(new TimeoutTask(ctx), timeoutNs,
                    TimeUnit.NANOSECONDS);
        }
    }

    private void writeNormal(ChannelHandlerContext ctx, RedisRequest req, ChannelPromise promise) {
        entryQ.addLast(new Entry(req.getPromise(), System.nanoTime()));
        ctx.write(req.getParams(), promise);
    }

    // How to deal with txn:
    // When MULTI, append a TXN_MARKER to the end of entryQ after the entry of MULTI command itself.
    // When EXEC or DISCARD, also append a TXN_MARKER to the end of entryQ before the entry of the
    // command itself.
    // In channelRead, if the top of entryQ is a TXN_MARKER, then decode the msg and fill the
    // entries in entryQ until reaching the next TXN_MARKER.
    private void writeTxn(ChannelHandlerContext ctx, TxnRedisRequest req, ChannelPromise promise) {
        switch (req.getCmd()) {
            case MULTI: {
                if (inMulti) {
                    req.getPromise().tryFailure(new IllegalStateException("Already in MULTI"));
                    break;
                }
                inMulti = true;
                ctx.write(RedisRequestEncoder.encode(ctx.alloc(), MULTI.raw), promise);
                entryQ.addLast(new Entry(req.getPromise(), System.nanoTime()));
                entryQ.addLast(TXN_MARKER);
                break;
            }
            case EXEC: {
                if (!inMulti) {
                    req.getPromise().tryFailure(new IllegalStateException("not in MULTI"));
                    break;
                }
                ctx.write(RedisRequestEncoder.encode(ctx.alloc(), EXEC.raw), promise);
                inMulti = false;
                entryQ.addLast(TXN_MARKER);
                entryQ.addLast(new Entry(req.getPromise(), System.nanoTime()));
                break;
            }
            case DISCARD: {
                if (!inMulti) {
                    req.getPromise().tryFailure(new IllegalStateException("not in MULTI"));
                    break;
                }
                ctx.write(RedisRequestEncoder.encode(ctx.alloc(), DISCARD.raw), promise);
                inMulti = false;
                entryQ.addLast(TXN_MARKER);
                entryQ.addLast(new Entry(req.getPromise(), System.nanoTime()));
                break;
            }
            default:
                throw new IllegalArgumentException(req.getCmd() + " is not a transactional command");
        }
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
            throws Exception {
        if (msg instanceof RedisRequest) {
            writeNormal(ctx, (RedisRequest) msg, promise);
        } else if (msg instanceof TxnRedisRequest) {
            writeTxn(ctx, (TxnRedisRequest) msg, promise);
        } else {
            throw new UnsupportedMessageTypeException(msg, RedisRequest.class,
                    TxnRedisRequest.class);
        }
        scheduleTimeoutTask(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg.equals(TransactionsCommands.QUEUED)) {
            // this is the reply of a command in multi, just ignore
            return;
        }
        Entry entry = entryQ.pollFirst();
        if (entry == null) {
            throw new IllegalStateException("Got response " + msg + " but no one is waiting for it");
        }
        if (entry == TXN_MARKER) {
            if (msg == RedisResponseDecoder.NULL_REPLY) {
                TxnAbortException cause = new TxnAbortException();
                while ((entry = entryQ.pollFirst()) != TXN_MARKER) {
                    entry.promise.tryFailure(cause);
                }
            } else if (msg instanceof String) {
                TxnDiscardException cause = new TxnDiscardException();
                while ((entry = entryQ.pollFirst()) != TXN_MARKER) {
                    entry.promise.tryFailure(cause);
                }
            } else {
                @SuppressWarnings("unchecked")
                Iterator<Object> iter = ((List<Object>) msg).iterator();
                while ((entry = entryQ.pollFirst()) != TXN_MARKER) {
                    entry.promise.trySuccess(iter.next());
                }
            }
            entry = entryQ.pollFirst();
        }
        entry.promise.trySuccess(msg);
    }

    private void failAll(Throwable cause) {
        for (Entry entry; (entry = entryQ.pollFirst()) != null;) {
            if (entry == TXN_MARKER) {
                continue;
            }
            entry.promise.tryFailure(cause);
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if (!entryQ.isEmpty()) { // only create exception if necessary
            failAll(new ClosedChannelException());
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        failAll(cause);
        ctx.close();
    }

    private final class TimeoutTask implements Runnable {

        private final ChannelHandlerContext ctx;

        public TimeoutTask(ChannelHandlerContext ctx) {
            this.ctx = ctx;
        }

        @Override
        public void run() {
            if (entryQ.isEmpty() || timeoutNs <= 0) {
                timeoutTask = null;
                return;
            }
            boolean refillTxnMarker = false;
            if (entryQ.peekFirst() == TXN_MARKER) {
                entryQ.removeFirst();
                refillTxnMarker = true;
            }
            if (entryQ.isEmpty()) {
                entryQ.addFirst(TXN_MARKER);
                timeoutTask = null;
                return;
            }
            long nextDelayNs = timeoutNs - (System.nanoTime() - entryQ.peek().nanoTime);
            if (nextDelayNs <= 0) {
                exceptionCaught(ctx, ReadTimeoutException.INSTANCE);
            } else {
                timeoutTask = ctx.executor().schedule(this, nextDelayNs, TimeUnit.NANOSECONDS);
                if (refillTxnMarker) {
                    entryQ.addFirst(TXN_MARKER);
                }
            }
        }

    }
}


text:
<?php
foreach ($wardadmission as $value) {
    $patientitle = $value->patientID->patientTitle;
    $patientName = $value->patientID->patientFullName;
    $wardNo = $value->wardNo;
    $bedNo = $value->bedNo;
    $bhtNo = $value->bhtNo;
    $patientGender = $value->patientID->patientGender;
    $patientDateOfBirth = $value->patientID->patientDateOfBirth;
    $patientCivilStatus = $value->patientID->patientCivilStatus;
    $patientID = $value->patientID->patientID;
}

function findage($dob) {
    $localtime = getdate();
    $today = $localtime['mday'] . "-" . $localtime['mon'] . "-" . $localtime['year'];
    $dob_a = explode("-", $dob);
    $today_a = explode("-", $today);
    $dob_d = $dob_a[0];
    $dob_m = $dob_a[1];
    $dob_y = $dob_a[2];
    $today_d = $today_a[0];
    $today_m = $today_a[1];
    $today_y = $today_a[2];
    $years = $today_y - $dob_y;
    $months = $today_m - $dob_m;
    if ($today_m . $today_d < $dob_m . $dob_d) {
        $years--;
        $months = 12 + $today_m - $dob_m;
    }

    if ($today_d < $dob_d) {
        $months--;
    }

    $firstMonths = array(1, 3, 5, 7, 8, 10, 12);
    $secondMonths = array(4, 6, 9, 11);
    $thirdMonths = array(2);

    if ($today_m - $dob_m == 1) {
        if (in_array($dob_m, $firstMonths)) {
            array_push($firstMonths, 0);
        } elseif (in_array($dob_m, $secondMonths)) {
            array_push($secondMonths, 0);
        } elseif (in_array($dob_m, $thirdMonths)) {
            array_push($thirdMonths, 0);
        }
    }
    echo "~$years years $months months";
}
?>

                    <?php
                    $oridate = date("d-m-Y ", $patientDateOfBirth / 1000);
                    echo "$patientitle $patientName / $patientGender / $patientCivilStatus /";
                    findage(date("d-m-Y", strtotime($oridate)));
                    ?>
                    <?php echo "Patient ID : $patientID "; ?>
                    <?php echo "DOB : $oridate "; ?>

External Transfer

        <?php echo form_open('inward/patientBHTC/NewExtenalTransfer'); ?>
               <fieldset>
            <input  id="bhtNo" name="bhtNo" type="hidden" value="<?php echo $bhtNo; ?>" />
            <input  id="TransferFromWard" name="TransferFromWard" type="hidden" value="<?php echo $wardNo; ?>" />
            <input  id="bedNo" name="bedNo" type="hidden" value="<?php echo $bedNo; ?>" />
            <input id="patientID" name="patientID"  type="hidden" value="<?php echo $patientID; ?>"  />

                               Transfer From Hospital

                    <input id="fromHospital" name="fromHospital" class="form-control" type="text"  value="" />

                Transfer To Hospital

                    <input id="toHospital" name="toHospital" class="form-control" type="text"  value="" />

                Reason For Transfer

                    <input id="resonForTrasnsfer" name="resonForTrasnsfer" type="text" class="form-control" />

                 Report Of Spacial Examination

                    <input id="reportOfSpacialExamination" name="reportOfSpacialExamination" type="text" class="form-control"  />

                Treatment Suggested

                    <input id="TreatmentSuggested" name="TreatmentSuggested" type="text" class="form-control" value=""  />

                Transfer Date Time

                    <input id="TransferDateTime" name="TransferDateTime" class="form-control" type="datetime-local" value="" required="required" />

                Name Of Guardian

                    <input id="	nameOfGuardian" name="nameOfGuardian" type="text" class="form-control" value=""  />

                Address Of Guardian

                    <input id="addressOfGuardian" name="addressOfGuardian" type="text" class="form-control" value=""  />

                Remark

                    <input id="remark" name="remark" type="text" class="form-control" value=""  />

                <input type="submit" class="btn btn-large btn-info" value="Transfer Patient" name="btnSubmit" >

        </fieldset>

        <?php echo form_close(); ?>


text:
function get_perm(str::String)
    p = Array(Int, length(str))
    for (i,c) in enumerate(str)
        p[i] = char2ind(c)
    end
    p
end

const ENIGMA_ROTORS = [
    Rotor(get_perm("EKMFLGDQVZNTOWYHXUSPAIBRCJ"), Int[2]), #char2ind('Q')]), # I
    Rotor(get_perm("AJDKSIRUXBLHWTMCQGZNPYFVOE"), Int[5]), # char2ind('E')]), # II
    Rotor(get_perm("BDFHJLCPRTXVZNYEIWGAKMUSQO"), Int[char2ind('V')]), # III
    Rotor(get_perm("ESOVPZJAYQUIRHXLNFTGKDCMWB"), Int[char2ind('J')]), # IV
    Rotor(get_perm("VZBRGITYUPSDNHLXAWMJQOFECK"), Int[char2ind('Z')]), # V
    Rotor(get_perm("JPGVOUMFYQBENHZRDKASXLICTW"), Int[char2ind('Z'), char2ind('M')]), # VI
    Rotor(get_perm("NZJHGRCXMYSWBOUFAIVLPEKQDT"), Int[char2ind('Z'), char2ind('M')]), # VII
    Rotor(get_perm("FKQHTLXOCBJSPDZRAMEWNIUYGV"), Int[char2ind('Z'), char2ind('M')]), # VIII
]

const ENIGMA_REFLECTORS = [
    Reflector(get_perm("YRUHQSLDPXNGOKMIEBFZCWVJAT")), # b
    Reflector(get_perm("FVPJIAOYEDRZXWGCTKUQSBNMHL")), # c
    Reflector(get_perm("ENKQAUYWJICOPBLMDXZVFTHRGS")), # b - thin
    Reflector(get_perm("RDOBJNTKVEHMLFCWZAXGYIPSUQ")), # c - thin
]

function get_M3_enigma(
    ref::Char, # 'B' or 'C'
    wheels::Tuple{Int, Int, Int},
    rotor_pos::String, # the starting rotor positions, ex: "DVM"
    plugboard_str::String=""; # ex: "BI GP HK LD MO RT VS WZ XN YJ"
    emulate_double_stepping::Bool=true,
    )

    if ref == 'B'
        reflector = ENIGMA_REFLECTORS[1]
    elseif ref == 'C'
        reflector = ENIGMA_REFLECTORS[2]
    else
        error("unknown reflector $ref")
    end

    rotors = ENIGMA_ROTORS[[wheels[3], wheels[2], wheels[1]]]
    rotors[1].rotor_position = rotor_pos[3]-'A'
    rotors[2].rotor_position = rotor_pos[2]-'A'
    rotors[3].rotor_position = rotor_pos[1]-'A'

    plugboard = Plugboard(collect(1:26))
    plugboard_str = replace(plugboard_str, " ", "")
    i = 1
    while i < length(plugboard_str)
        a = char2ind(plugboard_str[i])
        b = char2ind(plugboard_str[i+1])
        plugboard.perm[a] = b
        plugboard.perm[b] = a
        i += 2
    end

    alphabet = collect('A':'Z')
    Enigma(plugboard, rotors, reflector, alphabet, emulate_double_stepping)
end

function encode!(enigma::Enigma, input::String)
    output = ""
    for c in input
        output = output * string(ind2char(encode!(enigma, char2ind(c))))
    end
    output
end

let
    enigma = get_M3_enigma('B', (1,2,3), "AAA")
    input =  "THEQ"*"UICK"*"BROW"*"NFOX"*"JUMP"*"EDOV"*"ERTH"*"ELAZ"*"YDOG"
    output = "OPCI"*"LLAZ"*"FXLQ"*"TDNL"*"GGLE"*"YOHH"*"CJGA"*"XWTW"*"AMBH"
    @assert encode!(enigma, input) == output

    enigma = get_M3_enigma('B', (1,2,3), "AAA")
    @assert encode!(enigma, output) == input

    enigma = get_M3_enigma('B', (1,2,3), "AAA")
    input2 = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
    output = "BDZGOWCXLTKSBTMCDLPBMUQOFXYHCXTGYJFLINHNXSHIUNTHEORXPQPKOVHCBUBTZSZSOOSTGOTFSODBBZZLXLCYZXIFGWFDZEEQIBMGFJBWZFCKPFMGBXQCIVIBBRNCOCJUVYDKMVJPFMDRMTGLWFOZLXGJEYYQPVPBWNCKVKLZTCBDLDCTSNRCOOVPTGBVBBISGJSOYHDENCTNUUKCUGHREVWBDJCTQXXOGLEBZMDBRZOSXDTZSZBGDCFPRBZYQGSNCCHGYEWOHVJBYZGKDGYNNEUJIWCTYCYTUUMBOYVUNNQUKKSOBSCORSUOSCNVROQLHEUDSUKYMIGIBSXPIHNTUVGGHIFQTGZXLGYQCNVNSRCLVPYOSVRBKCEXRNLGDYWEBFXIVKKTUGKPVMZOTUOGMHHZDREKJHLEFKKPOXLWBWVBYUKDTQUHDQTREVRQJMQWNDOVWLJHCCXCFXRPPXMSJEZCJUFTBRZZMCSSNJNYLCGLOYCITVYQXPDIYFGEFYVXSXHKEGXKMMDSWBCYRKIZOCGMFDDTMWZTLSSFLJMOOLUUQJMIJSCIQVRUISTLTGNCLGKIKTZHRXENRXJHYZTLXICWWMYWXDYIBLERBFLWJQYWONGIQQCUUQTPPHBIEHTUVGCEGPEYMWICGKWJCUFKLUIDMJDIVPJDM"
    pred = replace(encode!(enigma, input2), " ", "")
    @assert pred == output

    enigma = get_M3_enigma('B', (3,5,8), "MCJ")
    output2 = "JFHJ"*"BXOD"*"IIZK"*"CHJU"*"TGOL"*"FIYX"*"RSLF"*"KKPO"*"JVRO"
    @assert encode!(enigma, input) == output2
    enigma = get_M3_enigma('B', (3,5,8), "MCJ")
    @assert encode!(enigma, output2) == input

    enigma = get_M3_enigma('C', (8,2,4), "PXM", "AB CY ET FQ HZ LG MJ OK US WX")
    output3 = "ULQC"*"XYXN"*"JMKV"*"FNAO"*"IVZS"*"OFTW"*"GQBB"*"XNWW"*"BIYS"
    @assert encode!(enigma, input) == output3
    enigma = get_M3_enigma('C', (8,2,4), "PXM", "AB CY ET FQ HZ LG MJ OK US WX")
    @assert encode!(enigma, output3) == input
end


text:
package org.pcsoft.framework.jcoding.type;

/**
 * Enumeration with all known visibility types
 */
public enum JVisibility {
    Public("public"),
    PackageInternal(""),
    Default(""),
    Protected("protected"),
    Private("private");

    private final String keyword;

    private JVisibility(String keyword) {
        this.keyword = keyword;
    }

    public String getKeyword() {
        return keyword;
    }
}


text:
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
// THIS FILE IS AUTOGENERATED, PLEASE DO NOT EDIT OR ELSE
package gnu.trove;

/**
 * Interface for procedures with one double parameter.
 *
 * Created: Mon Nov  5 21:45:49 2001
 *
 * @author Eric D. Friedman
 */

public interface TDoubleProcedure {
    /**
     * Executes this procedure. A false return value indicates that
     * the application executing this procedure should not invoke this
     * procedure again.
     *
     * @param value a value of type double
     * @return true if additional invocations of the procedure are
     * allowed.
     */
    boolean execute(double value);
}// TDoubleProcedure


text:
package cmput301f17t26.smores.all_exceptions;

/**
 * Created by Rohan on 10/19/2017.
 */

public class CommentTooLongException extends Exception {
}


text:
"""
    walle-web

    :copyright: © 2015-2017 walle-web.io
    :created time: 2017-03-19 15:50:07
    :author: wushuiyong@walle-web.io
"""
try:
    from flask_wtf import FlaskForm  # Try Flask-WTF v0.13+
except ImportError:
    from flask_wtf import Form as FlaskForm  # Fallback to Flask-WTF v0.12 or older
from flask_login import current_user
from walle.model.project import ProjectModel
from walle.service.notice import Notice
from wtforms import StringField
from wtforms import validators, ValidationError
from datetime import datetime

class ProjectForm(FlaskForm):
    name = StringField('name', [validators.Length(min=1, max=100)])
    environment_id = StringField('environment_id', [validators.Length(min=1, max=10)])
    space_id = StringField('space_id', [validators.Length(min=1, max=10)])
    status = StringField('status', [])
    excludes = StringField('excludes', [])
    is_include = StringField('excludes', [])
    master = StringField('master', [])
    server_ids = StringField('server_ids', [validators.Length(min=1)])
    keep_version_num = StringField('keep_version_num', [])

    target_root = StringField('target_root', [validators.Length(min=1, max=200)])
    target_releases = StringField('target_releases', [validators.Length(min=1, max=200)])

    task_vars = StringField('task_vars', [])
    prev_deploy = StringField('prev_deploy', [])
    post_deploy = StringField('post_deploy', [])
    prev_release = StringField('prev_release', [])
    post_release = StringField('post_release', [])

    repo_url = StringField('repo_url', [validators.Length(min=1, max=200)])
    repo_username = StringField('repo_username', [])
    repo_password = StringField('repo_password', [])
    repo_mode = StringField('repo_mode', [validators.Length(min=1, max=50)])
    notice_type = StringField('notice_type', [])
    notice_hook = StringField('notice_hook', [])
    task_audit = StringField('task_audit', [])

    id = None

    def set_id(self, id):
        self.id = id

    def form2dict(self):
        return {
            'name': self.name.data.replace('"', '').replace("'", ''),
            'user_id': current_user.id,

            'status': self.status.data if self.status.data else 1,
            'master': self.master.data if self.master.data else '',
            'environment_id': self.environment_id.data if self.environment_id.data else '',
            'space_id': self.space_id.data if self.space_id.data else current_user.space_id(),
            'excludes': self.excludes.data if self.excludes.data else '',
            'is_include': self.is_include.data,
            'server_ids': self.server_ids.data if self.server_ids.data else '',
            'keep_version_num': self.keep_version_num.data if self.keep_version_num.data else 5,

            'target_root': self.target_root.data.rstrip('/') if self.target_root.data else '',
            'target_releases': self.target_releases.data if self.target_releases.data else '',

            'task_vars': self.task_vars.data if self.task_vars.data else '',
            'prev_deploy': self.prev_deploy.data if self.prev_deploy.data else '',
            'post_deploy': self.post_deploy.data if self.post_deploy.data else '',
            'prev_release': self.prev_release.data if self.prev_release.data else '',
            'post_release': self.post_release.data if self.post_release.data else '',

            'repo_url': self.repo_url.data if self.repo_url.data else '',
            'repo_username': self.repo_username.data if self.repo_username.data else '',
            'repo_password': self.repo_password.data if self.repo_password.data else '',
            'repo_mode': self.repo_mode.data if self.repo_mode.data else '',

            'notice_type': self.notice_type.data if self.notice_type.data in [Notice.by_email,
                                                                              Notice.by_dingding] else '',
            'notice_hook': self.notice_hook.data if self.notice_hook.data else '',
            'task_audit': self.task_audit.data if self.task_audit.data else 0,
            'created_at': datetime.now(),
            'updated_at': datetime.now(),

        }


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

    <Button
        android:id="@+id/loadMoreButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dip"
        android:layout_marginRight="20dip"
        android:text="@string/loadmore"
        android:background="@drawable/normal_btn_click"/>

</LinearLayout>


text:
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _

class SocialAccountConfig(AppConfig):
    name = 'allauth.socialaccount'
    verbose_name = _('Social Accounts')