text:
package nl.knaw.dans.common.lang.repo;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import nl.knaw.dans.common.lang.repo.exception.LockAcquireTimeoutException;

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

/**
 * This object aids in synchronization of lists of objects by their ID. This
 * is especially handy for implementing thread-safe transaction handling. A
 * transaction involving several objects cannot start until another transaction
 * that is busy with one or more of the same objects.
 *
 * Example:
 * If one thread has several objects with the IDs A, B and C and wants to do
 * some operation on them, but another thread wants to do an operation on
 * object C and D then the second thread cannot start until the first thread
 * finishes and if a third thread wants to do some operation on D then it has
 * to wait for the second thread to finish first, etc.
 *
 * @author lobo
 */
public class IdSynchronizer<T>
{
    /**
     * key = ID
     * value = the lock
     */
    private Map<T, IdLock> idLocks = new HashMap<T, IdLock>();

    /**
     * key = ID
     * value = use count = how often a thread acquire a lock for this ID
     */
    private ThreadLocal<Map<T, Integer>> threadLocalIds = new ThreadLocal<Map<T, Integer>>();

    private int defaultLockTimeout;

    private boolean useFairPolicy;

    private static final Logger LOGGER = LoggerFactory.getLogger(IdSynchronizer.class);

    private ThreadLocal<Boolean> logEnabled = new ThreadLocal<Boolean>();

    private class IdLock
    {
        public ReentrantLock lock;
        public int threadCount;
        public T id;

        public IdLock(T id, boolean useFairPolicy)
        {
            lock = new ReentrantLock(useFairPolicy);
            threadCount = 1;
            this.id = id;
        }

        public void lock(int timeout) throws LockAcquireTimeoutException, InterruptedException
        {
            if (!lock.tryLock(0, TimeUnit.MILLISECONDS))
            {
                LOGGER.debug("Thread " + Thread.currentThread().toString() + " blocking for " + id);

                if (timeout >= 0)
                {
                    if (!lock.tryLock(timeout, TimeUnit.MILLISECONDS))
                    {
                        LOGGER.debug("Thread " + Thread.currentThread().toString() + " timedout trying to get lock for " + id);

                        throw new LockAcquireTimeoutException();
                    }
                }
                else
                {
                    try
                    {
                        // now only god can stop us, so better say your prayers :)
                        lock.lock();
                    }
                    catch (Throwable t)
                    {
                        // god did not listen to your prayers
                        if (t instanceof InterruptedException)
                            throw (InterruptedException) t;
                        else
                            throw new InterruptedException("Wait for lock on " + this.id + " interrupted. " + t.getMessage() != null ? t.getMessage() : "");
                    }
                }

                LOGGER.debug("Thread " + Thread.currentThread().toString() + " got lock for " + id);
            }
        }

        public void unlock()
        {
            try
            {
                lock.unlock();
            }
            catch (IllegalMonitorStateException e)
            {
                warn("Unlock called on " + this.id + " for thread that did not hold that lock", e);
            }
        }
    }

    public IdSynchronizer()
    {
        this(-1, false);
    }

    /**
     * @param defaultLockTimeout the default timeout value for trying to acquire a lock in milliseconds.
     * Set to -1 for no timeout, but possible infinite wait.
     * @param useFairPolicy see {@see ReentrantLock}. It's basically that the first thread to try
     * to acquire a lock gets it first (fifo).
     */
    public IdSynchronizer(int defaultLockTimeout, boolean useFairPolicy)
    {
        this.setDefaultLockTimeout(defaultLockTimeout);
        this.useFairPolicy = useFairPolicy;
    }

    private void warn(String msg)
    {
        warn(msg, null);
    }

    private void warn(String msg, Throwable t)
    {
        if (isLoggingEnabled())
            LOGGER.warn(msg, t);
    }

    private boolean isLoggingEnabled()
    {
        return logEnabled.get() == null || logEnabled.get().equals(Boolean.TRUE);
    }

    private void disableLogging()
    {
        logEnabled.set(Boolean.FALSE);
    }

    private void enableLogging()
    {
        logEnabled.set(Boolean.TRUE);
    }

    /**
     * Convenience method.
     *
     * Beware not to call this in a loop for multiple sids as that could
     * lead to dead locks. Think of thread 1 asking for a lock on A and
     * B while thread 2 asking for a lock on B and A asking for one lock
     * at a time, they might get stuck waiting on each other.
     *
     * @param id
     * @throws InterruptedException
     * @throws LockAcquireTimeoutException
     */
    public void acquireLock(T id) throws InterruptedException, LockAcquireTimeoutException
    {
        List<T> ids = new ArrayList<T>(1);
        ids.add(id);
        acquireLock(ids);
    }

    /**
     * Locks on a list of IDs. If one of the IDs was already locked then
     * this method will block until those locks are unlocked.
     *
     * If an exception is thrown it can be assumed that no locks are held anymore. So
     * either this method returns and all locks have been acquired or this method
     * throws an exception and no locks are acquired.
     *
     * @param ids a list of IDs
     * @throws InterruptedException thrown if the blocking thread got interrupted and had to abort
     * trying to acquire the lock
     * @throws LockAcquireTimeoutException thrown if the thread could not acquire the lock within
     * the defaultLockTimeout time.
     */
    public void acquireLock(final Collection<T> ids) throws InterruptedException, LockAcquireTimeoutException
    {
        List<IdLock> lockList = null;
        synchronized (idLocks)
        {
            Map<T, Integer> localIds = threadLocalIds.get();
            if (localIds == null)
                localIds = new HashMap<T, Integer>();

            for (T id : ids)
            {
                Integer useCount = localIds.get(id);
                if (useCount == null)
                {
                    useCount = new Integer(1);
                    localIds.put(id, useCount);
                }
                else
                {
                    useCount++;
                    localIds.put(id, useCount);
                    // skip locking: thread is already locked
                    continue;
                }

                IdLock idLock = idLocks.get(id);
                if (idLock == null)
                {
                    // new lock
                    idLock = new IdLock(id, useFairPolicy);
                    idLock.lock(defaultLockTimeout); // first time lock
                    idLocks.put(id, idLock);
                }
                else
                {
                    // existing lock
                    idLock.threadCount += 1;
                    if (lockList == null)
                        lockList = new ArrayList<IdLock>(ids.size());
                    lockList.add(idLock);
                }
            }

            threadLocalIds.set(localIds);
        }

        // do the locking outside the synchronized block
        // otherwise the blocking of the lock will block
        // the entire synchronized block, which will then
        // block every other call to aquireLock or releaseLock
        if (lockList != null)
        {
            try
            {
                for (IdLock idLock : lockList)
                {
                    idLock.lock(defaultLockTimeout);
                }
            }
            catch (InterruptedException e)
            {
                disableLogging();
                releaseLock(ids);
                enableLogging();

                warn("IdSynchronizer.acquireLock() interrupted", e);
                if (e instanceof InterruptedException)
                    throw (InterruptedException) e;
                else
                    throw new InterruptedException();
            }
        }
    }

    public void releaseLock(T id)
    {
        List<T> ids = new ArrayList<T>(1);
        ids.add(id);
        releaseLock(ids);
    }

    /**
     * Releases the lock or locks acquired by called acquireLock.
     */
    public void releaseLock(Collection<T> ids)
    {
        synchronized (idLocks)
        {
            Map<T, Integer> localIds = threadLocalIds.get();
            if (localIds == null)
            {
                warn("releaseLock called by thread that does not own " + "any locks.");
                return;
            }

            for (T id : ids)
            {
                Integer useCount = localIds.get(id);
                if (useCount == null)
                {
                    warn("releaseLock called on invalid ID '" + id.toString() + "'. " + "This ID was not locked by this thread.");
                    continue;
                }
                useCount--;

                if (useCount == 0)
                {
                    IdLock idLock = idLocks.get(id);
                    if (idLock != null)
                    {
                        idLock.unlock();
                        idLock.threadCount--;
                        if (idLock.threadCount == 0)
                            idLocks.remove(id);
                    }
                    else
                    {
                        // log this case but do no interrupt runtime
                        LOGGER.error("lock in thread list, but not found: " + "this should not happen. Programming mistake in " + this.getClass() + " class.");
                    }

                    localIds.remove(id);
                }
                else
                {
                    localIds.put(id, useCount);
                }
            }

            if (localIds.size() == 0)
                threadLocalIds.set(null);
        }
    }

    /**
     * @return the number of id's that are currently locked
     */
    protected int getLockIdCount()
    {
        synchronized (idLocks)
        {
            return idLocks.size();
        }
    }

    /**
     * @return the number of threads waiting for a lock on a id
     */
    protected int getLockThreadCount(T id)
    {
        synchronized (idLocks)
        {
            IdLock idLock = idLocks.get(id);
            if (idLock != null)
                return idLock.threadCount;
            else
                return 0;
        }
    }

    /**
     * @return the number of times a thread acquired a lock for a single ID
     */
    protected int getLockThreadUseCount(T id)
    {
        synchronized (idLocks)
        {
            Map<T, Integer> localIds = threadLocalIds.get();
            if (localIds == null)
            {
                return 0;
            }

            Integer useCount = localIds.get(id);
            if (useCount == null)
            {
                return 0;
            }
            else
            {
                return useCount;
            }
        }
    }

    /**
     * Sets the default timeout value in milliseconds for this class to acquire a lock.
     */
    public void setDefaultLockTimeout(int defaultLockTimeout)
    {
        this.defaultLockTimeout = defaultLockTimeout;
    }

    /**
     * Gets the default timeout value in milliseconds for this class to acquire a lock.
     */
    public int getDefaultLockTimeout()
    {
        return defaultLockTimeout;
    }

    /**
     * @return true if the attempt to get the lock will be based on a fair use policy
     * (fifo).
     */
    public boolean isUsingFairPolicy()
    {
        return useFairPolicy;
    }

}


text:
import re
import random
import socket
import string
import codecs
import urllib2
import ConfigParser
from plugin import Plugin
from wikitools import wiki
from vendor import importdir
from bs4 import BeautifulSoup
from wikitools import category
from asyncirc.ircbot import IRCBot

class Rezeptionistin(object):

  # Constructor
  #

  def __init__(self):

    # load config
    config = ConfigParser.ConfigParser()
    if not config.read("config.ini"):
      print "Error: your config.ini could not be read"
      exit(1)

    # load plugins
    importdir.do("plugins", globals())
    self.plugins = [module() for module in Plugin.__subclasses__()]

    self.server=config.get('IRC','server')
    self.port=int(config.get('IRC', 'port'))
    self.nick=config.get('IRC', 'nick')
    self.ircchan=config.get('IRC', 'ircchan')
    self.debugchan=config.get('IRC', 'debugchan')
    self.useragent=config.get('HTTP', 'useragent')
    self.site = wiki.Wiki(config.get('MediaWiki', 'wikiapiurl'))
    self.site.login(config.get('MediaWiki', 'user'), config.get('MediaWiki', 'password'))
    self.httpregex=re.compile(r'https?://')

    self.irc = IRCBot(self.server, self.port, self.nick)

  # Helper Methods
  #

  def netcat(self, hostname, port, content):
    s = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)
    s.connect((hostname, port))
    s.shutdown(socket.SHUT_WR)
    while 1:
      data = s.recv(1024)
      if data == "":
        break
      f = data
    s.close()
    return f

  def wikiupdate(self, title, url):
    cat = category.Category(self.site, "Linklist")
    for article in cat.getAllMembersGen(namespaces=[0]):
      print article.edit(appendtext="\n* {title} - {url} \n".format(title=title, url=url))

  def geturlfrommsg(self, message):
    url = re.search("(?P<url>https?://[^\s]+)", message).group("url")
    return url

  def getpage(self, url):
    req = urllib2.Request(url, headers={ 'User-Agent': self.useragent })
    soup = BeautifulSoup(urllib2.urlopen(req))
    return soup

  def geturltitle(self, url):
    try:
      page = self.getpage(url)
      title = self.sanitize(page.title.string.lstrip())
    except:
      title = ""
    return title

  def split_by_nth(self, text, n, seperator=' '):
    groups = text.split(seperator)
    res_l = list(seperator.join(groups[:n]))
    res_r = list(seperator.join(groups[n:]))
    res_l.extend(res_r)
    return res_l

  def send_message(self, recipient, msg):
    self.irc.msg(recipient, "\x0F" + msg)

  def send_command(self, recipient, cmd):
    self.irc.msg(recipient, cmd)

  def sanitize(self, s):
    return str(s).translate(string.maketrans("\n\r",'  '))

  # IRC Handlers

  def on_msg(self, irc, user_nick, host, channel, message):
    for plugin in self.plugins:
      plugin.on_msg(self, user_nick, host, channel, message)

  def on_privmsg(self, irc, user_nick, host, message):
    for plugin in self.plugins:
      plugin.on_privmsg(self, user_nick, host, message)

  def on_join(self, irc, user_nick, host, channel):
    for plugin in self.plugins:
      plugin.on_join(self, user_nick, host, channel)

  # Operations

  def run(self):
    # Assign event handlers
    self.irc.on_msg(self.on_msg)
    self.irc.on_privmsg(self.on_privmsg)
    self.irc.on_join(self.on_join)

    # Start Bot
    self.irc.start()
    self.irc.join(self.ircchan)
    self.irc.join(self.debugchan)

    # Run Eventloop
    try:
      while self.irc.running:
        self.irc.send_raw(raw_input(""))
    except KeyboardInterrupt:
      print("Received exit command")
    finally:
      self.irc.stop()

redpajama_set_name: RedPajamaGithub


text:
var fs = require('fs');
var log = require('./logging')('writer');

function write(filename, json, sync) {
    if (sync) {
        try {
            fs.writeFileSync(filename, JSON.stringify(json, null, 4));
            log.info("The file was saved to " + filename);
        } catch (e) {
            log.warn(e);
        }
    }
    else {
        fs.writeFile(filename, JSON.stringify(json, null, 4), function(err) {
            if (err) {
                log.warn(err);
                return;
            }

            log.info("The file was saved to "+filename);
        });
    }
}

// Functions which will be available to external callers
exports.write = write;


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="Hello">Hello World, Click Me!</string>
    <string name="ApplicationName">MvvmCross.Droid</string>
</resources>


text:
module.exports = GC

var EventEmitter = require("events").EventEmitter
var util = require("util")
var t2filter = require("through2-filter")
var spy = require("through2-spy")
var Transform = require("stream").Transform || require("readable-stream/transform")

function GC(db, fn, lts) {
  if (!(this instanceof GC)) return new GC(db, fn, lts)
  EventEmitter.call(this)
  this.db = db
  this.Filter = t2filter.ctor({objectMode: true}, fn)
  this.lts = lts
}
util.inherits(GC, EventEmitter)

GC.prototype.run = function (cb) {
  var self = this
  var start = Date.now()
  var end
  var scanned = culled = 0

  var rs = this.db.readStream()

  var ws = this.db.writeStream({type: "del"})
  var reply = function () {
    if (end) return
    end = Date.now()
    self.emit("finish", start, end, scanned, culled)
    if (cb) return cb(null, start, end, scanned, culled)
  }
  ws.once("end", reply)
  ws.once("close", reply)
  ws.once("error", function (err) {
    if (cb) return cb(err)
    throw err
  })

  var filter = new this.Filter({objectMode: true})
  if (!filter instanceof Transform) return cb(new Error("Filter must be a streams2 Transform"))

  var spyOpts = {objectMode: true}

  var pipeline = rs
    .pipe(spy(spyOpts, function () {scanned++}))
    .pipe(filter)
    .pipe(spy(spyOpts, function () {culled++}))

  if (this.lts) pipeline.pipe(this.lts.writeStream())

  pipeline.pipe(ws)
}


text:
package com.gs.fw.common.mithra.test;

import java.sql.*;

import com.gs.fw.common.mithra.MithraManager;
import com.gs.fw.common.mithra.MithraManagerProvider;
import com.gs.fw.common.mithra.MithraTransaction;
import com.gs.fw.common.mithra.TransactionalCommand;
import com.gs.fw.common.mithra.finder.Operation;
import com.gs.fw.common.mithra.test.domain.*;

public class TestInplaceUpdate extends MithraTestAbstract
{

    private  AuditedOrderList getAllAuditedOrders()
    {
        Operation op = AuditedOrderFinder.all();
        AuditedOrderList list = new AuditedOrderList(op);
        assertTrue(list.size() >  0);

        return list;
    }

    public void testAuditedWithMultupleInPlaceUpdateAndTerminate()
    {
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand<Object>()
        {
            @Override
            public Object executeTransaction(MithraTransaction tx) throws Throwable
            {
                AuditedOrderList list = AuditedOrderFinder.findMany(AuditedOrderFinder.processingDate().eq(InfinityTimestamp.getParaInfinity()));
                assert(list.size() > 1);
                for(int i=0;i<list.size();i++)
                {
                    list.get(i).setDescriptionUsingInPlaceUpdate("inplace");
                }
                list.get(0).cascadeTerminate();
                return null;
            }
        });
    }

    public void testAuditedWithInplaceUpdate()
    {
        AuditedOrderList list = getAllAuditedOrders();
        final AuditedOrder auditedOrder = list.get(0);

        Operation initOp = AuditedOrderFinder.processingDate().equalsEdgePoint()
                                .and(AuditedOrderFinder.processingDateFrom().greaterThan(new Timestamp(1)));
        int originalSize = (new AuditedOrderList(initOp).size());

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand()
        {
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    auditedOrder.setDescriptionUsingInPlaceUpdate("Young");
                    return null;
                }
        });
        Operation op4 = AuditedOrderFinder.processingDate().equalsEdgePoint()
                                .and(AuditedOrderFinder.processingDateFrom().greaterThan(new Timestamp(1)));
        int resultSize = new AuditedOrderList(op4).size();
        assertEquals(originalSize, resultSize);

        Operation op3 = AuditedOrderFinder.description().eq("Young");
        AuditedOrderList list3 = new AuditedOrderList(op3);
        assertTrue(list3.size() == 1) ;
    }

    public void testAuditedWithRegularUpdate()
    {
        AuditedOrderList list = getAllAuditedOrders();
        final AuditedOrder auditedOrder = list.get(0);

        Operation initOp = AuditedOrderFinder.processingDate().equalsEdgePoint()
                                .and(AuditedOrderFinder.processingDateFrom().greaterThan(new Timestamp(1)));
        int originalSize = (new AuditedOrderList(initOp).size());

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand(){
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    auditedOrder.setDescription("Ryu");
                    return null;
                }
        });
        Operation op4 = AuditedOrderFinder.processingDate().equalsEdgePoint()
                                .and(AuditedOrderFinder.processingDateFrom().greaterThan(new Timestamp(1)));
        int resultSize = new AuditedOrderList(op4).size();
        assertTrue(originalSize < resultSize);

        Operation op5 = AuditedOrderFinder.description().eq("Ryu");
        AuditedOrderList list5 = new AuditedOrderList(op5);
        assertTrue(list5.size() == 1);
    }

    protected BitemporalOrderList getAllBitemporalOrders()
    {
        Operation op = BitemporalOrderFinder.all()
                            .and(BitemporalOrderFinder.businessDate().eq(createReferenceBusinessDate(2000, 1, 1)));
        BitemporalOrderList bitemporalOrders = new BitemporalOrderList(op);
        assertTrue(bitemporalOrders.size() > 0);

        return bitemporalOrders;
    }

    public void testBitemporalWithInplaceUpdate()
    {
        Operation initOp = BitemporalOrderFinder.processingDate().equalsEdgePoint()
                                .and(BitemporalOrderFinder.businessDate().equalsEdgePoint())
                                .and(BitemporalOrderFinder.processingDateFrom().greaterThan(new Timestamp(1))
                                .and(BitemporalOrderFinder.businessDateFrom().greaterThan(new Timestamp(1))));
        int originalSize = (new AuditedOrderList(initOp).size());

        final BitemporalOrder bitemproalOrder = getAllBitemporalOrders().get(0);
        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand(){
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    bitemproalOrder.setDescriptionUsingInPlaceUpdate("Description InplaceUpdate");
                    return null;
                }
        });
        Operation resultOp = BitemporalOrderFinder.processingDate().equalsEdgePoint()
                                .and(BitemporalOrderFinder.businessDate().equalsEdgePoint())
                                .and(BitemporalOrderFinder.processingDateFrom().greaterThan(new Timestamp(1))
                                .and(BitemporalOrderFinder.businessDateFrom().greaterThan(new Timestamp(1))));
        int resultSize = (new BitemporalOrderList(resultOp).size());
        assertEquals(originalSize, resultSize);

        Operation op3 = BitemporalOrderFinder.description().eq("Description InplaceUpdate")
                            .and(BitemporalOrderFinder.businessDate().eq(createReferenceBusinessDate(2000, 1, 1)));
        BitemporalOrderList list3 = new BitemporalOrderList(op3);
        assertEquals(list3.size(), 1);
    }

    public void testBitemporalWithRegularUpdate()
    {
        Operation initOp = BitemporalOrderFinder.processingDate().equalsEdgePoint()
                                .and(BitemporalOrderFinder.businessDate().equalsEdgePoint())
                                .and(BitemporalOrderFinder.processingDateFrom().greaterThan(new Timestamp(1))
                                .and(BitemporalOrderFinder.businessDateFrom().greaterThan(new Timestamp(1))));
        int originalSize = (new AuditedOrderList(initOp).size());

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand(){
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    getAllBitemporalOrders().get(0).setDescription("Description Regular Update");
                    return null;
                }
        });
        Operation resultOp = BitemporalOrderFinder.processingDate().equalsEdgePoint()
                                .and(BitemporalOrderFinder.businessDate().equalsEdgePoint())
                                .and(BitemporalOrderFinder.processingDateFrom().greaterThan(new Timestamp(1))
                                .and(BitemporalOrderFinder.businessDateFrom().greaterThan(new Timestamp(1))));
        int resultSize = (new BitemporalOrderList(resultOp).size());
        assertTrue(originalSize < resultSize);

        Operation op4 = BitemporalOrderFinder.description().eq("Description Regular Update")
                            .and(BitemporalOrderFinder.businessDate().eq(createReferenceBusinessDate(2000, 1, 1)));
        BitemporalOrderList list4 = new BitemporalOrderList(op4);
        assertTrue(list4.size() == 1);
    }

    public void testBitemporalWithMixedUpdates()
    {
        Operation initOp = BitemporalOrderFinder.processingDate().equalsEdgePoint()
                                .and(BitemporalOrderFinder.businessDate().equalsEdgePoint())
                                .and(BitemporalOrderFinder.processingDateFrom().greaterThan(new Timestamp(1))
                                .and(BitemporalOrderFinder.businessDateFrom().greaterThan(new Timestamp(1))));
        int originalSize = (new AuditedOrderList(initOp).size());

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand(){
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    getAllBitemporalOrders().get(0).setDescriptionUsingInPlaceUpdate("Description MIX Update");
                    getAllBitemporalOrders().get(0).setUserId(-666);
                    return null;
                }
        });
        Operation resultOp = BitemporalOrderFinder.processingDate().equalsEdgePoint()
                                .and(BitemporalOrderFinder.businessDate().equalsEdgePoint())
                                .and(BitemporalOrderFinder.processingDateFrom().greaterThan(new Timestamp(1))
                                .and(BitemporalOrderFinder.businessDateFrom().greaterThan(new Timestamp(1))));
        int resultSize = (new BitemporalOrderList(resultOp).size());
        assertTrue(originalSize < resultSize);

        Operation op5 = BitemporalOrderFinder.description().eq("Description MIX Update")
                            .and(BitemporalOrderFinder.businessDate().eq(createReferenceBusinessDate(2000, 1, 1)))
                            .and(BitemporalOrderFinder.userId().eq(-666));
        BitemporalOrderList list5 = new BitemporalOrderList(op5);
        assertTrue(list5.size() == 1);
    }

    public void testAuditedWithInplaceUpdateAndDelete()
    {
        AuditedOrderList list = getAllAuditedOrders();
        final AuditedOrder auditedOrder = list.get(0);

        Operation initOp = AuditedOrderFinder.processingDate().equalsEdgePoint()
                                .and(AuditedOrderFinder.processingDateFrom().greaterThan(new Timestamp(1)));
        int originalSize = (new AuditedOrderList(initOp).size());

        MithraManagerProvider.getMithraManager().executeTransactionalCommand(new TransactionalCommand(){
                public Object executeTransaction(MithraTransaction tx) throws Throwable
                {
                    auditedOrder.setDescriptionUsingInPlaceUpdate("Young");
                    auditedOrder.terminate();
                    return null;
                }
        });
        Operation op4 = AuditedOrderFinder.processingDate().equalsEdgePoint()
                                .and(AuditedOrderFinder.processingDateFrom().greaterThan(new Timestamp(1)));
        int resultSize = new AuditedOrderList(op4).size();
        assertEquals(originalSize, resultSize);

        Operation op3 = AuditedOrderFinder.description().eq("Young");
        AuditedOrderList list3 = new AuditedOrderList(op3);
        assertEquals(0, list3.size());
    }
}


text:
#contenu { width:1000px; background-color:grey; border: 2px solid black;
}

#titre { text-align:center;
}

#date { width:500px; float:left; height: 300px;
}

#localisation {width:500px; height: 300px; float:left;
}

#especes {width:1000px;
}

#bas_de_page {
}

h1{color:white;}

table{
	border-color: green;
	border-width: 0 0 1px 1px;
	border-style: solid;
	border-spacing: 0px;
	font-size: small;
}
tr{
	background-color:white;
	color:darkgreen;
}
td{
	border-color: green;
	border-width: 1px 1px 0 0;
	border-style: solid;
	color: darkgreen;
	padding: 5px;
}
th{
	border-color: green;
	border-width: 1px 1px 0 0;
	border-style: solid;
	background-color:yellowgreen;
	color:white;
	padding: 5px;
}

body{
	color:black;
	background-color: #C8C8C8 ;
	background: url(/assets/images/paper_texture_04.png) no-repeat center center fixed;
	-webkit-background-size: cover;
	-moz-background-size: cover;
	-o-background-size: cover;
	background-size: cover;
}

ul{
	list-style-type:none;
	margin:0;
	padding:0;
	overflow:hidden;
}
li{
	float:left;
	display:block;
	width:inherit;
}

table.gestionDesTemoinsPassifs{
	font-size:0.6em;
}
input.nouveauTemoinInput{
	width:90px;
}
input.nouveauTemoinCours{
	width:60px;
}
input.nouveauTemoinCivilite{
	width:20px;
}

body {
	background-color: #EDEDED;
	font-family: sans-serif;
	font-size: medium;
}

/*button{*/
	/*padding: 5px;*/
	/*width: 200px;*/
	/*border: none;*/
	/*background: cornflowerblue;*/
	/*background: yellowgreen;*/
	/*transition: border 0.3s;*/
	/*color: white;*/
/*}*/

/*button:hover{*/
	/*padding: 5px;*/
	/*width: 200px;*/
	/*border: solid 1px white;*/
	/*background: cornflowerblue;*/
	/*background: yellowgreen;*/
	/*transition: border 0.3s;*/
	/*color: white;*/
/*}*/


text:
angular.module('mc.common').factory('mc.common.remove',
[
    function()
    {
        function remove(item)
        {
            this.fromCollectionOf = function(items)
            {
                items.splice(items.indexOf(item), 1);
            };

            return this;
        };

        return remove;
    }
]);


text:
var Scraper = require('./Scraper');

class scraper extends Scraper.UltiproScraper {

	constructor(company) {
        var string1 = "QUA1003QBP";
        var string2 = "0a11c700-8c72-42cc-bea0-d774f5014673";
        super(company, string1, string2);
    }

}

module.exports = scraper;


text:
package io.vertx.it;

import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.jdbc.JDBCClient;
import io.vertx.ext.jdbc.spi.DataSourceProvider;
import io.vertx.ext.sql.ResultSet;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.RunTestOnContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.jdbcclient.JDBCConnectOptions;
import io.vertx.jdbcclient.JDBCPool;
import io.vertx.jdbcclient.SqlOutParam;
import io.vertx.jdbcclient.impl.AgroalCPDataSourceProvider;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowStream;
import io.vertx.sqlclient.Tuple;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.postgresql.util.PGInterval;
import org.testcontainers.containers.PostgreSQLContainer;

import java.sql.JDBCType;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.util.Arrays;
import java.util.List;

@RunWith(VertxUnitRunner.class)
public class PostgresTest {

  @ClassRule
  public static final RunTestOnContext rule = new RunTestOnContext();

  @SuppressWarnings("rawtypes")
  @ClassRule
  public static final PostgreSQLContainer server = (PostgreSQLContainer) new PostgreSQLContainer("postgres:12-alpine")
    .withInitScript("init-pgsql.sql");

  protected JDBCPool initJDBCPool(JsonObject extraOption) {
    final JDBCConnectOptions options = new JDBCConnectOptions().setJdbcUrl(server.getJdbcUrl())
      .setUser(server.getUsername())
      .setPassword(server.getPassword());
    final DataSourceProvider provider = new AgroalCPDataSourceProvider(options, new PoolOptions().setMaxSize(1));
    return JDBCPool.pool(rule.vertx(), provider.init(extraOption));
  }

  protected JDBCClient initJDBCClient(JsonObject extraOption) {
    JsonObject options = new JsonObject().put("url", server.getJdbcUrl())
      .put("user", server.getUsername())
      .put("password", server.getPassword());
    return JDBCClient.createShared(rule.vertx(), options.mergeIn(extraOption, true), "dbName");
  }

  @Test
  public void simpleClientCallFunctionTest(TestContext should) {
    final Async test = should.async();
    final JDBCClient client = initJDBCClient(new JsonObject());

    client.callWithParams(
      "{ call animal_stats(?, ?, ?) }",
      new JsonArray().add(false),
      new JsonArray().addNull().add("BIGINT").add("REAL"),
      asyncResult -> {
        if (asyncResult.failed()) {
          should.fail(asyncResult.cause());
        } else {
          ResultSet statsResult = asyncResult.result();
          JsonArray output = statsResult.getOutput();
          System.out.println(new JsonObject().put("stats", output.toString()).encodePrettily());
          should.assertTrue(output.getValue(1) instanceof Number);
          should.assertTrue(output.getValue(2) instanceof Number);
          test.complete();
        }
      }
    );
  }

  @Test
  public void simplePoolCallFunctionTest(TestContext should) {
    final Async test = should.async();
    final JDBCPool pool = initJDBCPool(new JsonObject());

    pool
      .preparedQuery("{ call animal_stats(?, ?, ?) }")
      .execute(Tuple.of(false, SqlOutParam.OUT(JDBCType.BIGINT), SqlOutParam.OUT(JDBCType.REAL)))
      .onFailure(should::fail)
      .onSuccess(rows -> {
        // we can verify if there was an output received from the callable statement
        if (rows.property(JDBCPool.OUTPUT)) {
          // and then iterate the results
          for (Row row : rows) {
            should.assertTrue(row.getValue(0) instanceof Number);
            should.assertEquals(3, row.getInteger(0));
            should.assertTrue(row.getValue(1) instanceof Number);
            should.assertEquals(33.33333206176758, row.getDouble(1));
          }
        }

        test.complete();
      });
  }

  @Test
  public void simplePoolSelectFunctionTest(TestContext should) {
    final Async test = should.async();
    final JDBCPool pool = initJDBCPool(new JsonObject());

    pool
      .preparedQuery("select * from animal_stats(?)")
      .execute(Tuple.of(false))
      .onFailure(should::fail)
      .onSuccess(rows -> {
        // we can verify if there was an output received from the callable statement
        for (Row row : rows) {
          should.assertTrue(row.getValue(0) instanceof Number);
          should.assertEquals(3, row.getInteger(0));
          should.assertTrue(row.getValue(1) instanceof Number);
          should.assertEquals(33.33333206176758, row.getDouble(1));
        }

        test.complete();
      });
  }

  @Test
  public void simpleRowStreamTest(TestContext should) {
    final Async test = should.async();
    final JDBCPool pool = initJDBCPool(new JsonObject());

    List<String> animals = Arrays.asList("dog", "cat", "cow");

    pool
      .getConnection()
      .onFailure(should::fail)
      .onSuccess(connection -> {
        connection
          .prepare("SELECT * FROM ANIMAL")
          .onFailure(should::fail)
          .onSuccess(pq -> {
            // Streams require run within a transaction
            connection.begin()
              .onFailure(should::fail)
              .onSuccess(tx -> {
                // Fetch 1 row at a time
                RowStream<Row> stream = pq.createStream(1);
                // Use the stream
                stream.exceptionHandler(should::fail);
                stream.endHandler(v -> {
                  // Close the stream to release the resources in the database
                  stream.close(closed -> tx.commit(committed -> test.complete()));
                });
                stream.handler(row -> should.assertTrue(animals.contains(row.getString("name"))));
              });
          });
      });
  }

  @Test
  public void threeParamsTest(TestContext should) {
    final Async test = should.async();

    final JDBCClient client = initJDBCClient(new JsonObject());
    // 3x INOUT
    callWithInOut(client, "{ call f_inout_inout_inout(?, ?, ?) }",
      new JsonArray().add(false).add(false).add(false),             // OK
      new JsonArray().add("BOOLEAN").add("BOOLEAN").add("BOOLEAN"))
      .compose(v ->
        // 1x IN, 2x INOUT
        callWithInOut(client, "{ call f_in_inout_inout(?, ?, ?) }",
          new JsonArray().add(false).add(false).add(false),             // OK
          new JsonArray().addNull().add("BOOLEAN").add("BOOLEAN")))
      .compose(v ->
        // 1x implicit IN, 2x INOUT
        callWithInOut(client, "{ call f_blank_inout_inout(?, ?, ?) }",
          new JsonArray().add(false).add(false).add(false),             // OK
          new JsonArray().addNull().add("BOOLEAN").add("BOOLEAN")))
      .compose(v ->
        // 1x IN, 2x OUT
        callWithInOut(client, "{ call f_in_out_out(?, ?, ?) }",
          new JsonArray().add(false),                                   // OK
          new JsonArray().addNull().add("BOOLEAN").add("BOOLEAN")))
      .compose(v ->
        // 1x implicit IN, 2x OUT
        callWithInOut(client, "{ call f_blank_out_out(?, ?, ?) }",
          new JsonArray(),                                   // failing
          new JsonArray().addNull().add("BOOLEAN").add("BOOLEAN")))
      .onFailure(should::fail)
      .onSuccess(v -> test.complete());
  }

  private Future<Void> callWithInOut(JDBCClient client, String sql, JsonArray in, JsonArray out) {
    final Promise<Void> promise = ((VertxInternal) rule.vertx()).promise();

    client.callWithParams(
      sql,
      in,
      out,
      asyncResult -> {
        if (asyncResult.failed()) {
          printResults("FAIL ", sql, in, out, asyncResult.cause().getMessage());
          promise.fail(asyncResult.cause());
        } else {
          ResultSet statsResult = asyncResult.result();
          JsonArray output = statsResult.getOutput();
          printResults("OK   ", sql, in, out, output.encodePrettily());
          promise.complete();
        }
      });

    return promise.future();
  }

  private void printResults(String succMsg, String sql, JsonArray in, JsonArray out, String result) {
    System.out.println(succMsg + " sql: " + sql + " \n"
      + " IN: " + in.toString() + "\n"
      + " OUT: " + out.toString() + "\n"
      + " result: " + result);
  }

  @Test
  public void testQueryTemporalTable(TestContext should) {
    final Async async = should.async();
    JDBCClient client = initJDBCClient(new JsonObject());
    client
      .query("SELECT * FROM temporal_data_type WHERE id = 1", should.asyncAssertSuccess(resultSet -> {
        should.assertEquals(1, resultSet.getNumRows());
        final JsonArray row = resultSet.getResults().get(0);
        should.assertEquals(1, row.getInteger(0));
        should.assertEquals(LocalDate.parse("2022-05-30"), row.getValue(1));
        should.assertEquals(LocalTime.parse("18:00:00"), row.getValue(2));
        should.assertEquals(OffsetTime.parse("04:00:00Z"), row.getValue(3));
        should.assertEquals(LocalDateTime.parse("2022-05-14T07:00:00"), row.getValue(4));
        should.assertEquals(OffsetDateTime.parse("2022-05-14T09:00:00Z"), row.getValue(5));
        should.assertEquals("10 years 3 mons 332 days 20 hours 20 mins 20.999999 secs", row.getValue(6));
        async.complete();
      }));
  }

  @Test
  public void testPoolQueryTemporalTable(TestContext should) {
    final Async async = should.async();
    JDBCPool pool = initJDBCPool(new JsonObject());
    pool
      .preparedQuery("SELECT * FROM temporal_data_type WHERE id = 1").execute()
      .onSuccess(rows -> {
        should.assertEquals(1, rows.value().size());
        Row row = rows.value().iterator().next();
        should.assertEquals(1, row.getInteger(0));
        should.assertEquals(LocalDate.parse("2022-05-30"), row.getValue(1));
        should.assertEquals(LocalTime.parse("18:00:00"), row.getValue(2));
        should.assertEquals(OffsetTime.parse("04:00:00Z"), row.getValue(3));
        should.assertEquals(LocalDateTime.parse("2022-05-14T07:00:00"), row.getValue(4));
        should.assertEquals(OffsetDateTime.parse("2022-05-14T09:00:00Z"), row.getValue(5));
        should.assertEquals("10 years 3 mons 332 days 20 hours 20 mins 20.999999 secs", row.getValue(6));
        async.complete();
      })
      .onFailure(should::fail);
  }

  @Test
  public void testInsertTemporalTable(TestContext should) throws SQLException {
    final Async async = should.strictAsync(2);
    final JDBCPool pool = initJDBCPool(new JsonObject());
    final Tuple params = Tuple.tuple()
      .addValue(2)
      .addValue(LocalDate.parse("2022-05-30"))
      .addValue(LocalTime.parse("18:00:00"))
      .addValue(OffsetTime.parse("06:00:00+02:00"))
      .addValue(LocalDateTime.parse("2022-05-14T07:00:00"))
      .addValue(OffsetDateTime.parse("2022-05-14T07:00:00-02:00"))
      .addValue(new PGInterval("10 years 3 mons 332 days 20 hours 20 mins 20.999999 secs"));
    pool
      .preparedQuery("INSERT INTO temporal_data_type" +
        "(\"id\", \"Date\", \"Time\", \"TimeTz\", \"Timestamp\", \"TimestampTz\", \"Interval\") " +
        "VALUES (?, ?, ?, ?, ?, ?, ?)")
      .execute(params)
      .onFailure(should::fail)
      .onSuccess(rows -> async.countDown())
      .flatMap(ignore -> pool.preparedQuery("SELECT * FROM temporal_data_type WHERE id = 2").execute())
      .onFailure(should::fail)
      .onSuccess(rows -> {
        final Row row = rows.value().iterator().next();
        should.assertEquals(2, row.getInteger(0));
        should.assertEquals(LocalDate.parse("2022-05-30"), row.getValue(1));
        should.assertEquals(LocalTime.parse("18:00:00"), row.getValue(2));
        should.assertEquals(OffsetTime.parse("04:00:00Z"), row.getValue(3));
        should.assertEquals(LocalDateTime.parse("2022-05-14T07:00:00"), row.getValue(4));
        should.assertEquals(OffsetDateTime.parse("2022-05-14T09:00:00Z"), row.getValue(5));
        should.assertEquals("10 years 3 mons 332 days 20 hours 20 mins 20.999999 secs", row.getValue(6));
        async.complete();
      });
  }
}


text:
var infos = initViewport();

var canvas = document.getElementById('myCanvas');

//create your world with your options (only the first parameter canvas is mandatory)
var myWorld = boxbox.createWorld(canvas,{
    preventScroll: true,
    disableTouchEvents : !infos.isTouch,    //won't add the touch events listeners if true
    disableKeyEvents : true,                //won't add the key events listeners if true
    disableMouseEvents : infos.isTouch,     //won't add the mouse events listeners if true
    debugDraw: false,
    boundaries : {                          //here you specify where you want your world to stop (while panning for example)
        left : 0,
        right : 30,
        top : 0,
        bottom : 12
    }
});

//walls
//this config is shared by the all the walls
var wallConfig = {
    type: "static",     //the walls won't move
    borderWidth : 0,
    color : "darkred"
};
myWorld.createEntity( wallConfig, {
    name: "left",
    x: 0,
    y: 6,
    width : 0.5,
    height : 12
});
myWorld.createEntity( wallConfig, {
    name: "right",
    x: 30,
    y: 6,
    width : 0.5,
    height : 12
});
myWorld.createEntity( wallConfig, {
    name: "top",
    x: 15,
    y: 0,
    width : 30,
    height : 0.5
});
myWorld.createEntity( wallConfig, {
    name: "bottom",
    x: 15,
    y: 12,
    width : 30,
    height : 0.5
});

//player
var player = myWorld.createEntity({
    name: "player",
    shape: "circle",
    color : "blue",
    borderWidth : 0,
    radius: 1,
    x: 3,
    y: 2,
    onStartContact:function(entity){    //when the player hits the ground, it goes back to blue
        if(entity.name() === "bottom"){
            this.color("blue");
        }
    }
});

//blocks
//this config is shared by all blocks
var blockConfig = {
    shape: "square",
    color: "brown",
    width: 0.5,
    height: 4,
    y: 10,
    onImpact: function( entity, force ) {
        if ( entity.name() === "player" ) {
            this.color( "black" );
            if(force > 40){
                entity.color("red");
            }
        }
        if ( force > 50 && entity.name() !== "bottom" ) {
            this.destroy();
        }
    }
};
myWorld.createEntity( blockConfig, { x: 13 } );
myWorld.createEntity( blockConfig, { x: 19 } );
myWorld.createEntity( blockConfig, { x: 25 } );
myWorld.createEntity( blockConfig, {
        x: 16,
        y: 7,
        width: 6,
        height: 0.5
});
myWorld.createEntity( blockConfig, {
        x: 22,
        y: 7,
        width: 6,
        height: 0.5
});
myWorld.createEntity( blockConfig, { x: 16, y: 4 } );
myWorld.createEntity( blockConfig, { x: 22, y: 4 } );
myWorld.createEntity( blockConfig, {
        x: 19,
        y: 1,
        width: 6,
        height: 0.5
});

//crates
//this config is shared by all crates
var crateConfig = {
    shape: "square",
    color: "yellow",
    width: 2,
    height: 3,
    y: 10
};
var crate1 = myWorld.createEntity( crateConfig, { x: 16 } );
var crate2 = myWorld.createEntity( crateConfig, { x: 22 } );
var crate3 = myWorld.createEntity( crateConfig, { x: 19, y: 5 } );


text:
$(function () {
    var content = $('#content');
    var status = $('#status');
    var input = $('#input');
    var myColor = false;
    var myName = false;
    var connection = new WebSocket('ws:' + window.location.href.substring(window.location.protocol.length));

    connection.onopen = function () {
        status.text('Choose name:');
    };
    connection.onmessage = function (message) {
      var json = JSON.parse(message.data);
         if (json.type === 'color') { // first response from the server with user's color
            myColor = json.data;
            status.text(myName + ': ').css('color', myColor);
        }else if (json.type === 'message') { // it's a single message
            addMessage(json.data.author, json.data.text,
                       json.data.color, new Date(json.data.time));
        }
    };

    input.keydown(function(e) {
        if (e.keyCode === 13) {
            var msg = $(this).val();
            if (!msg)    return;
            connection.send(msg);
            $(this).val('');
            if (myName === false) {
                myName = msg;
            }
        }
    });

    function addMessage(author, message, color, dt) {
        content.append('
' + author + ' @ ' +
             + dt.getHours() + ':'
             + (dt.getMinutes()<10?('0'+ dt.getMinutes()):dt.getMinutes()) + '----' + message + '
');
    }
});


text:
import { StackScreenProps } from "@react-navigation/stack"
import { ArtworkFilterNavigationStack } from "app/Components/ArtworkFilter"
import {
  aggregationForFilter,
  FilterData,
  FilterDisplayName,
  FilterParamName,
} from "app/Components/ArtworkFilter/ArtworkFilterHelpers"
import {
  ArtworksFiltersStore,
  useSelectedOptionsDisplay,
} from "app/Components/ArtworkFilter/ArtworkFilterStore"
import { MultiSelectCheckOptionScreen } from "./MultiSelectCheckOption"
import { useMultiSelect } from "./useMultiSelect"

interface ArtistIDsSaleArtworksOptionsScreenProps
  extends StackScreenProps<ArtworkFilterNavigationStack, "ArtistIDsOptionsScreen"> {}

const isArtistsIFollowFilter = (option: FilterData) => {
  return option.paramName === FilterParamName.artistsIFollow
}
const isAllArtistsFilter = (option: FilterData) => {
  return option.displayText === "All Artists"
}

export const ArtistIDsSaleArtworksOptionsScreen: React.FC<
  ArtistIDsSaleArtworksOptionsScreenProps
> = ({ navigation }) => {
  const paramName = FilterParamName.artistIDs
  const selectFiltersAction = ArtworksFiltersStore.useStoreActions(
    (state) => state.selectFiltersAction
  )
  const counts = ArtworksFiltersStore.useStoreState((state) => state.counts)
  const aggregations = ArtworksFiltersStore.useStoreState((state) => state.aggregations)
  const aggregation = aggregationForFilter(paramName, aggregations)

  const options: FilterData[] | undefined =
    aggregation?.counts.map((aggCount) => {
      return {
        displayText: aggCount.name,
        paramName,
        paramValue: aggCount.value,
        count: aggCount.count,
      }
    }) ?? []

  const selectedOptions = useSelectedOptionsDisplay()
  const { handleSelect, handleClear, isActive, isSelected } = useMultiSelect({
    options,
    paramName,
  })

  const artistIFollowFilter = selectedOptions.find(isArtistsIFollowFilter)
  const isSelectedArtistIFollowFilter = !!artistIFollowFilter?.paramValue
  const displayOptions = [
    {
      displayText: "Artists You Follow",
      paramName: FilterParamName.artistsIFollow,
      paramValue: isSelectedArtistIFollowFilter,
      count: counts.followedArtists,
    },
    {
      displayText: "All Artists",
      paramName,
      paramValue: !isSelectedArtistIFollowFilter && !isActive,
    },
    ...options.map((option) => ({ ...option, paramValue: isSelected(option) })),
  ]

  const selectOption = (option: FilterData, updatedValue: boolean) => {
    selectFiltersAction({
      displayText: option.displayText,
      paramValue: isArtistsIFollowFilter(option),
      paramName: FilterParamName.artistsIFollow,
    })

    if (isArtistsIFollowFilter(option) || isAllArtistsFilter(option)) {
      handleClear()
    } else {
      handleSelect(option, updatedValue)
    }
  }

  const shouldAddIndent = (option: FilterData) => {
    return !(isArtistsIFollowFilter(option) || isAllArtistsFilter(option))
  }

  return (
    <MultiSelectCheckOptionScreen
      onSelect={selectOption}
      filterHeaderText={FilterDisplayName.artistIDs}
      filterOptions={displayOptions}
      navigation={navigation}
      shouldAddIndent={shouldAddIndent}
    />
  )
}


text:
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './app/index.jsx',
	output: {
		      path: path.resolve(__dirname, 'dist'),
		      filename: 'index_bundle.js',
					publicPath: '/'
	},
	module: {
		      rules: [
			            { test: /\.(js)$/, use: 'babel-loader' },
			            { test: /\.css$/, use: [ 'style-loader', 'css-loader' ]},
									{ test: /\.(jsx)$/, use: 'babel-loader' }
			          ]
	},
	devServer:{
		historyApiFallback:true
	},
	plugins: [
    new HtmlWebpackPlugin({
      template: 'app/index.html'
    })
	]
};


text:
require 'rly'
require 'ast'
require 'parser/ast/node'

module Carbonate
  class Parser < Rly::Yacc
    def without_spaces(elements)
      elements.reject do |element|
        element.type == :S
      end
    end

    def wrap_in_begin(nodes)
      if nodes.one?
        nodes.first
      else
        s(:begin, nodes)
      end
    end

    def destructure_arguments(arguments)
      if arguments[0..-2].any? { |arg| [:pseudo_block, :block_pass].include?(arg.type) }
        raise FormatError, 'You can specify only one block per method call (as the last argument)'
      end

      if !arguments.empty? && arguments.last.type == :pseudo_block
        [arguments[0..-2], arguments.last]
      else
        [arguments, nil]
      end
    end

    def s(type, children)
      self.class.s(type, children)
    end

    class << self
      def s(type, children = [])
        ::Parser::AST::Node.new(type, children)
      end

      def identifier(value)
        value.gsub('-', '_').to_sym
      end

      def handle_string(string, range)
        replacements = {
          '\\n' => "\n",
          '\\r' => "\r",
          '\\t' => "\t",
          '\\"' => '"'
        }
        string[range].gsub(/\\[nrt"]/, replacements)
      end
    end

    lexer do
      literals '+-*/%=<>&|^~!()[]{}#@.'

      token :FLOAT, /-?\d+\.\d+/ do |t|
        t.value = Parser.s(:float, [t.value.to_f])
        t
      end

      token :INTEGER, /-?\d+/ do |t|
        t.value = Parser.s(:int, [t.value.to_i])
        t
      end

      token :SYMBOL, /:([A-Za-z0-9_-]+[!?=]?|[+\-*\/])/ do |t|
        t.value = Parser.s(:sym, [Parser.identifier(t.value[1..-1])])
        t
      end

      token :REGEXP, /#"([^"\\]|\\[nrt"])*"/ do |t|
        t.value = Parser.s(:regexp,
          [
            Parser.s(:str, [Parser.handle_string(t.value, 2..-2)]),
            Parser.s(:regopt)
          ]
        )
        t
      end

      token :STRING, /"([^"\\]|\\[nrt"])*"/ do |t|
        t.value = Parser.s(:str, [Parser.handle_string(t.value, 1..-2)])
        t
      end

      token :TRUE, /true/ do |t|
        t.value = Parser.s(:true)
        t
      end

      token :FALSE, /false/ do |t|
        t.value = Parser.s(:false)
        t
      end

      # nil (without special characters at the end)
      token :NIL, /nil(?![!?=])/

      # characters treated as whitespace
      token :S, /[\s,]+/ do |t|
        t.lexer.lineno += t.value.count("\n")
        t
      end

      # keywords
      token :DEFCLASS,  /defclass/
      token :DEFMODULE, /defmodule/
      token :DEFMETHOD, /defmethod/
      token :DEF_OR,    /def-or/
      token :DEF,       /def/
      token :RETURN,    /return/
      token :SUPER,     /super/
      token :ZSUPER,    /zsuper/
      token :TRY,       /try/
      token :RESCUE,    /rescue/
      token :ENSURE,    /ensure/

      token :DO,     /do/
      token :IF,     /if/
      token :UNLESS, /unless/
      token :CASE,   /case/
      token :WHILE,  /while/
      token :UNTIL,  /until/
      token :AND,    /and/
      token :OR,     /or/

      token :CONST, /\.?([A-Z][A-Za-z0-9_-]+\.)*[A-Z][A-Za-z0-9_-]+/ do |t|
        parts = t.value.split('.').reject(&:empty?)
        top_namespace = Parser.s(:cbase) if t.value.start_with?('.')

        t.value = parts.inject(top_namespace) do |namespace, part|
          Parser.s(:const, [namespace, Parser.identifier(part)])
        end
        t
      end

      # method name with '!', '?' or '=' at the end
      token :METHOD_NAME, /[a-z][A-Za-z0-9_-]*[!?=]/ do |t|
        t.value = Parser.identifier(t.value)
        t
      end

      # local variable or method name without special chars at the end
      token :LVAR, /[a-z][A-Za-z0-9_-]*/ do |t|
        t.value = Parser.identifier(t.value)
        t
      end

      # method name with '!', '?' or '=' at the end, called without an explicit receiver
      token :SELF_METHOD_NAME, /@[a-z][A-Za-z0-9_-]*[!?=]/ do |t|
        t.value = Parser.identifier(t.value)
        t
      end

      # instance variable or method name without special chars, called without an explicit receiver
      token :IVAR, /@[a-z][A-Za-z0-9_-]*/ do |t|
        t.value = Parser.identifier(t.value)
        t
      end

      on_error do |t|
        fail FormatError, "Unknown character '#{t.value}' at line #{t.lexer.lineno.succ}"
      end
    end

    # outermost scope
    rule 'source : forms S | forms' do |source, forms|
      source.value = wrap_in_begin(forms.value)
    end

    # multiple forms
    rule 'forms : forms S form | form' do |forms, *forms_array|
      forms.value = without_spaces(forms_array).flat_map(&:value)
    end

    # form can be a local variable
    #   user
    rule 'form : LVAR' do |form, lvar|
      form.value = s(:lvar, [lvar.value])
    end

    # form can be an instance variable
    #   @user
    rule 'form : IVAR' do |form, ivar|
      form.value = s(:ivar, [ivar.value])
    end

    # form can also be an S-expression, a literal value, a constant, self or a collection of forms
    rule 'form : INTEGER
               | FLOAT
               | STRING
               | SYMBOL
               | REGEXP
               | TRUE
               | FALSE
               | nil
               | array
               | hash
               | set
               | irange
               | erange
               | CONST
               | self
               | sexp' do |form, element|
      form.value = element.value
    end

    # array
    #   [1 2 3]
    rule 'array : "[" forms "]"' do |array, _, sexps, _|
      array.value = s(:array, sexps.value)
    end

    # empty array
    #   []
    rule 'array : "[" "]"' do |array, _, _|
      array.value = s(:array, [])
    end

    # hash
    #   {:first-name "Rich", :last-name "Hickey"}
    # commas are optional, elements count must be even
    rule 'hash : "{" forms "}"' do |hash, _, forms, _|
      raise FormatError.new('Odd number of elements in a hash') if forms.value.count.odd?

      pairs = forms.value.each_slice(2).map { |pair| s(:pair, pair) }
      hash.value = s(:hash, pairs)
    end

    # empty hash
    #   {}
    rule 'hash : "{" "}"' do |hash, _, _|
      hash.value = s(:hash, [])
    end

    # set
    #   #{123 "string" :symbol}
    rule 'set : "#" "{" forms "}"' do |set, _, _, forms, _|
      set.value = s(:send,
        [
          s(:const, [nil, :Set]),
          :new,
          s(:array, forms.value)
        ]
      )
    end

    # inclusive range
    #   1..10
    rule 'irange : form "." "." form' do |range, first, _, _, last|
      range.value = s(:irange, [first.value, last.value])
    end

    # exclusive range
    #   1...11
    rule 'erange : form "." "." "." form' do |range, first, _, _, _, last|
      range.value = s(:erange, [first.value, last.value])
    end

    # self
    #   @
    rule 'self : "@"' do |self_node, _|
      self_node.value = s(:self, [])
    end

    # nil
    #   nil
    rule 'nil : NIL' do |nil_node, _|
      nil_node.value = s(:nil, [])
    end

    # multiple S-expressions
    rule 'sexps : sexps S sexp | sexp' do |sexps, *sexps_array|
      sexps.value = without_spaces(sexps_array).flat_map(&:value)
    end

    # do statement - combines several forms into one
    # so you can fit several statements in a place for just one
    rule 'sexp : "(" DO S forms ")"' do |sexp, _, _, _, forms, _|
      sexp.value = s(:begin, forms.value)
    end

    # if statement
    # can have only "then" clause:
    #   (if (valid? user) (save user))
    # or both "then" and "else" clauses:
    #   (if (> a b) a b)
    rule 'sexp : "(" IF S form S form ")"
               | "(" IF S form S form S form ")"' do |sexp, _, _, _, condition, _, then_clause, _, else_clause, _|
      sexp.value = s(:if, [condition.value, then_clause.value, else_clause && else_clause.value])
    end

    # unless statement
    #   (unless (persisted? user) (save user))
    rule 'sexp : "(" UNLESS S form S form ")"' do |sexp, _, _, _, condition, _, then_clause, _|
      sexp.value = s(:if, [condition.value, nil, then_clause.value])
    end

    # case statement
    #   (case x
    #     1 "one"
    #     2 "two")
    # can have an "else" clause at the end:
    #   (case lang
    #     "clojure" "great!"
    #     "ruby" "cool"
    #     "crap")
    rule 'sexp : "(" CASE S form S forms ")"' do |sexp, _, _, _, form, _, forms, _|
      elements = if forms.value.count.even?
        [*forms.value, nil]
      else
        forms.value
      end

      when_clauses = elements[0..-2].each_slice(2).map do |value, expr|
        s(:when, [value, expr])
      end

      sexp.value = s(:case, [form.value, *when_clauses, elements.last])
    end

    # while loop
    #   (while (< x 5) (def x (+ x 1)))
    rule 'sexp : "(" WHILE S form S form ")"' do |sexp, _, _, _, condition, _, body, _|
      sexp.value = s(:while, [condition.value, body.value])
    end

    # until loop
    #   (until (>= x 5) (def x (+ x 1)))
    rule 'sexp : "(" UNTIL S form S form ")"' do |sexp, _, _, _, condition, _, body, _|
      sexp.value = s(:until, [condition.value, body.value])
    end

    # instance method call with an explicit receiver
    #   (+ 2 2)
    rule 'sexp : "(" func S form ")"
               | "(" func S form S arguments_list ")"' do |sexp, _, func, _, receiver, _, arguments_list, _|
      arguments, block = destructure_arguments(arguments_list && arguments_list.value || [])
      send_node = s(:send, [receiver.value, func.value, *arguments])

      sexp.value = if block.nil?
        send_node
      else
        s(:block, [send_node, *block.children])
      end
    end

    # class method call with an explicit receiver
    #   (User/find-by {:first-name "John"})
    rule 'sexp : "(" CONST "/" func ")"
               | "(" CONST "/" func S arguments_list ")"' do |sexp, _, const, _, func, _, arguments_list, _|
      arguments, block = destructure_arguments(arguments_list && arguments_list.value || [])
      send_node = s(:send, [const.value, func.value, *arguments])

      sexp.value = if block.nil?
        send_node
      else
        s(:block, [send_node, *block.children])
      end
    end

    # method call with an implicit receiver
    #   (@attr-reader :first-name)
    rule 'sexp : "(" IVAR ")"
               | "(" IVAR S arguments_list ")"
               | "(" SELF_METHOD_NAME ")"
               | "(" SELF_METHOD_NAME S arguments_list ")"' do |sexp, _, method_name, _, arguments_list, _|
      arguments, block = destructure_arguments(arguments_list && arguments_list.value || [])
      send_node = s(:send, [nil, method_name.value[1..-1].to_sym, *arguments])

      sexp.value = if block.nil?
        send_node
      else
        s(:block, [send_node, *block.children])
      end
    end

    # class constructor call
    #   (User. {:name "John"})
    rule 'sexp : "(" CONST "." ")"
               | "(" CONST "." S arguments_list ")"' do |sexp, _, const, _, _, arguments_list, _|
      arguments, block = destructure_arguments(arguments_list && arguments_list.value || [])
      send_node = s(:send, [const.value, :new, *arguments])

      sexp.value = if block.nil?
        send_node
      else
        s(:block, [send_node, *block.children])
      end
    end

    # call to super with explicit parameters
    #   (super)
    #   (super "argument")
    rule 'sexp : "(" SUPER ")"
               | "(" SUPER S arguments_list ")"' do |sexp, _, _, _, arguments_list, _|
      arguments, block = destructure_arguments(arguments_list && arguments_list.value || [])
      send_node = s(:super, arguments)

      sexp.value = if block.nil?
        send_node
      else
        s(:block, [send_node, *block.children])
      end
    end

    # call to super with implicit parameters
    #   (zsuper)
    rule 'sexp : "(" ZSUPER ")"
               | "(" ZSUPER S arguments_list ")"' do |sexp, _, _, _, arguments_list, _|
      arguments, block = destructure_arguments(arguments_list && arguments_list.value || [])
      send_node = s(:zsuper, [])

      sexp.value = if block.nil?
        send_node
      else
        s(:block, [send_node, *block.children])
      end
    end

    # multiple arguments (in method invocation)
    rule 'arguments_list : arguments_list S argument | argument | empty' do |arguments_list, *arguments|
      arguments_list.value = without_spaces(arguments).flat_map(&:value)
    end

    # an argument can be a simple form
    rule 'argument : form' do |argument, form|
      argument.value = form.value
    end

    # an argument can be splat
    rule 'argument : "&" S form' do |argument, _, _, form|
      argument.value = s(:splat, [form.value])
    end

    # the last argument can be passed as a block
    rule 'argument : "#" S form' do |argument, _, _, form|
      argument.value = s(:block_pass, [form.value])
    end

    # the last argument can be an inline block
    rule 'argument : "#" "(" parameters_list S forms ")"' do |argument, _, _, params, _, forms, _|
      block_body = wrap_in_begin(forms.value)
      argument.value = s(:pseudo_block, [params.value, block_body])
    end

    # the last argument can also be an inline block without parameters
    rule 'argument : "#" form
                   | "#" "(" forms ")"' do |argument, _, *forms_array|
      body = forms_array.reject do |element|
        ['(', ')'].include?(element.type)
      end.flat_map(&:value)

      argument.value = s(:pseudo_block, [s(:args, []), wrap_in_begin(body)])
    end

    # return statement without parameters
    #   (return)
    rule 'sexp : "(" RETURN ")"' do |sexp, _, _, _|
      sexp.value = s(:return, [])
    end

    # return statement with parameters
    #   (return 1)
    rule 'sexp : "(" RETURN S forms ")"' do |sexp, _, _, _, forms, _|
      sexp.value = s(:return, forms.value)
    end

    # try statement with a rescue clause
    #   (try (File/read path)
    #        (rescue Errno.ENOENT e
    #                (@puts (message e))))
    rule 'sexp : "(" TRY S forms S rescues ")"' do |sexp, _, _, _, forms, _, rescue_clauses, _|
      sexp.value = s(:kwbegin, [s(:rescue, [wrap_in_begin(forms.value), *rescue_clauses.value, nil])])
    end

    # try statement with an ensure clause
    #   (try (File/read path)
    #        (ensure (@puts "Tries to read a file.")))
    rule 'sexp : "(" TRY S forms S ensure ")"' do |sexp, _, _, _, forms, _, ensure_clause|
      sexp.value = s(:kwbegin, [s(:ensure, [wrap_in_begin(forms.value), ensure_clause.value.children.first])])
    end

    # try statement with rescue and ensure clauses
    #   (try (File/read path)
    #        (rescue Errno.ENOENT e (@puts (message e)))
    #        (ensure (@puts "Tried to read a file.")))
    rule 'sexp : "(" TRY S forms S rescues S ensure ")"' do |sexp, _, _, _, forms, _, rescue_clauses, _, ensure_clause, _|
      rescue_subexpression = s(:rescue, [wrap_in_begin(forms.value), *rescue_clauses.value, nil])
      sexp.value = s(:kwbegin, [s(:ensure, [rescue_subexpression, ensure_clause.value.children.first])])
    end

    # multiple rescue clauses
    rule 'rescues : rescues S rescue | rescue' do |rescues, *rescues_array|
      rescues.value = without_spaces(rescues_array).flat_map(&:value)
    end

    # rescue clause
    rule 'rescue : "(" RESCUE S CONST S LVAR S forms ")"' do |rescue_clause, _, _, _, const, _, lvar, _, forms, _|
      rescue_clause.value = s(:resbody,
        [
          s(:array, [const.value]),
          s(:lvasgn, [lvar.value]),
          wrap_in_begin(forms.value)
        ]
      )
    end

    # ensure clause
    rule 'ensure : "(" ENSURE S forms ")"' do |ensure_clause, _, _, _, forms, _|
      ensure_clause.value = s(:pseudo_ensure, [wrap_in_begin(forms.value)])
    end

    # class definition w/o a parent class
    #   (defclass User (class body))
    rule 'sexp : "(" DEFCLASS S CONST S forms ")"' do |sexp, _, _, _, const, _, forms, _|
      class_body = wrap_in_begin(forms.value)
      sexp.value = s(:class, [const.value, nil, class_body])
    end

    # class definition with a parent class
    #   (defclass User < Base (class body))
    rule 'sexp : "(" DEFCLASS S CONST S "<" S form S forms ")"' do |sexp, _, _, _, const, _, _, _, form, _, forms|
      class_body = wrap_in_begin(forms.value)
      sexp.value = s(:class, [const.value, form.value, class_body])
    end

    # module definition
    #   (defmodule Enumerable (module body ...))
    rule 'sexp : "(" DEFMODULE S CONST S forms ")"' do |sexp, _, _, _, const, _, forms, _|
      module_body = wrap_in_begin(forms.value)
      sexp.value = s(:module, [const.value, module_body])
    end

    # singleton class definition
    #   (<<- user (defmethod name [] @name)
    rule 'sexp : "(" "<" "<" "-" S form S forms ")"' do |sexp, _, _, _, _, _, form, _, forms, _|
      singleton_body = wrap_in_begin(forms.value)
      sexp.value = s(:sclass, [form.value, singleton_body])
    end

    # method defition
    #   (defmethod full-name [] (join [first-name last-name]))
    #   (defmethod read-file [path]
    #     (File/read path)
    #     (rescue Errno.ENOENT e (@puts "No file found."))
    #     (ensure (@puts "Tried to read a file.")))
    rule 'sexp : "(" DEFMETHOD S LVAR S parameters_list S method_body ")"
               | "(" DEFMETHOD S METHOD_NAME S parameters_list S method_body ")"' do |sexp, _, _, _, method_name, _, params, _, method_body, _|
      sexp.value = s(:def, [method_name.value.to_sym, params.value, method_body.value])
    end

    # method body consisting of forms
    rule 'method_body : forms' do |method_body, forms|
      method_body.value = wrap_in_begin(forms.value)
    end

    # method body consisting of forms and rescue clauses
    rule 'method_body : forms S rescues' do |method_body, forms, _, rescue_clauses|
      method_body.value = s(:rescue, [wrap_in_begin(forms.value), *rescue_clauses.value, nil])
    end

    # method body consisting of forms and an ensure clause
    rule 'method_body : forms S ensure' do |method_body, forms, _, ensure_clause|
      method_body.value = s(:ensure, [wrap_in_begin(forms.value), ensure_clause.value.children.first])
    end

    # method body consisting of forms and rescue and ensure clauses
    rule 'method_body : forms S rescues S ensure' do |method_body, forms, _, rescue_clauses, _, ensure_clause|
      rescue_subexpression = s(:rescue, [wrap_in_begin(forms.value), *rescue_clauses.value, nil])
      method_body.value = s(:ensure, [rescue_subexpression, ensure_clause.value.children.first])
    end

    # lambda definition
    #   (-> [user] (email user))
    rule 'sexp : "(" "-" ">" S parameters_list S forms ")"' do |sexp, _, _, _, _, params, _, forms, _|
      lambda_body = wrap_in_begin(forms.value)
      sexp.value = s(:block, [s(:send, [nil, :lambda]), params.value, lambda_body])
    end

    # lambda definition without parameters
    #   (-> (@puts "Hello world!"))
    rule 'sexp : "(" "-" ">" S forms ")"' do |sexp, _, _, _, _, forms, _|
      lambda_body = wrap_in_begin(forms.value)
      sexp.value = s(:block, [s(:send, [nil, :lambda]), s(:args, []), lambda_body])
    end

    # local variable assignment
    #   (def username "7even")
    rule 'sexp : "(" DEF S LVAR S form ")"' do |sexp, _, _, _, var_name, _, form, _|
      sexp.value = s(:lvasgn, [var_name.value, form.value])
    end

    # conditional local variable assignment
    #   (def-or username "7even")
    rule 'sexp : "(" DEF_OR S LVAR S form ")"' do |sexp, _, _, _, var_name, _, form, _|
      sexp.value = s(:or_asgn, [s(:lvasgn, [var_name.value]), form.value])
    end

    # instance variable assignment
    #   (def @age 30)
    rule 'sexp : "(" DEF S IVAR S form ")"' do |sexp, _, _, _, var_name, _, form, _|
      sexp.value = s(:ivasgn, [var_name.value, form.value])
    end

    # conditional instance variable assignment
    #   (def-or @age 30)
    rule 'sexp : "(" DEF_OR S IVAR S form ")"' do |sexp, _, _, _, var_name, _, form, _|
      sexp.value = s(:or_asgn, [s(:ivasgn, [var_name.value]), form.value])
    end

    # object attribute assignment
    #   (def user.name "John")
    rule 'sexp : "(" DEF S form "." LVAR S form ")"' do |sexp, _, _, _, object, _, lvar, _, form, _|
      method_name = "#{lvar}=".to_sym
      sexp.value = s(:send, [object.value, method_name, form.value])
    end

    # conditional object attribute assignment
    #   (def-or user.name "John")
    rule 'sexp : "(" DEF_OR S form "." LVAR S form ")"' do |sexp, _, _, _, object, _, lvar, _, form, _|
      sexp.value = s(:or_asgn, [s(:send, [object.value, lvar.value]), form.value])
    end

    # constant assignment
    #   (def DAYS-IN-WEEK 7)
    rule 'sexp : "(" DEF S CONST S form ")"' do |sexp, _, _, _, const, _, form, _|
      sexp.value = s(:casgn, [*const.value.children, form.value])
    end

    # method parameters list (in method definition)
    #   [a b c]
    rule 'parameters_list : "[" parameters "]"' do |parameters_list, _, parameters, _|
      parameters_list.value = s(:args, parameters.value)
    end

    # method parameters list with a block parameter at the end
    #   [a b c # d]
    rule 'parameters_list : "[" parameters S block_parameter "]"' do |parameters_list, _, args, _, block_parameter, _|
      parameters_list.value = s(:args, [*args.value, block_parameter.value])
    end

    # method parameters list consisting of one block parameter
    #   [# parameters]
    rule 'parameters_list : "[" block_parameter "]"' do |parameters_list, _, block_parameter, _|
      parameters_list.value = s(:args, [block_parameter.value])
    end

    # multiple parameters
    rule 'parameters : parameters S parameter | parameter | empty' do |parameters, *parameters_array|
      parameters.value = without_spaces(parameters_array).flat_map(&:value)
    end

    # a parameter can be a local variable
    rule 'parameter : LVAR' do |parameter, identifier|
parameter.value = s(:arg, [identifier.value])
    end

    # a parameter can have a default value
    #   [base 10]
    rule 'parameter : "[" LVAR S form "]"' do |parameter, _, identifier, _, default_value, _|
      parameter.value = s(:optarg, [identifier.value, default_value.value])
    end

    # a parameter can be a splat
    rule 'parameter : "&" S LVAR' do |parameter, _, _, identifier|
      parameter.value = s(:restarg, [identifier.value])
    end

    # the last parameter can be a block
    rule 'block_parameter : "#" S LVAR' do |block_parameter, _, _, identifier|
      block_parameter.value = s(:blockarg, [identifier.value])
    end

    # empty rule
    rule('empty :') do |empty|
      empty.value = []
    end

    # method name (may be operator)
    rule 'func : operator | METHOD_NAME | LVAR' do |func, function|
      func.value = function.value
    end

    # operator
    rule 'operator : "+" | "-" | "*" | "/" | "%" | "*" "*"
                   | "=" | "!" "=" | "<" | ">" | "<" "=" | ">" "=" | "<" "=" ">" | "=" "=" "="
                   | "&" | "|" | "^" | "~" | "<" "<" | ">" ">" | "!"' do |operator, *operator_chars|
      operator_name = operator_chars.map(&:value).join

      operator.value = if operator_name == '='
        :==
      else
        operator_name.to_sym
      end
    end

    # logical 'and' & 'or'
    #   (and a b)
    #   (or a b)
    rule 'sexp : "(" AND S forms ")"
               | "(" OR S forms ")"' do |sexp, _, operator, _, forms, _|
      sexp.value = s(operator.value, forms.value)
    end

    # collection member reader
    #   hash[:key]
    #   array[1, 5]
    rule 'sexp : form "[" forms "]"' do |sexp, collection, _, arguments, _|
      sexp.value = s(:send, [collection.value, :[], *arguments.value])
    end

    # collection member writer
    #   (def hash[:key] value)
    #   (def array[1 2] 3)
    rule 'sexp : "(" DEF S form "[" forms "]" S form ")"' do |sexp, _, _, _, collection, _, arguments, _, _, value, _|
      sexp.value = s(:send, [collection.value, :[]=, *arguments.value, value.value])
    end

    # conditional collection member writer
    #   (def-or hash[:key] value)
    rule 'sexp : "(" DEF_OR S form "[" forms "]" S form ")"' do |sexp, _, _, _, collection, _, arguments, _, _, value, _|
      sexp.value = s(:or_asgn, [s(:send, [collection.value, :[], *arguments.value]), value.value])
    end

    on_error -> (token) do
      if token.nil?
        fail FormatError, 'Input ends unexpectedly'
      else
        token_string = if token.value.respond_to?(:children)
          token.value.children.first
        else
          token.value
        end

        message = "Unexpected token '#{token_string}'"
        message << " at line #{token.location_info[:lineno].succ}"

        fail FormatError, message
      end
    end

    class FormatError < RuntimeError; end
  end
end


text:
namespace content {

TestWebContentsView::TestWebContentsView() {
}

TestWebContentsView::~TestWebContentsView() {
}

void TestWebContentsView::ShowPopupMenu(const gfx::Rect& bounds,
                                        int item_height,
                                        double item_font_size,
                                        int selected_item,
                                        const std::vector<WebMenuItem>& items,
                                        bool right_aligned,
                                        bool allow_multiple_selection) {
}

void TestWebContentsView::StartDragging(
    const WebDropData& drop_data,
    WebKit::WebDragOperationsMask allowed_ops,
    const gfx::ImageSkia& image,
    const gfx::Vector2d& image_offset,
    const DragEventSourceInfo& event_info) {
}

void TestWebContentsView::UpdateDragCursor(WebKit::WebDragOperation operation) {
}

void TestWebContentsView::GotFocus() {
}

void TestWebContentsView::TakeFocus(bool reverse) {
}

gfx::NativeView TestWebContentsView::GetNativeView() const {
  return gfx::NativeView();
}

gfx::NativeView TestWebContentsView::GetContentNativeView() const {
  return gfx::NativeView();
}

gfx::NativeWindow TestWebContentsView::GetTopLevelNativeWindow() const {
  return gfx::NativeWindow();
}

void TestWebContentsView::GetContainerBounds(gfx::Rect *out) const {
}

void TestWebContentsView::OnTabCrashed(base::TerminationStatus status,
                                       int error_code) {
}

void TestWebContentsView::SizeContents(const gfx::Size& size) {
}

void TestWebContentsView::Focus() {
}

void TestWebContentsView::SetInitialFocus() {
}

void TestWebContentsView::StoreFocus() {
}

void TestWebContentsView::RestoreFocus() {
}

WebDropData* TestWebContentsView::GetDropData() const {
  return NULL;
}

gfx::Rect TestWebContentsView::GetViewBounds() const {
  return gfx::Rect();
}

#if defined(OS_MACOSX)
void TestWebContentsView::SetAllowOverlappingViews(bool overlapping) {
}

bool TestWebContentsView::GetAllowOverlappingViews() const {
  return false;
}
#endif

void TestWebContentsView::CreateView(const gfx::Size& initial_size,
                                     gfx::NativeView context) {
}

RenderWidgetHostView* TestWebContentsView::CreateViewForWidget(
    RenderWidgetHost* render_widget_host) {
  return NULL;
}

RenderWidgetHostView* TestWebContentsView::CreateViewForPopupWidget(
    RenderWidgetHost* render_widget_host) {
  return NULL;
}

void TestWebContentsView::SetPageTitle(const string16& title) {
}

void TestWebContentsView::RenderViewCreated(RenderViewHost* host) {
}

void TestWebContentsView::RenderViewSwappedIn(RenderViewHost* host) {
}

void TestWebContentsView::SetOverscrollControllerEnabled(bool enabled) {
}

#if defined(OS_MACOSX)
bool TestWebContentsView::IsEventTracking() const {
  return false;
}

void TestWebContentsView::CloseTabAfterEventTracking() {
}
#endif

}  // namespace content


text:
var command = require("models/command.js");
var commandType = command.prototype.commandType;

function result(type, file, args){
	this.type = type;
	this.args = args;
	this.file = file;
	if(type==commandType.Run){
		this.expect = "";
		this.predict = "";
	}else{
		this.expect = [];
		this.predict = [];
	}
};

module.exports = result;


text:
run ios
==========

Usage | Synopsis
---|---
Run on all connected devices | `$ tns run ios [--release] [--justlaunch]`
Run on a selected connected device | `$ tns run ios [--device <Device ID>] [--release] [--justlaunch]`
Start an emulator and run the app inside it | `$ tns run ios --emulator [<Emulator Options>] [--release]`

Runs your project on a connected iOS device or in the iOS Simulator, if configured. This is shorthand for prepare, build, and deploy. While your app is running, prints the output from the application in the console.

<% if(isConsole && (isWindows || isLinux)) { %>WARNING: You can run this command only on OS X systems. To view the complete help for this command, run `$ tns help run ios`<% } %>
<% if((isConsole && isMacOS) || isHtml) { %>
<% if(isHtml) { %>> <% } %>IMPORTANT: Before building for iOS device, verify that you have configured a valid pair of certificate and provisioning profile on your OS X system. <% if(isHtml) { %>For more information, see [Obtaining Signing Identities and Downloading Provisioning Profiles](https://developer.apple.com/library/mac/recipes/xcode_help-accounts_preferences/articles/obtain_certificates_and_provisioning_profiles.html).<% } %>

### Options
* `--device` - Specifies a connected device on which to run the app.
* `--emulator` - If set, runs the app in a native emulator for the target platform, if configured. When set, you can also set any other valid combination of emulator options as listed by `$ tns help emulate ios`. You cannot use `--device` and `--emulator` simultaneously.
* `--release` - If set, produces a release build. Otherwise, produces a debug build.
* `--justlaunch` - If set, does not print the application output in the console.

### Attributes
* `<Device ID>` is the index or name of the target device as listed by `$ tns device ios`
* `<Emulator Options>` is any valid combination of options as listed by `$ tns help emulate ios`
<% } %>
<% if(isHtml) { %>
### Prerequisites
Before running the iOS Simulator, verify that you have met the following requirements.
* You have installed Xcode. The version of Xcode must be compatible with the ios-sim-portable npm package on which the  NativeScript CLI depends. For more information, visit [https://www.npmjs.org/package/ios-sim-portable](https://www.npmjs.org/package/ios-sim-portable).

### Command Limitations

* You can run `$ tns run ios` only on OS X systems.
* You cannot use `--device` and `--emulator` simultaneously.

### Related Commands

Command | Description
----------|----------
[build android](build-android.html) | Builds the project for Android and produces an APK that you can manually deploy on device or in the native emulator.
[build ios](build-ios.html) | Builds the project for iOS and produces an APP or IPA that you can manually deploy in the iOS Simulator or on device, respectively.
[build](build.html) | Builds the project for the selected target platform and produces an application package that you can manually deploy on device or in the native emulator.
[debug android](debug-android.html) | Debugs your project on a connected Android device or in a native emulator.
[debug ios](debug-ios.html) | Debugs your project on a connected iOS device or in a native emulator.
[debug](debug.html) | Debugs your project on a connected device or in a native emulator.
[deploy](deploy.html) | Builds and deploys the project to a connected physical or virtual device.
[emulate android](emulate-android.html) | Builds the specified project and runs it in a native Android emulator.
[emulate ios](emulate-ios.html) | Builds the specified project and runs it in the native iOS Simulator.
[emulate](emulate.html) | You must run the emulate command with a related command.
[livesync](livesync.html) | Synchronizes the latest changes in your project to devices.
[livesync ios](livesync-ios.html) | Synchronizes the latest changes in your project to iOS devices.
[livesync android](livesync-android.html) | Synchronizes the latest changes in your project to Android devices.
[run android](run-android.html) | Runs your project on a connected Android device or in a native Android emulator, if configured.
[run](run.html) | Runs your project on a connected device or in the native emulator for the selected platform.
<% } %>


text:
'use strict';

const { expect } = require('chai');
const { ConfigBuilder } = require('../../../lib/config/ConfigBuilder');
const { FlakeIdGeneratorConfigImpl } = require('../../../lib/config/FlakeIdGeneratorConfig');
const { ConfigurationError } = require('../../../');

describe('ConfigPatternMatcherTest', function () {
    const inputConfig = {
        flakeIdGenerators: {}
    };
    const f1 = {
        prefetchValidityMillis: 111,
        prefetchCount: 44
    };
    const f2 = {
        prefetchValidityMillis: 1176451,
        prefetchCount: 534
    };
    const f3 = {
        prefetchValidityMillis: 114,
        prefetchCount: 14
    };
    const f4 = {
        prefetchValidityMillis: 42,
        prefetchCount: 4
    };

    beforeEach(function () {
        inputConfig.flakeIdGenerators['pref*'] = f2;
        inputConfig.flakeIdGenerators['*postf'] = f3;
        inputConfig.flakeIdGenerators['pref*postf'] = f4;
    });

    function assertConfig(actual, expected, name) {
        for (const prop in actual) {
            if (typeof actual[prop] !== 'function') {
                if (prop === 'name') {
                    expect(actual[prop]).to.be.equal(name);
                } else {
                    expect(actual[prop]).to.be.equal(expected[prop]);
                }
            }
        }
    }

    it('lookupByPattern', function () {
        const config = new ConfigBuilder(inputConfig).build();

        assertConfig(config.getFlakeIdGeneratorConfig('pref123postf'), f4, 'pref123postf');
        assertConfig(config.getFlakeIdGeneratorConfig('123postf'), f3, '123postf');
        assertConfig(config.getFlakeIdGeneratorConfig('pref123'), f2, 'pref123');
        assertConfig(config.getFlakeIdGeneratorConfig('unconfigured'), new FlakeIdGeneratorConfigImpl(), 'unconfigured');
    });

    it('lookupByPattern with explicit default', function () {
        inputConfig.flakeIdGenerators['default'] = f1;
        const config = new ConfigBuilder(inputConfig).build();

        assertConfig(config.getFlakeIdGeneratorConfig('pref123postf'), f4, 'pref123postf');
        assertConfig(config.getFlakeIdGeneratorConfig('123postf'), f3, '123postf');
        assertConfig(config.getFlakeIdGeneratorConfig('pref123'), f2, 'pref123');
        assertConfig(config.getFlakeIdGeneratorConfig('unconfigured'), f1, 'unconfigured');
    });

    it('duplicate pattern throws', function () {
        inputConfig.flakeIdGenerators['abcde*'] = f2;
        const config = new ConfigBuilder(inputConfig).build();

        expect(config.getFlakeIdGeneratorConfig.bind(inputConfig, 'abcde.somemore.postf')).to.throw(ConfigurationError);
    });
});


text:
.. os-win documentation master file, created by
   sphinx-quickstart on Tue Jul  9 22:26:36 2015.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to os-win's documentation!
==================================

Contents:

.. toctree::
   :maxdepth: 2

   readme
   installation
   usage
   contributing

Sample Configuration File
-------------------------

.. toctree::
   :maxdepth: 1

   sample_config


text:
package com.orm.record;

import com.orm.app.ClientApp;
import com.orm.dsl.BuildConfig;
import com.orm.model.RelationshipMixedBModel;
import com.orm.model.SimpleExtendedModel;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricGradleTestRunner;
import org.robolectric.annotation.Config;

import java.util.List;

import static com.orm.SugarRecord.save;
import static com.orm.SugarRecord.count;
import static com.orm.SugarRecord.listAll;

import static org.junit.Assert.assertEquals;

@RunWith(RobolectricGradleTestRunner.class)
@Config(sdk = 18, constants = BuildConfig.class, application = ClientApp.class, packageName = "com.orm.model", manifest = Config.NONE)
public class RelationshipMixedBTests {

    @Test
    public void emptyDatabaseTest() throws Exception {
        assertEquals(0L, count(RelationshipMixedBModel.class));
        assertEquals(0L, count(SimpleExtendedModel.class));
    }

    @Test
    public void oneSaveTest() throws Exception {
        SimpleExtendedModel simple = new SimpleExtendedModel();

        save(simple);
        save(new RelationshipMixedBModel(simple));

        assertEquals(1L, count(SimpleExtendedModel.class));
        assertEquals(1L, count(RelationshipMixedBModel.class));
    }

    @Test
    public void twoSameSaveTest() throws Exception {
        SimpleExtendedModel simple = new SimpleExtendedModel();

        save(simple);
        save(new RelationshipMixedBModel(simple));
        save(new RelationshipMixedBModel(simple));

        assertEquals(1L, count(SimpleExtendedModel.class));
        assertEquals(2L, count(RelationshipMixedBModel.class));
    }

    @Test
    public void twoDifferentSaveTest() throws Exception {
        SimpleExtendedModel simple = new SimpleExtendedModel();
        save(simple);
        SimpleExtendedModel anotherSimple = new SimpleExtendedModel();

        save(anotherSimple);
        save(new RelationshipMixedBModel(simple));
        save(new RelationshipMixedBModel(anotherSimple));

        assertEquals(2L, count(SimpleExtendedModel.class));
        assertEquals(2L, count(RelationshipMixedBModel.class));
    }

    @Test
    public void manySameSaveTest() throws Exception {
        SimpleExtendedModel simple = new SimpleExtendedModel();
        save(simple);

        for (int i = 1; i <= 100; i++) {
            save(new RelationshipMixedBModel(simple));
        }

        assertEquals(1L, count(SimpleExtendedModel.class));
        assertEquals(100L, count(RelationshipMixedBModel.class));
    }

    @Test
    public void manyDifferentSaveTest() throws Exception {
        for (int i = 1; i <= 100; i++) {
            SimpleExtendedModel simple = new SimpleExtendedModel();
            save(simple);
            save(new RelationshipMixedBModel(simple));
        }

        assertEquals(100L, count(SimpleExtendedModel.class));
        assertEquals(100L, count(RelationshipMixedBModel.class));
    }

    @Test
    public void listAllSameTest() throws Exception {
        SimpleExtendedModel simple = new SimpleExtendedModel();
        save(simple);
        for (int i = 1; i <= 100; i++) {
            save(new RelationshipMixedBModel(simple));
        }
        List<RelationshipMixedBModel> models = listAll(RelationshipMixedBModel.class);
        assertEquals(100, models.size());
        for (RelationshipMixedBModel model : models) {
            assertEquals(simple.getId(), model.getSimple().getId());
        }
    }

    @Test
    public void listAllDifferentTest() throws Exception {
        for (int i = 1; i <= 100; i++) {
            SimpleExtendedModel simple = new SimpleExtendedModel();
            save(simple);
            save(new RelationshipMixedBModel(simple));
        }
        List<RelationshipMixedBModel> models = listAll(RelationshipMixedBModel.class);
        assertEquals(100, models.size());
        for (RelationshipMixedBModel model : models) {
            assertEquals(model.getId(), model.getSimple().getId());
        }
    }
}


text:
using System;
using System.Linq;
using System.Linq.Expressions;
using E = System.Linq.Expressions.Expression;
using System.Reflection;
using static System.Linq.Expressions.Expression;
using static Lenses.Assets;
using static Lenses.Debug;

namespace Lenses
{
    public static class ExpressionHelpers
    {
        public static UnaryExpression Copy<T>(Expression obj) =>
            Convert<T>(obj.CallInstance(copyMethod));

        public static UnaryExpression Convert<T>(Expression obj) =>
            E.Convert(obj, typeof(T));

        public static ParameterExpression Variable<T>(string name) =>
            E.Variable(typeof(T), name);

        public static ParameterExpression Parameter<T>(string name) =>
            E.Parameter(typeof(T), name);

        public static MemberExpression PropertyOrField(Expression expression, MemberInfo memberInfo)
        {
            if (memberInfo is PropertyInfo propertyInfo)
            {
                return Property(expression, propertyInfo);
            }
            var fieldInfo = memberInfo as FieldInfo;
            if (fieldInfo != null)
            {
                return Field(expression, fieldInfo);
            }
            throw new NotSupportedException("Method Info is not supported");
        }

        internal static MethodInfo GetMethodInfo<T>(Expression<Action<T>> lambda) =>
            lambda.Body.Cast<MethodCallExpression>().Method;

        internal static MethodInfo GetMethodInfo<T>(Expression<Func<T,object>> lambda) =>
            lambda.Body.Cast<MethodCallExpression>().Method;

        public static MemberInfo GetMemberInfo<T,U>(Expression<Func<T,U>> lambda)
        {
            var lambdaBody = lambda.Body;
            return lambdaBody.Cast<MemberExpression>().Member;
        }

        internal static MethodCallExpression CallStatic(this MethodInfo staticMethod, params Expression[] arguments) =>
            E.Call(staticMethod, arguments);

        internal static MethodCallExpression CallInstance(this Expression instance, MethodInfo instanceMethod, params Expression[] arguments) =>
            E.Call(instance, instanceMethod, arguments);

        public static void Deconstruct(this BinaryExpression expr, out Expression left, out Expression right)
        {
            left = expr.Left;
            right = expr.Right;
        }

        public static void Deconstruct(this MemberExpression expr, out Expression left, out MemberInfo right)
        {
            left = expr.Expression;
            right = expr.Member;
        }
    }
}


text:
namespace Microsoft.Azure.Management.Security.Models
{
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Contains all OVF (virtual machine) full versions of the Central Manager
    /// </summary>
    public partial class PackageDownloadsCentralManagerFullOvf
    {
        /// <summary>
        /// Initializes a new instance of the
        /// PackageDownloadsCentralManagerFullOvf class.
        /// </summary>
        public PackageDownloadsCentralManagerFullOvf()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the
        /// PackageDownloadsCentralManagerFullOvf class.
        /// </summary>
        /// <param name="enterprise">The Enterprise package type</param>
        /// <param name="enterpriseHighAvailability">The
        /// EnterpriseHighAvailability package type</param>
        /// <param name="medium">The Medium package type</param>
        /// <param name="mediumHighAvailability">The MediumHighAvailability
        /// package type</param>
        public PackageDownloadsCentralManagerFullOvf(IList<PackageDownloadInfo> enterprise = default(IList<PackageDownloadInfo>), IList<PackageDownloadInfo> enterpriseHighAvailability = default(IList<PackageDownloadInfo>), IList<PackageDownloadInfo> medium = default(IList<PackageDownloadInfo>), IList<PackageDownloadInfo> mediumHighAvailability = default(IList<PackageDownloadInfo>))
        {
            Enterprise = enterprise;
            EnterpriseHighAvailability = enterpriseHighAvailability;
            Medium = medium;
            MediumHighAvailability = mediumHighAvailability;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets the Enterprise package type
        /// </summary>
        [JsonProperty(PropertyName = "enterprise")]
        public IList<PackageDownloadInfo> Enterprise { get; private set; }

        /// <summary>
        /// Gets the EnterpriseHighAvailability package type
        /// </summary>
        [JsonProperty(PropertyName = "enterpriseHighAvailability")]
        public IList<PackageDownloadInfo> EnterpriseHighAvailability { get; private set; }

        /// <summary>
        /// Gets the Medium package type
        /// </summary>
        [JsonProperty(PropertyName = "medium")]
        public IList<PackageDownloadInfo> Medium { get; private set; }

        /// <summary>
        /// Gets the MediumHighAvailability package type
        /// </summary>
        [JsonProperty(PropertyName = "mediumHighAvailability")]
        public IList<PackageDownloadInfo> MediumHighAvailability { get; private set; }

    }
}