text:
This repository contains a set of packages that primarily contain interface files (.msg and .srv) which are used both to implement client library concepts and for testing.

# rcl_interface packages
* [action_msgs](action_msgs/README.md): Messages and services for [ROS 2 actions](http://design.ros2.org/articles/actions.html)
* [builtin_interfaces](builtin_interfaces/README.md): Message definitions for types in the OMG IDL Platform Specific Model
* [composition_interfaces](composition_interfaces/README.md): Services for managing composeable nodes.
* [lifecycle_msgs](lifecycle_msgs/README.md): Message and service definitions for managing lifecycle nodes.
* [rcl_interfaces](rcl_interfaces/README.md): Message and service definitions for ROS client libraries
* [rosgraph_msgs](rosgraph_msgs/README.md): Message definitions relating the ROS Computation Graph
* test_msgs: Used exclusively for testing purposes


text:
const utils = require('./utils');
const logLog = utils.logLog;
const logError = utils.logError;
const logTime = utils.logTime;
const strValue = utils.stringValue;
const getCount = utils.getCount;
const moveAllTableRecords = utils.moveAllTableRecords;

let beehive = global.beehive;
let notYetUpdatedWithParentLocations = new Map();

function prepareLocationInsert(rows, nextId) {
    let insert = 'INSERT INTO location(location_id, name, description, address1, ' +
        'address2, city_village, state_province, postal_code, country, latitude, ' +
        'longitude, creator, date_created, county_district, address3, address6, ' +
        'address5, address4, retired, retired_by, date_retired, retire_reason, ' +
        'parent_location, uuid) VALUES ';

    let toBeinserted = '';
    rows.forEach(row => {
        if (toBeinserted.length > 1) {
            toBeinserted += ',';
        }
        let retiredBy = row['retired_by'] === null ? null : beehive.userMap.get(row['retired_by']);
        let changedBy = row['changed_by'] === null ? null : beehive.userMap.get(row['changed_by']);

        let parentLocation = beehive.locationMap.get(row['parent_location']);
        if(parentLocation === undefined) {
            parentLocation = null;
            if(row['parent_location'] !== null) {
                notYetUpdatedWithParentLocations.set(nextId, row['parent_location']);
            }
        }
        beehive.locationMap.set(row['location_id'], nextId);

        toBeinserted += `(${nextId}, ${strValue(row['name'])}, ` +
            `${strValue(row['description'])}, ${strValue(row['address1'])}, ` +
            `${strValue(row['address2'])}, ${strValue(row['city_village'])}, ` +
            `${strValue(row['state_province'])}, ${strValue(row['postal_code'])}, ` +
            `${strValue(row['country'])}, ${strValue(row['latitude'])}, ` +
            `${strValue(row['longitude'])}, ${beehive.userMap.get(row['creator'])}, ` +
            `${strValue(utils.formatDate(row['date_created']))}, ` +
            `${strValue(row['county_district'])}, ${strValue(row['address3'])}, ` +
            `${strValue(row['address6'])}, ${strValue(row['address5'])}, ` +
            `${strValue(row['address4'])}, ${row['retired']}, ${retiredBy}, ` +
            `${strValue(utils.formatDate(row['date_retired']))}, ` +
            `${strValue(row['retire_reason'])}, ${parentLocation}, ` +
            `${utils.uuid(row['uuid'])})`;

        nextId++;
    });

    let insertStatement = insert + toBeinserted;
    return [insertStatement, nextId];
}

async function updateParentForLocations(connection, idMap) {
    if(idMap.size > 0) {
        let update = 'INSERT INTO location(location_id, parent_location) VALUES ';
        let lastPart = ' ON DUPLICATE KEY UPDATE parent_location = VALUES(parent_location)';

        let values = '';
        idMap.forEach((srcParentId, locationId) => {
            if(values.length > 1) {
                values += ',';
            }
            values += `(${locationId}, ${beehive.locationMap.get(srcParentId)})`;
        });

        let query = update + values + lastPart;
        utils.logDebug('Location parents update query:', query);
        await connection.query(query);
    }
    return idMap.size;
}

async function consolidateLocations(srcConn, destConn) {
    let query = 'SELECT * FROM location order by date_created';
    let [srcLocs] = await srcConn.query(query);
    let [destLocs] = await destConn.query(query);
    let [sql] = [null];

    try {
        let missingInDest = [];
        srcLocs.forEach(srcLoc => {
            let match = destLocs.find(destLoc => {
                return srcLoc['name'] === destLoc['name'];
            });

            if (match !== undefined && match !== null) {
                beehive.locationMap.set(srcLoc['location_id'], match['location_id']);
            } else {
                missingInDest.push(srcLoc);
            }
        });

        if (missingInDest.length > 0) {
            let nextLocationId = await utils.getNextAutoIncrementId(destConn, 'location');

            [sql] = prepareLocationInsert(missingInDest, nextLocationId);
            utils.logDebug('Location insert statement:\n', utils.shortenInsert(sql));
            let [result] = await destConn.query(sql);

            await updateParentForLocations(destConn, notYetUpdatedWithParentLocations);

            return result.affectedRows;
        }
        return 0;
    }
    catch(ex) {
        logError('Error while consolidating locations');
        if(sql) {
            logError('Statement during error:');
            logError(sql);
        }
        throw ex;
    }
}

module.exports = consolidateLocations;

redpajama_set_name: RedPajamaGithub


text:
/*******************************************************************************
* Utilities                                                                    *
*******************************************************************************/

function createWebSocket(path) {
    var host = window.location.hostname;
    if(host == '') host = 'localhost';
    var uri = 'ws://' + host + ':8000' + path;

    var Socket = "MozWebSocket" in window ? MozWebSocket : WebSocket;
    return new Socket(uri);
}

/*******************************************************************************
* Actual tests                                                                 *
*******************************************************************************/

module('QUnit');

test('demo', function() {
    ok(true, 'Demo test');
});

module('Hybi00');

asyncTest('echo-text', function() {
    var ws = createWebSocket('/echo-text');
    var messages = ['Hi folks', 'Hello there', 'λ±…'];

    ws.onopen = function() {
        ws.send(messages[0]);
    };

    ws.onmessage = function(event) {
        var message = event.data;
        equal(message, messages[0]);
        messages = messages.slice(1);
        if(messages.length > 0) {
            ws.send(messages[0]);
        } else {
            ws.close();
            start();
        }
    };
});

asyncTest('close me', function() {
    var ws = createWebSocket('/close-me');
    ws.onopen = function() {
        ws.send('Close me!');
    };
    ws.onclose = function() {
        ok(true, 'closed');
        start();
    };
});

asyncTest('concurrent send', function() {
    var ws = createWebSocket('/concurrent-send');
    var expected = [];
    for(var i = 1; i <= 100; i++) {
        expected.push('Herp-a-derp ' + i);
    }

    ws.onmessage = function(event) {
        var msg = event.data;
        var idx = expected.indexOf(msg);
        expected.splice(idx, 1);

        if(expected.length <= 0) {
            ws.close();
            ok(true, 'all received');
            start();
        }
    }
});

module('Hybi10');

asyncTest('ping', function() {
    var ws = createWebSocket('/ping');

    ws.onmessage = function(event) {
        if(event.data == 'OK') {
            ws.close();
            ok(true, 'ping');
            start();
        }
    };
});

asyncTest('blob', function() {
    var ws = createWebSocket('/echo');

    ws.onopen = function() {
        ws.binaryType = 'blob';
        var b = new Blob(['Hello world.'], {"type": "text/plain"});
        ws.send(b);
    };

    ws.onmessage = function(event){
        console.log(event.data)
        console.log(event.data.type)
    };
});


text:
// This files implements the logic for converting `scf.parallel` loops into
// tiled loops.

#include <cstdint>
#include <tuple>
#include <utility>

#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/iterator_range.h"
#include "mlir-hlo/Transforms/passes.h"
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Func/IR/FuncOps.h"
#include "mlir/Dialect/MemRef/IR/MemRef.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/SCF/Transforms/Transforms.h"
#include "mlir/Dialect/SCF/Utils/Utils.h"
#include "mlir/IR/OperationSupport.h"
#include "mlir/IR/Value.h"
#include "mlir/Transforms/GreedyPatternRewriteDriver.h"

namespace mlir {

#define GEN_PASS_DEF_TILELOOPSPASS
#include "mlir-hlo/Transforms/passes.h.inc"

using ::mlir::scf::ParallelOp;

namespace {

// This is the implementation of the TileLoops pass declared in
//  include/mlir-hlo/Transforms/passes.td
class TileLoopsPass : public impl::TileLoopsPassBase<TileLoopsPass> {
 public:
  // Creates a TileLoopsPass with tiles sizes provided through `tile_sizes`
  // and unroll factors provided through `unroll_factors`.
  explicit TileLoopsPass(ArrayRef<int64_t> tileSizes,
                         ArrayRef<int64_t> unrollFactors) {
    tile_sizes_ = tileSizes;
    unroll_factors_ = unrollFactors;
  }

  void runOnOperation() override;
};

}  // namespace

// Returns whether the access pattern in `ploop` is "complex". That is, whether
// any memref.load op in its region uses indices that don't correspond to the
// loop induction variables.
static bool isComplexAccessPattern(ParallelOp ploop) {
  auto isComplex = [&](memref::LoadOp loadOp) {
    if (!loadOp.getMemRefType().getLayout().isIdentity()) return true;
    if (loadOp.getIndices().empty()) return false;
    return loadOp.getIndices() != ploop.getInductionVars();
  };
  return llvm::any_of(ploop.getBody()->getOps<memref::LoadOp>(), isComplex);
}

void TileLoopsPass::runOnOperation() {
  SmallVector<int64_t> unrolledTile;
  if (tile_sizes_.size() == unroll_factors_.size()) {
    unrolledTile.reserve(tile_sizes_.size());
    for (int64_t i = 0; i < static_cast<int64_t>(tile_sizes_.size()); ++i)
      unrolledTile.push_back(tile_sizes_[i] * unroll_factors_[i]);
  }

  SmallVector<ParallelOp, 2> ploops;
  getInnermostParallelLoops(this->getOperation().getOperation(), ploops);
  for (ParallelOp ploop : ploops) {
    // Do not unroll if the tiling and unrolling have different rank, or if
    // the access pattern is complex.
    if (unrolledTile.empty() || isComplexAccessPattern(ploop)) {
      tileParallelLoop(ploop, tile_sizes_, /*noMinMaxBounds=*/false);
      continue;
    }

    // Collect lower/upper bounds and step size, if they are constants.
    auto getConstDefOps = [](OperandRange operands) {
      return llvm::to_vector(llvm::map_range(operands, [&](Value value) {
        return value.getDefiningOp<arith::ConstantIndexOp>();
      }));
    };
    auto lower = getConstDefOps(ploop.getLowerBound());
    auto upper = getConstDefOps(ploop.getUpperBound());
    auto step = getConstDefOps(ploop.getStep());

    bool noMinMaxBounds = false;
    ploop = tileParallelLoop(ploop, unrolledTile, noMinMaxBounds).second;
    ploop = tileParallelLoop(ploop, unroll_factors_, noMinMaxBounds).second;

    // Use static upper bound on unrolled loop if possible. That is, if the
    // unroll factor evenly divides the iteration size of the outer ploop.
    OpBuilder builder(ploop);
    Location loc = ploop.getLoc();
    for (int64_t i = 0; i < static_cast<int64_t>(unrolledTile.size()); ++i) {
      if (!lower[i] || !upper[i] || !step[i]) continue;
      int64_t unrollFactor = unroll_factors_[i];
      int64_t difference = upper[i].value() - lower[i].value();
      if (difference % (step[i].value() * unrollFactor) != 0) continue;
      ploop.getUpperBoundMutable().slice(i, 1).assign(
          builder.create<arith::ConstantIndexOp>(loc, unrollFactor));
    }
  }

  // Apply arithmetic dialect canonicalizations so that
  // ParallelToGpuLaunchLowering can derive loop-invariant upper bound for
  // number of iterations.
  RewritePatternSet patterns(&getContext());
  getContext()
      .getOrLoadDialect<arith::ArithDialect>()
      ->getCanonicalizationPatterns(patterns);
  if (failed(applyPatternsAndFoldGreedily(getOperation(), std::move(patterns))))
    return signalPassFailure();
}

std::unique_ptr<OperationPass<func::FuncOp>> createTileLoopsPass(
    ArrayRef<int64_t> tileSizes, ArrayRef<int64_t> unrollFactors) {
  return std::make_unique<TileLoopsPass>(tileSizes, unrollFactors);
}

}  // namespace mlir


text:
package org.kie.workbench.common.stunner.core.client.api;

import java.util.Collection;

import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;

import org.jboss.errai.ioc.client.container.SyncBeanDef;
import org.jboss.errai.ioc.client.container.SyncBeanManager;
import org.kie.workbench.common.stunner.core.api.AbstractDefinitionManager;
import org.kie.workbench.common.stunner.core.definition.DefinitionSetProxy;
import org.kie.workbench.common.stunner.core.definition.adapter.AdapterManager;
import org.kie.workbench.common.stunner.core.definition.adapter.DefinitionAdapter;
import org.kie.workbench.common.stunner.core.definition.adapter.DefinitionSetAdapter;
import org.kie.workbench.common.stunner.core.definition.adapter.DefinitionSetRuleAdapter;
import org.kie.workbench.common.stunner.core.definition.adapter.MorphAdapter;
import org.kie.workbench.common.stunner.core.definition.adapter.PropertyAdapter;
import org.kie.workbench.common.stunner.core.definition.adapter.PropertySetAdapter;
import org.kie.workbench.common.stunner.core.definition.clone.CloneManager;
import org.kie.workbench.common.stunner.core.registry.RegistryFactory;

@ApplicationScoped
public class ClientDefinitionManager extends AbstractDefinitionManager {

    private final SyncBeanManager beanManager;

    protected ClientDefinitionManager() {
        super();
        this.beanManager = null;
    }

    @Inject
    public ClientDefinitionManager(final SyncBeanManager beanManager,
                                   final RegistryFactory registryFactory,
                                   final AdapterManager adapterManager,
                                   final CloneManager cloneManager
    ) {
        super(registryFactory,
              adapterManager,
              cloneManager);
        this.beanManager = beanManager;
    }

    @PostConstruct
    @SuppressWarnings("unchecked")
    public void init() {
        // DefinitionSet client adapters.
        Collection<SyncBeanDef<DefinitionSetAdapter>> beanDefSetAdapters = beanManager.lookupBeans(DefinitionSetAdapter.class);
        for (SyncBeanDef<DefinitionSetAdapter> defSet : beanDefSetAdapters) {
            DefinitionSetAdapter definitionSet = defSet.getInstance();
            addAdapter(definitionSet);
        }
        // DefinitionSetRule client adapters.
        Collection<SyncBeanDef<DefinitionSetRuleAdapter>> beanDefSetRuleAdapters = beanManager.lookupBeans(DefinitionSetRuleAdapter.class);
        for (SyncBeanDef<DefinitionSetRuleAdapter> defSet : beanDefSetRuleAdapters) {
            DefinitionSetRuleAdapter definitionSet = defSet.getInstance();
            addAdapter(definitionSet);
        }
        // Definition client adapters.
        Collection<SyncBeanDef<DefinitionAdapter>> beanDefAdapters = beanManager.lookupBeans(DefinitionAdapter.class);
        for (SyncBeanDef<DefinitionAdapter> defSet : beanDefAdapters) {
            DefinitionAdapter definitionSet = defSet.getInstance();
            addAdapter(definitionSet);
        }
        // PropertySet client adapters.
        Collection<SyncBeanDef<PropertySetAdapter>> beanPropSetAdapters = beanManager.lookupBeans(PropertySetAdapter.class);
        for (SyncBeanDef<PropertySetAdapter> defSet : beanPropSetAdapters) {
            PropertySetAdapter definitionSet = defSet.getInstance();
            addAdapter(definitionSet);
        }
        // Property client adapters.
        Collection<SyncBeanDef<PropertyAdapter>> beanPropAdapters = beanManager.lookupBeans(PropertyAdapter.class);
        for (SyncBeanDef<PropertyAdapter> defSet : beanPropAdapters) {
            PropertyAdapter definitionSet = defSet.getInstance();
            addAdapter(definitionSet);
        }
        // Morph adapters.
        Collection<SyncBeanDef<MorphAdapter>> beanMorphAdapters = beanManager.lookupBeans(MorphAdapter.class);
        for (SyncBeanDef<MorphAdapter> morphAdapter : beanMorphAdapters) {
            MorphAdapter instance = morphAdapter.getInstance();
            addAdapter(instance);
        }
        // Once adapters present, add the Definition Sets found on current context.
        Collection<SyncBeanDef<DefinitionSetProxy>> beanDefSets = beanManager.lookupBeans(DefinitionSetProxy.class);
        for (SyncBeanDef<DefinitionSetProxy> defSet : beanDefSets) {
            DefinitionSetProxy definitionSetProxy = defSet.getInstance();
            Object definitionSet = definitionSetProxy.getDefinitionSet();
            addDefinitionSet(definitionSet);
        }
    }
}


text:
package build.buildfarm.worker;

import static build.bazel.remote.execution.v2.ExecutionStage.Value.QUEUED;
import static java.util.concurrent.TimeUnit.MICROSECONDS;

import build.bazel.remote.execution.v2.ExecuteOperationMetadata;
import build.buildfarm.common.Poller;
import build.buildfarm.instance.MatchListener;
import build.buildfarm.v1test.ExecuteEntry;
import build.buildfarm.v1test.QueueEntry;
import com.google.common.base.Preconditions;
import com.google.common.base.Stopwatch;
import com.google.common.base.Throwables;
import com.google.longrunning.Operation;
import com.google.protobuf.Any;
import com.google.protobuf.Timestamp;
import com.google.protobuf.util.Timestamps;
import java.util.logging.Logger;
import javax.annotation.Nullable;
import lombok.extern.java.Log;

@Log
public class MatchStage extends PipelineStage {
  private boolean inGracefulShutdown = false;

  public MatchStage(WorkerContext workerContext, PipelineStage output, PipelineStage error) {
    super("MatchStage", workerContext, output, error);
  }

  class MatchOperationListener implements MatchListener {
    private OperationContext operationContext;
    private final Stopwatch stopwatch;
    private long waitStart;
    private long waitDuration;
    private Poller poller = null;
    private QueueEntry queueEntry = null;
    private boolean matched = false;

    public MatchOperationListener(OperationContext operationContext, Stopwatch stopwatch) {
      this.operationContext = operationContext;
      this.stopwatch = stopwatch;
      waitDuration = this.stopwatch.elapsed(MICROSECONDS);
    }

    boolean wasMatched() {
      return matched;
    }

    @Override
    public void onWaitStart() {
      waitStart = stopwatch.elapsed(MICROSECONDS);
    }

    @Override
    public void onWaitEnd() {
      long elapsedUSecs = stopwatch.elapsed(MICROSECONDS);
      waitDuration += elapsedUSecs - waitStart;
      waitStart = elapsedUSecs;
    }

    @SuppressWarnings("ConstantConditions")
    @Override
    public boolean onEntry(@Nullable QueueEntry queueEntry) throws InterruptedException {
      if (queueEntry == null) {
        return false;
      }

      Preconditions.checkState(poller == null);
      operationContext =
          operationContext
              .toBuilder()
              .setQueueEntry(queueEntry)
              .setPoller(workerContext.createPoller("MatchStage", queueEntry, QUEUED))
              .build();
      return onOperationPolled();
    }

    @Override
    public void onError(Throwable t) {
      Throwables.throwIfUnchecked(t);
      throw new RuntimeException(t);
    }

    @Override
    public void setOnCancelHandler(Runnable onCancelHandler) {
      // never called, only blocking stub used
    }

    @SuppressWarnings("SameReturnValue")
    private boolean onOperationPolled() throws InterruptedException {
      String operationName = operationContext.queueEntry.getExecuteEntry().getOperationName();
      logStart(operationName);

      long matchingAtUSecs = stopwatch.elapsed(MICROSECONDS);
      OperationContext matchedOperationContext = match(operationContext);
      long matchedInUSecs = stopwatch.elapsed(MICROSECONDS) - matchingAtUSecs;
      logComplete(operationName, matchedInUSecs, waitDuration, true);
      matchedOperationContext.poller.pause();
      try {
        output.put(matchedOperationContext);
      } catch (InterruptedException e) {
        error.put(matchedOperationContext);
        throw e;
      }
      matched = true;
      return true;
    }
  }

  @Override
  protected Logger getLogger() {
    return log;
  }

  @Override
  protected void iterate() throws InterruptedException {
    // stop matching and picking up any works if the worker is in graceful shutdown.
    if (inGracefulShutdown) {
      return;
    }
    Stopwatch stopwatch = Stopwatch.createStarted();
    OperationContext operationContext = OperationContext.newBuilder().build();
    if (!output.claim(operationContext)) {
      return;
    }
    MatchOperationListener listener = new MatchOperationListener(operationContext, stopwatch);
    try {
      logStart();
      workerContext.match(listener);
    } finally {
      if (!listener.wasMatched()) {
        output.release();
      }
    }
  }

  void prepareForGracefulShutdown() {
    inGracefulShutdown = true;
  }

  private OperationContext match(OperationContext operationContext) {
    Timestamp workerStartTimestamp = Timestamps.fromMillis(System.currentTimeMillis());

    ExecuteEntry executeEntry = operationContext.queueEntry.getExecuteEntry();
    // this may be superfluous - we can probably just set the name and action digest
    Operation operation =
        Operation.newBuilder()
            .setName(executeEntry.getOperationName())
            .setMetadata(
                Any.pack(
                    ExecuteOperationMetadata.newBuilder()
                        .setActionDigest(executeEntry.getActionDigest())
                        .setStage(QUEUED)
                        .setStdoutStreamName(executeEntry.getStdoutStreamName())
                        .setStderrStreamName(executeEntry.getStderrStreamName())
                        .build()))
            .build();

    OperationContext matchedOperationContext =
        operationContext.toBuilder().setOperation(operation).build();

    matchedOperationContext
        .executeResponse
        .getResultBuilder()
        .getExecutionMetadataBuilder()
        .setWorker(workerContext.getName())
        .setQueuedTimestamp(executeEntry.getQueuedTimestamp())
        .setWorkerStartTimestamp(workerStartTimestamp);
    return matchedOperationContext;
  }

  @Override
  public OperationContext take() {
    throw new UnsupportedOperationException();
  }

  @Override
  public boolean claim(OperationContext operationContext) {
    throw new UnsupportedOperationException();
  }

  @Override
  public void release() {
    throw new UnsupportedOperationException();
  }

  @Override
  public void put(OperationContext operation) {
    throw new UnsupportedOperationException();
  }
}


text:
package main

type iCommand interface {
	execute()
}


text:
package org.knowm.xchange.luno.dto.account;

import com.fasterxml.jackson.annotation.JsonProperty;

public class LunoAccount {
  public final String id;
  public final String name;
  public final String currency;
  public final boolean defaultAccount;

  public LunoAccount(
      @JsonProperty(value = "id", required = true) String id,
      @JsonProperty(value = "name", required = true) String name,
      @JsonProperty(value = "currency", required = true) String currency,
      @JsonProperty(value = "is_default", required = true) boolean defaultAccount) {
    this.id = id;
    this.name = name;
    this.currency = currency;
    this.defaultAccount = defaultAccount;
  }

  @Override
  public String toString() {
    return "LunoAccount [id="
        + id
        + ", name="
        + name
        + ", currency="
        + currency
        + ", defaultAccount="
        + defaultAccount
        + "]";
  }
}


text:
package ru.job4j.taskIterator;

import org.junit.Test;
import ru.job4j.taskIterator.EvenIt;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * Test
 *
 * @author atrifonov.
 * @since 16.08.2017.
 * @version 1.
 */
public class TestEvenIt {
    /**
     * Test.
     */
    @Test
    public void whenArrayHaveEvenNumbersThatIteratorReturnOnlyEvenNumbers() {
        EvenIt iterator = new EvenIt(new int[]{1,2,3,4,5,6,7,1,3,4,6,8});
        List<Integer> list = new LinkedList<>();
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
        List<Integer> expectedList = new LinkedList<>(Arrays.asList(new Integer[]{2,4,6,4,6,8}));
        assertThat(list, is(expectedList));
    }

    /**
     * Test.
     */
    @Test
    public void whenHasNestAfterNextThenTrue() {
        EvenIt iterator = new EvenIt(new int[]{1,2,3,4});

        iterator.next();
        iterator.hasNext();

        assertThat(iterator.next(), is(4));
    }
}


text:
package com.afollestad.cabinet.plugins;

import android.os.Parcel;
import android.os.Parcelable;

import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;

/**
 * Used to store file objects that are sent from the plugin service to the main app.
 *
 * @author Aidan Follestad (afollestad)
 */
public class PluginFile implements Parcelable, Serializable {

    private static final long serialVersionUID = 5568771528989642943L;

    private final String mPackage;
    private final String mPath;
    private final String mThumbnail;
    private final long mCreated;
    private final long mModified;
    private final boolean isDir;
    private final long mLength;
    private final boolean isHidden;
    private final String mPermissions;
    private PluginFile mParent;

    public PluginFile(Parcel in) {
        mPackage = in.readString();
        mPath = in.readString();
        mThumbnail = in.readString();
        mCreated = in.readLong();
        mModified = in.readLong();
        isDir = in.readInt() == 1;
        mLength = in.readLong();
        isHidden = in.readInt() == 1;
        mPermissions = in.readString();
        mParent = in.readParcelable(PluginFile.class.getClassLoader());
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(mPackage);
        dest.writeString(mPath);
        dest.writeString(mThumbnail);
        dest.writeLong(mCreated);
        dest.writeLong(mModified);
        dest.writeInt(isDir ? 1 : 0);
        dest.writeLong(mLength);
        dest.writeInt(isHidden ? 1 : 0);
        dest.writeString(mPermissions);
        dest.writeParcelable(mParent, flags);
    }

    public PluginFile(JSONObject json) {
        mPackage = json.optString("package");
        mPath = json.optString("path");
        mThumbnail = json.optString("thumbnail");
        mCreated = json.optLong("created");
        mModified = json.optLong("modified");
        isDir = json.optBoolean("is_dir");
        mLength = json.optLong("length");
        isHidden = json.optBoolean("is_hidden");
        if (json.has("parent"))
            mParent = new PluginFile(json.optJSONObject("parent"));
        mPermissions = json.optString("permissions");
    }

    private PluginFile(Builder builder) {
        mPackage = builder.packageName;
        mPath = builder.path;
        mThumbnail = builder.thumbnail;
        mCreated = builder.created;
        mModified = builder.modified;
        isDir = builder.isDir;
        mLength = builder.length;
        isHidden = builder.hidden;
        mParent = builder.parent;
        mPermissions = builder.permissions;
    }

    public String getPackage() {
        return mPackage;
    }

    public String getPath() {
        return mPath;
    }

    public String getThumbnail() {
        return mThumbnail;
    }

    public long getCreated() {
        return mCreated;
    }

    public long getModified() {
        return mModified;
    }

    public boolean isDir() {
        return isDir;
    }

    public long getLength() {
        return mLength;
    }

    public boolean isHidden() {
        return isHidden;
    }

    public PluginFile getParent() {
        if (mParent == null && !mPath.equals("/")) {
            Builder parentBuilder = new Builder(null, getPackage())
                    .isDir(true)
                    .hidden(false);
            String tempPath = mPath;
            if (tempPath.endsWith(File.separator))
                tempPath = tempPath.substring(0, tempPath.length() - 1);
            tempPath = tempPath.substring(0, tempPath.lastIndexOf(File.separatorChar));
            mParent = parentBuilder.path(tempPath).build();
        }
        return mParent;
    }

    public String getPermissions() {
        return mPermissions;
    }

    public static class Builder {

        protected final String packageName;
        protected final PluginFile parent;

        protected String path;
        protected String thumbnail;
        protected long created;
        protected long modified;
        protected boolean isDir;
        protected long length;
        protected boolean hidden;
        protected String permissions;

        public Builder(PluginFile parent, String packageName) {
            this.parent = parent;
            this.packageName = packageName;
        }

        public Builder path(String path) {
            this.path = path;
            return this;
        }

        public Builder thumbnail(String thumbnail) {
            this.thumbnail = thumbnail;
            return this;
        }

        public Builder created(long created) {
            this.created = created;
            return this;
        }

        public Builder modified(long modified) {
            this.modified = modified;
            return this;
        }

        public Builder isDir(boolean isDir) {
            this.isDir = isDir;
            return this;
        }

        public Builder length(long length) {
            this.length = length;
            return this;
        }

        public Builder hidden(boolean hidden) {
            this.hidden = hidden;
            return this;
        }

        public Builder permissions(String permissions) {
            this.permissions = permissions;
            return this;
        }

        public PluginFile build() {
            if (this.isDir)
                this.length = -1;
            if (this.path == null || this.path.trim().isEmpty())
                this.path = "/";
            return new PluginFile(this);
        }

        @Override
        public String toString() {
            return "PluginFile#Builder: " + packageName;
        }
    }

    @Override
    public int describeContents() {
        return 0;
    }

    public JSONObject toJson() {
        JSONObject json = new JSONObject();
        try {
            json.put("package", mPackage);
            json.put("path", mPath);
            json.put("thumbnail", mThumbnail);
            json.put("created", mCreated);
            json.put("modified", mModified);
            json.put("is_dir", isDir);
            json.put("length", mLength);
            json.put("is_hidden", isHidden);
            if (mParent != null)
                json.put("parent", mParent.toJson());
            json.put("permissions", mPermissions);
        } catch (Exception ignored) {
        }
        return json;
    }

    public static final Creator<PluginFile> CREATOR = new Creator<PluginFile>() {
        @Override
        public PluginFile[] newArray(int size) {
            return new PluginFile[size];
        }

        @Override
        public PluginFile createFromParcel(Parcel source) {
            return new PluginFile(source);
        }
    };

    @Override
    public String toString() {
        return "[" + mPackage + "]: " + mPath;
    }
}


text:
try:
    from Tkinter import Label, Frame, Toplevel, Entry
    from Tkconstants import *
    from ttk import Separator
except ImportError:
    from tkinter import Label, Frame, Toplevel, Entry
    from tkinter.constants import *
    from tkinter.ttk import Separator

try:
  basestring
except NameError:
  basestring = str

class Listbox(Frame):
    def __init__(self, master, options, width=20, bordercolor="#cccccc", foreground="black", background="white", activebackground="#2780E3", activeforeground="white",padx=15, pady=7, command=None):
        Frame.__init__(self, master, background=background, highlightbackground=bordercolor, highlightcolor=bordercolor, highlightthickness=1, bd= 0)

        self._foreground = foreground
        self._background = background
        self._activebackground = activebackground
        self._activeforeground = activeforeground

        self._items = []

        index = 0
        for option in options:

            if option is None:
                Separator(self, orient=HORIZONTAL).pack(fill=X)
                continue

            if isinstance(option, basestring):
                test = option
                value = option
            else:
                text, value = option

            label_item = Label(self, width=width, text=text, background=background, foreground="black",  anchor=W, padx=padx, pady=pady)
            label_item.pack(fill=X)

            label_item.index = index
            label_item.value = value

            label_item.bind("<Enter>", self._on_enter_label_item)
            label_item.bind("<Leave>", self._on_leave_label_item)
            label_item.bind("<1>", lambda event, index=index:self._on_click_item(event.widget, index))
            self._items.append(label_item)

            index += 1

        self._actived_item = None
        self._command = command

        self.bind("<Up>", self._on_up)
        self.bind("<Down>", self._on_down)
        self.bind("<Return>", self._on_return)

    def _on_return(self, event):
        if self._command is not None:
             if self._actived_item is not None:
                 self._command(self._actived_item.value)

    def _activate_colors(self, label_item):
        label_item.configure(background=self._activebackground, foreground=self._activeforeground)

    def _deactivate_colors(self, label_item):
        label_item.configure(background=self._background, foreground=self._foreground)

    def _on_enter_label_item(self, event):
        label_item = event.widget
        self._activate_colors(label_item)

        self._actived_item = label_item

    def _on_leave_label_item(self, event):
        label_item = event.widget
        self._deactivate_colors(label_item)

    def _on_click_item(self, label_item, index):
        if self._actived_item != label_item:
            self._deactivate_colors(self._actived_item)
            self._activate_colors(label_item)
            self._actived_item = label_item

        self.focus_set()
        if self._command is not None:
            self._command(label_item.value)

    def _on_up(self, event):
        if self._actived_item is None:
            label_item = self._items[0]
            self._actived_item = label_item
            self._activate_colors(label_item)

        else:
            index = self._actived_item.index
            if index == 0: return
            index -= 1

            self._deactivate_colors(self._actived_item)

            self._actived_item = self._items[index]
            self._activate_colors(self._actived_item)

    def _on_down(self, event):
        if self._actived_item is None:
            label_item = self._items[0]
            self._actived_item = label_item
            self._activate_colors(label_item)

        else:
            index = self._actived_item.index
            if index == len(self._items) - 1: return

            index += 1

            self._deactivate_colors(self._actived_item)
            self._actived_item = self._items[index]
            self._activate_colors(self._actived_item)

if __name__ == "__main__":
    try:
        from Tkinter import Tk
    except ImportError:
        from tkinter import Tk

    root = Tk()

    def command(value):
        print("selected value: %s"%value)

    listbox = Listbox(root, options=(("Spain", "es"), None, ("USA", "us"), ("France","fr"), ("Britain", "br")), command=command)
    listbox.pack()

    listbox.focus()

    root.mainloop()


text:
using System.Collections.Generic;
using Free.FileFormats.VRML.Fields;
using Free.FileFormats.VRML.Interfaces;

namespace Free.FileFormats.VRML.Nodes
{
	/// <summary>
	/// The TriangleSet2D node specifies a set of triangles in the local 2D coordinate system.
	/// </summary>
	public class x3dTriangleSet2D : X3DNode, X3DGeometryNode
	{
		public List<SFVec2f> Vertices { get; set; }
		public bool Solid { get; set; }

		public x3dTriangleSet2D()
		{
			Vertices=new List<SFVec2f>();
			Solid=false;
		}

		internal override X3DPrototypeInstance GetProto() { return new x3dTriangleSet2DPROTO(); }

		internal override bool ParseNodeBodyElement(string id, VRMLParser parser)
		{
			if(id=="vertices")Vertices.AddRange(parser.ParseSFVec2fOrMFVec2fValue());
			else if(id=="solid") Solid=parser.ParseBoolValue();
			else return false;
			return true;
		}
	}
}


text:
import { expect } from 'chai';

import {
  beforeEach,
  describe,
  it,
} from '@bigtest/mocha';

import translations from '../../../translations/ui-users/en';

import setupApplication from '../helpers/setup-application';
import FeeFineInteractor from '../interactors/settings-feefine';

describe('Manual charges', () => {
  setupApplication({ scenarios: ['templates'] });

  describe('visit users-settings: fee-fines', () => {
    beforeEach(async function () {
      this.visit('/settings/users/feefinestable');

      await FeeFineInteractor.whenLoaded();
      await FeeFineInteractor.whenListLoaded();
    });

    it('renders proper amount of rows', () => {
      expect(FeeFineInteractor.list.rowCount).to.equal(1);
    });

    it('renders proper amount of columns', () => {
      expect(FeeFineInteractor.list.rows(0).cellCount).to.equal(5);
    });

    it('renders proper values for the first row', () => {
      const firstRow = FeeFineInteractor.list.rows(0);

      expect(firstRow.cells(0).text).to.equal('Feefine 1');
      expect(firstRow.cells(1).text).to.equal('1050.00');
      expect(firstRow.cells(2).text).to.equal('-');
      expect(firstRow.cells(3).text).to.equal('-');
    });

    describe('delete manual charge', () => {
      it('confirmation modal is not visible until delete button is clicked', () => {
        expect(FeeFineInteractor.confirmationModal.isPresent).to.be.false;
      });

      describe('is visible', () => {
        beforeEach(async () => {
          await FeeFineInteractor.list.rows(0).deleteButton.click();
        });

        it('when delete button is clicked', () => {
          expect(FeeFineInteractor.confirmationModal.isPresent).to.be.true;
        });
      });

      describe('confirmation modal disappears', () => {
        beforeEach(async () => {
          await FeeFineInteractor.list.rows(0).deleteButton.click();
          await FeeFineInteractor.confirmationModal.cancelButton.click();
        });

        it('when cancel button is clicked', () => {
          expect(FeeFineInteractor.confirmationModal.isPresent).to.be.false;
        });
      });

      describe('upon click on confirm button initiates the deletion process and in case of success', () => {
        beforeEach(async () => {
          await FeeFineInteractor.list.rows(0).deleteButton.click();
          await FeeFineInteractor.confirmationModal.confirmButton.click();
        });

        it('confirmation modal disappears', () => {
          expect(FeeFineInteractor.confirmationModal.isPresent).to.be.false;
        });

        it('the successful toast appears', () => {
          expect(FeeFineInteractor.callout.successCalloutIsPresent).to.be.true;
        });

        it('renders empty message', () => {
          expect(FeeFineInteractor.list.isPresent).to.be.false;
        });
      });
    });

    describe('cancel edit manual feefine', () => {
      beforeEach(async () => {
        await FeeFineInteractor.list.rows(0).editButton.click();
        await FeeFineInteractor.list.rows(0).textfield(0).fillAndBlur('Changed value');
        await FeeFineInteractor.list.rows(0).textfield(1).fillAndBlur('300');
        await FeeFineInteractor.list.rows(0).select(1).selectAndBlur('Template 1');
        await FeeFineInteractor.list.rows(0).select(0).selectAndBlur('Template 3');
        await FeeFineInteractor.list.rows(0).cancelButton.click();
      });

      it('renders proper values after cancel', () => {
        const firstRow = FeeFineInteractor.list.rows(0);

        expect(firstRow.cells(0).text).to.equal('Feefine 1');
        expect(firstRow.cells(1).text).to.equal('1050.00');
        expect(firstRow.cells(3).text).to.equal('-');
      });
    });

    describe('edit manual charge', () => {
      beforeEach(async () => {
        await FeeFineInteractor.list.rows(0).editButton.click();
        await FeeFineInteractor.list.rows(0).textfield(0).fillAndBlur('Changed value');
        await FeeFineInteractor.list.rows(0).textfield(1).fillAndBlur('300');
        await FeeFineInteractor.list.rows(0).select(1).selectAndBlur('Template 1');
        await FeeFineInteractor.list.rows(0).select(0).selectAndBlur('Template 3');
        await FeeFineInteractor.list.rows(0).saveButton.click();
      });

      it('renders proper values after update', () => {
        expect(FeeFineInteractor.list.rows(0).cells(0).text).to.equal('Changed value');
        expect(FeeFineInteractor.list.rows(0).cells(1).text).to.equal('300.00');
        expect(FeeFineInteractor.list.rows(0).cells(3).text).to.equal('Template 1');
      });
    });

    describe('create new manual feature', () => {
      beforeEach(async () => {
        await FeeFineInteractor.newItemButton.click();
        await FeeFineInteractor.list.rows(0).textfield(0).fillAndBlur('New feefine');
        await FeeFineInteractor.list.rows(0).textfield(1).fillAndBlur('100');
        await FeeFineInteractor.list.rows(0).select(1).selectAndBlur('Template 2');
        await FeeFineInteractor.list.rows(0).select(0).selectAndBlur('Template 4');
        await FeeFineInteractor.list.rows(0).saveButton.click();
      });

      it('renders proper values after update', () => {
        const lastRow = FeeFineInteractor.list.rows(1);

        expect(lastRow.cells(0).text).to.equal('New feefine');
        expect(lastRow.cells(1).text).to.equal('100.00');
        expect(lastRow.cells(3).text).to.equal('Template 2');
      });

      it('renders proper amount of rows', () => {
        expect(FeeFineInteractor.list.rowCount).to.equal(2);
      });
    });

    describe('edit and cancel owner charge notice', () => {
      beforeEach(async () => {
        await FeeFineInteractor.ownerSelect.selectAndBlur('Main Admin1');
        await FeeFineInteractor.notice.primaryButton.click();
        await FeeFineInteractor.notice.ownerChargeNotice.selectAndBlur('Template 3');
        await FeeFineInteractor.notice.ownerActionNotice.selectAndBlur('Template 2');
        await FeeFineInteractor.notice.cancelNotice.click();
      });

      it('renders proper values after cancel', () => {
        expect(FeeFineInteractor.notice.ownerChargeNoticeValue).to.equal('-');
        expect(FeeFineInteractor.notice.ownerActionNoticeValue).to.equal('-');
      });
    });

    describe('edit and save owner charge notice', () => {
      beforeEach(async () => {
        await FeeFineInteractor.ownerSelect.selectAndBlur('Main Admin1');
        await FeeFineInteractor.notice.primaryButton.click();
        await FeeFineInteractor.notice.ownerChargeNotice.selectAndBlur('Template 3');
        await FeeFineInteractor.notice.ownerActionNotice.selectAndBlur('Template 2');
        await FeeFineInteractor.notice.primaryButton.click();
      });

      it('renders proper values after update', () => {
        const lastRow = FeeFineInteractor.list.rows(1);

        expect(FeeFineInteractor.notice.ownerChargeNoticeValue).to.equal('Template 3');
        expect(FeeFineInteractor.notice.ownerActionNoticeValue).to.equal('Template 2');
        expect(lastRow.cells(2).text).to.equal(translations['settings.default']);
        expect(lastRow.cells(3).text).to.equal(translations['settings.default']);
      });
    });

    describe('copy feefines and save', () => {
      beforeEach(async () => {
        await FeeFineInteractor.ownerSelect.selectAndBlur('Main Admin2');
        await FeeFineInteractor.copyOwnerModal.select.selectAndBlur('Main Admin1');
        await FeeFineInteractor.copyOwnerModal.yes.clickAndBlur();
        await FeeFineInteractor.copyOwnerModal.no.clickAndBlur();
        await FeeFineInteractor.copyOwnerModal.buttons(0).click();
      });

      it('renders copy modal', () => {
        expect(FeeFineInteractor.isLoaded).to.be.false;
      });
    });

    describe('copy feefines and save', () => {
      beforeEach(async () => {
        await FeeFineInteractor.ownerSelect.selectAndBlur('Main Admin2');
        await FeeFineInteractor.copyOwnerModal.select.selectAndBlur('Main Admin1');
        await FeeFineInteractor.copyOwnerModal.yes.clickAndBlur();
        await FeeFineInteractor.copyOwnerModal.buttons(0).click();
      });

      it('renders copy modal', () => {
        expect(FeeFineInteractor.isLoaded).to.be.false;
      });
    });

    describe('create new manual whit errors', () => {
      beforeEach(async () => {
        await FeeFineInteractor.newItemButton.click();
        await FeeFineInteractor.list.rows(0).textfield(0).fillAndBlur('');
        await FeeFineInteractor.list.rows(0).textfield(0).fillAndBlur('Damage camera fee0');
        await FeeFineInteractor.list.rows(0).textfield(1).fillAndBlur('Item Lost');
        await FeeFineInteractor.list.rows(0).textfield(1).fillAndBlur('-10');
        await FeeFineInteractor.ownerSelect.selectAndBlur('Main Admin1');
        await FeeFineInteractor.newItemButton.click();
        await FeeFineInteractor.list.rows(0).textfield(0).fillAndBlur('Feefine 1');
        await FeeFineInteractor.list.rows(0).saveButton.click();
      });

      it('renders proper values after update', () => {
        const lastRow = FeeFineInteractor.list.rows(1);

        expect(lastRow.cells(0).text).to.equal('Damage camera fee0');
        expect(lastRow.cells(1).text).to.equal('1000.00');
        expect(lastRow.cells(3).text).to.equal('-');
      });
    });
  });
});


text:
<?php

namespace Doctrine\Tests\ORM\Mapping;

use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Events;

require_once __DIR__ . '/../../TestInit.php';
require_once __DIR__ . '/../../Models/Global/GlobalNamespaceModel.php';

class ClassMetadataTest extends \Doctrine\Tests\OrmTestCase
{
    public function testClassMetadataInstanceSerialization()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        // Test initial state
        $this->assertTrue(count($cm->getReflectionProperties()) == 0);
        $this->assertInstanceOf('ReflectionClass', $cm->reflClass);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->name);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->rootEntityName);
        $this->assertEquals(array(), $cm->subClasses);
        $this->assertEquals(array(), $cm->parentClasses);
        $this->assertEquals(ClassMetadata::INHERITANCE_TYPE_NONE, $cm->inheritanceType);

        // Customize state
        $cm->setInheritanceType(ClassMetadata::INHERITANCE_TYPE_SINGLE_TABLE);
        $cm->setSubclasses(array("One", "Two", "Three"));
        $cm->setParentClasses(array("UserParent"));
        $cm->setCustomRepositoryClass("UserRepository");
        $cm->setDiscriminatorColumn(array('name' => 'disc', 'type' => 'integer'));
        $cm->mapOneToOne(array('fieldName' => 'phonenumbers', 'targetEntity' => 'CmsAddress', 'mappedBy' => 'foo'));
        $cm->markReadOnly();
        $cm->addNamedQuery(array('name' => 'dql', 'query' => 'foo'));
        $this->assertEquals(1, count($cm->associationMappings));

        $serialized = serialize($cm);
        $cm = unserialize($serialized);
        $cm->wakeupReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        // Check state
        $this->assertTrue(count($cm->getReflectionProperties()) > 0);
        $this->assertEquals('Doctrine\Tests\Models\CMS', $cm->namespace);
        $this->assertInstanceOf('ReflectionClass', $cm->reflClass);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->name);
        $this->assertEquals('UserParent', $cm->rootEntityName);
        $this->assertEquals(array('Doctrine\Tests\Models\CMS\One', 'Doctrine\Tests\Models\CMS\Two', 'Doctrine\Tests\Models\CMS\Three'), $cm->subClasses);
        $this->assertEquals(array('UserParent'), $cm->parentClasses);
        $this->assertEquals('Doctrine\Tests\Models\CMS\UserRepository', $cm->customRepositoryClassName);
        $this->assertEquals(array('name' => 'disc', 'type' => 'integer', 'fieldName' => 'disc'), $cm->discriminatorColumn);
        $this->assertTrue($cm->associationMappings['phonenumbers']['type'] == ClassMetadata::ONE_TO_ONE);
        $this->assertEquals(1, count($cm->associationMappings));
        $oneOneMapping = $cm->getAssociationMapping('phonenumbers');
        $this->assertTrue($oneOneMapping['fetch'] == ClassMetadata::FETCH_LAZY);
        $this->assertEquals('phonenumbers', $oneOneMapping['fieldName']);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsAddress', $oneOneMapping['targetEntity']);
        $this->assertTrue($cm->isReadOnly);
        $this->assertEquals(array('dql' => array('name'=>'dql','query'=>'foo','dql'=>'foo')), $cm->namedQueries);
    }

    public function testFieldIsNullable()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        // Explicit Nullable
        $cm->mapField(array('fieldName' => 'status', 'nullable' => true, 'type' => 'string', 'length' => 50));
        $this->assertTrue($cm->isNullable('status'));

        // Explicit Not Nullable
        $cm->mapField(array('fieldName' => 'username', 'nullable' => false, 'type' => 'string', 'length' => 50));
        $this->assertFalse($cm->isNullable('username'));

        // Implicit Not Nullable
        $cm->mapField(array('fieldName' => 'name', 'type' => 'string', 'length' => 50));
        $this->assertFalse($cm->isNullable('name'), "By default a field should not be nullable.");
    }

    /**
     * @group DDC-115
     */
    public function testMapAssocationInGlobalNamespace()
    {
        require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php";

        $cm = new ClassMetadata('DoctrineGlobal_Article');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->mapManyToMany(array(
            'fieldName' => 'author',
            'targetEntity' => 'DoctrineGlobal_User',
            'joinTable' => array(
                'name' => 'bar',
                'joinColumns' => array(array('name' => 'bar_id', 'referencedColumnName' => 'id')),
                'inverseJoinColumns' => array(array('name' => 'baz_id', 'referencedColumnName' => 'id')),
            ),
        ));

        $this->assertEquals("DoctrineGlobal_User", $cm->associationMappings['author']['targetEntity']);
    }

    public function testMapManyToManyJoinTableDefaults()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->mapManyToMany(
            array(
            'fieldName' => 'groups',
            'targetEntity' => 'CmsGroup'
        ));

        $assoc = $cm->associationMappings['groups'];
        //$this->assertInstanceOf('Doctrine\ORM\Mapping\ManyToManyMapping', $assoc);
        $this->assertEquals(array(
            'name' => 'cmsuser_cmsgroup',
            'joinColumns' => array(array('name' => 'cmsuser_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE')),
            'inverseJoinColumns' => array(array('name' => 'cmsgroup_id', 'referencedColumnName' => 'id', 'onDelete' => 'CASCADE'))
        ), $assoc['joinTable']);
        $this->assertTrue($assoc['isOnDeleteCascade']);
    }

    public function testSerializeManyToManyJoinTableCascade()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->mapManyToMany(
            array(
            'fieldName' => 'groups',
            'targetEntity' => 'CmsGroup'
        ));

        /* @var $assoc \Doctrine\ORM\Mapping\ManyToManyMapping */
        $assoc = $cm->associationMappings['groups'];
        $assoc = unserialize(serialize($assoc));

        $this->assertTrue($assoc['isOnDeleteCascade']);
    }

    /**
     * @group DDC-115
     */
    public function testSetDiscriminatorMapInGlobalNamespace()
    {
        require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php";

        $cm = new ClassMetadata('DoctrineGlobal_User');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->setDiscriminatorMap(array('descr' => 'DoctrineGlobal_Article', 'foo' => 'DoctrineGlobal_User'));

        $this->assertEquals("DoctrineGlobal_Article", $cm->discriminatorMap['descr']);
        $this->assertEquals("DoctrineGlobal_User", $cm->discriminatorMap['foo']);
    }

    /**
     * @group DDC-115
     */
    public function testSetSubClassesInGlobalNamespace()
    {
        require_once __DIR__."/../../Models/Global/GlobalNamespaceModel.php";

        $cm = new ClassMetadata('DoctrineGlobal_User');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->setSubclasses(array('DoctrineGlobal_Article'));

        $this->assertEquals("DoctrineGlobal_Article", $cm->subClasses[0]);
    }

    /**
     * @group DDC-268
     */
    public function testSetInvalidVersionMapping_ThrowsException()
    {
        $field = array();
        $field['fieldName'] = 'foo';
        $field['type'] = 'string';

        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
        $cm->setVersionMapping($field);
    }

    public function testGetSingleIdentifierFieldName_MultipleIdentifierEntity_ThrowsException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->isIdentifierComposite  = true;

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
        $cm->getSingleIdentifierFieldName();
    }

    public function testDuplicateAssociationMappingException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $a1 = array('fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo');
        $a2 = array('fieldName' => 'foo', 'sourceEntity' => 'stdClass', 'targetEntity' => 'stdClass', 'mappedBy' => 'foo');

        $cm->addInheritedAssociationMapping($a1);
        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
        $cm->addInheritedAssociationMapping($a2);
    }

    public function testDuplicateColumnName_ThrowsMappingException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name'));

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
        $cm->mapField(array('fieldName' => 'username', 'columnName' => 'name'));
    }

    public function testDuplicateColumnName_DiscriminatorColumn_ThrowsMappingException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name'));

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
        $cm->setDiscriminatorColumn(array('name' => 'name'));
    }

    public function testDuplicateColumnName_DiscriminatorColumn2_ThrowsMappingException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->setDiscriminatorColumn(array('name' => 'name'));

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
        $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name'));
    }

    public function testDuplicateFieldAndAssocationMapping1_ThrowsException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name'));

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
        $cm->mapOneToOne(array('fieldName' => 'name', 'targetEntity' => 'CmsUser'));
    }

    public function testDuplicateFieldAndAssocationMapping2_ThrowsException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->mapOneToOne(array('fieldName' => 'name', 'targetEntity' => 'CmsUser'));

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
        $cm->mapField(array('fieldName' => 'name', 'columnName' => 'name'));
    }

    /**
     * @group DDC-1224
     */
    public function testGetTemporaryTableNameSchema()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->setTableName('foo.bar');

        $this->assertEquals('foo_bar_id_tmp', $cm->getTemporaryIdTableName());
    }

    public function testDefaultTableName()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        // When table's name is not given
        $primaryTable = array();
        $cm->setPrimaryTable($primaryTable);

        $this->assertEquals('CmsUser', $cm->getTableName());
        $this->assertEquals('CmsUser', $cm->table['name']);

        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        // When joinTable's name is not given
        $cm->mapManyToMany(array(
            'fieldName' => 'user',
            'targetEntity' => 'CmsUser',
            'inversedBy' => 'users',
            'joinTable' => array('joinColumns' => array(array('referencedColumnName' => 'id')),
                                 'inverseJoinColumns' => array(array('referencedColumnName' => 'id')))));
        $this->assertEquals('cmsaddress_cmsuser', $cm->associationMappings['user']['joinTable']['name']);
    }

    public function testDefaultJoinColumnName()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        // this is really dirty, but it's the simpliest way to test whether
        // joinColumn's name will be automatically set to user_id
        $cm->mapOneToOne(array(
            'fieldName' => 'user',
            'targetEntity' => 'CmsUser',
            'joinColumns' => array(array('referencedColumnName' => 'id'))));
        $this->assertEquals('user_id', $cm->associationMappings['user']['joinColumns'][0]['name']);

        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->mapManyToMany(array(
            'fieldName' => 'user',
            'targetEntity' => 'CmsUser',
            'inversedBy' => 'users',
            'joinTable' => array('name' => 'user_CmsUser',
                                'joinColumns' => array(array('referencedColumnName' => 'id')),
                                'inverseJoinColumns' => array(array('referencedColumnName' => 'id')))));
        $this->assertEquals('cmsaddress_id', $cm->associationMappings['user']['joinTable']['joinColumns'][0]['name']);
        $this->assertEquals('cmsuser_id', $cm->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['name']);
    }

    /**
     * @group DDC-559
     */
    public function testUnderscoreNamingStrategyDefaults()
    {
        $namingStrategy     = new \Doctrine\ORM\Mapping\UnderscoreNamingStrategy(CASE_UPPER);
        $oneToOneMetadata   = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', $namingStrategy);
        $manyToManyMetadata = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', $namingStrategy);

        $oneToOneMetadata->mapOneToOne(array(
            'fieldName'     => 'user',
            'targetEntity'  => 'CmsUser'
        ));

        $manyToManyMetadata->mapManyToMany(array(
            'fieldName'     => 'user',
            'targetEntity'  => 'CmsUser'
        ));

        $this->assertEquals(array('USER_ID'=>'ID'), $oneToOneMetadata->associationMappings['user']['sourceToTargetKeyColumns']);
        $this->assertEquals(array('USER_ID'=>'USER_ID'), $oneToOneMetadata->associationMappings['user']['joinColumnFieldNames']);
        $this->assertEquals(array('ID'=>'USER_ID'), $oneToOneMetadata->associationMappings['user']['targetToSourceKeyColumns']);

        $this->assertEquals('USER_ID', $oneToOneMetadata->associationMappings['user']['joinColumns'][0]['name']);
        $this->assertEquals('ID', $oneToOneMetadata->associationMappings['user']['joinColumns'][0]['referencedColumnName']);

        $this->assertEquals('CMS_ADDRESS_CMS_USER', $manyToManyMetadata->associationMappings['user']['joinTable']['name']);

        $this->assertEquals(array('CMS_ADDRESS_ID','CMS_USER_ID'), $manyToManyMetadata->associationMappings['user']['joinTableColumns']);
        $this->assertEquals(array('CMS_ADDRESS_ID'=>'ID'), $manyToManyMetadata->associationMappings['user']['relationToSourceKeyColumns']);
        $this->assertEquals(array('CMS_USER_ID'=>'ID'), $manyToManyMetadata->associationMappings['user']['relationToTargetKeyColumns']);

        $this->assertEquals('CMS_ADDRESS_ID', $manyToManyMetadata->associationMappings['user']['joinTable']['joinColumns'][0]['name']);
        $this->assertEquals('CMS_USER_ID', $manyToManyMetadata->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['name']);

        $this->assertEquals('ID', $manyToManyMetadata->associationMappings['user']['joinTable']['joinColumns'][0]['referencedColumnName']);
        $this->assertEquals('ID', $manyToManyMetadata->associationMappings['user']['joinTable']['inverseJoinColumns'][0]['referencedColumnName']);

        $cm = new ClassMetadata('DoctrineGlobal_Article', $namingStrategy);
        $cm->mapManyToMany(array('fieldName' => 'author', 'targetEntity' => 'Doctrine\Tests\Models\CMS\CmsUser'));
        $this->assertEquals('DOCTRINE_GLOBAL_ARTICLE_CMS_USER', $cm->associationMappings['author']['joinTable']['name']);
    }

    /**
     * @group DDC-886
     */
    public function testSetMultipleIdentifierSetsComposite()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->mapField(array('fieldName' => 'name'));
        $cm->mapField(array('fieldName' => 'username'));

        $cm->setIdentifier(array('name', 'username'));
        $this->assertTrue($cm->isIdentifierComposite);
    }

    /**
     * @group DDC-944
     */
    public function testMappingNotFound()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException', "No mapping found for field 'foo' on class 'Doctrine\Tests\Models\CMS\CmsUser'.");
        $cm->getFieldMapping('foo');
    }

    /**
     * @group DDC-961
     */
    public function testJoinTableMappingDefaults()
    {
        $cm = new ClassMetadata('DoctrineGlobal_Article');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->mapManyToMany(array('fieldName' => 'author', 'targetEntity' => 'Doctrine\Tests\Models\CMS\CmsUser'));

        $this->assertEquals('doctrineglobal_article_cmsuser', $cm->associationMappings['author']['joinTable']['name']);
    }

    /**
     * @group DDC-117
     */
    public function testMapIdentifierAssociation()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->mapOneToOne(array(
            'fieldName' => 'article',
            'id' => true,
            'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article',
            'joinColumns' => array(),
        ));

        $this->assertTrue($cm->containsForeignIdentifier, "Identifier Association should set 'containsForeignIdentifier' boolean flag.");
        $this->assertEquals(array("article"), $cm->identifier);
    }

    /**
     * @group DDC-117
     */
    public function testOrphanRemovalIdentifierAssociation()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException', 'The orphan removal option is not allowed on an association that');
        $cm->mapOneToOne(array(
            'fieldName' => 'article',
            'id' => true,
            'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article',
            'orphanRemoval' => true,
            'joinColumns' => array(),
        ));
    }

    /**
     * @group DDC-117
     */
    public function testInverseIdentifierAssocation()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException', 'An inverse association is not allowed to be identifier in');
        $cm->mapOneToOne(array(
            'fieldName' => 'article',
            'id' => true,
            'mappedBy' => 'details', // INVERSE!
            'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article',
            'joinColumns' => array(),
        ));
    }

    /**
     * @group DDC-117
     */
    public function testIdentifierAssocationManyToMany()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\DDC117\DDC117ArticleDetails');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException', 'Many-to-many or one-to-many associations are not allowed to be identifier in');
        $cm->mapManyToMany(array(
            'fieldName' => 'article',
            'id' => true,
            'targetEntity' => 'Doctrine\Tests\Models\DDC117\DDC117Article',
            'joinColumns' => array(),
        ));
    }

    /**
     * @group DDC-996
     */
    public function testEmptyFieldNameThrowsException()
    {
        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException',
            "The field or association mapping misses the 'fieldName' attribute in entity 'Doctrine\Tests\Models\CMS\CmsUser'.");
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->mapField(array('fieldName' => ''));
    }

    public function testRetrievalOfNamedQueries()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->assertEquals(0, count($cm->getNamedQueries()));

        $cm->addNamedQuery(array(
            'name'  => 'userById',
            'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1'
        ));

        $this->assertEquals(1, count($cm->getNamedQueries()));
    }

    /**
     * @group DDC-1663
     */
    public function testRetrievalOfResultSetMappings()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->assertEquals(0, count($cm->getSqlResultSetMappings()));

        $cm->addSqlResultSetMapping(array(
            'name'      => 'find-all',
            'entities'  => array(
                array(
                    'entityClass'   => 'Doctrine\Tests\Models\CMS\CmsUser',
                ),
            ),
        ));

        $this->assertEquals(1, count($cm->getSqlResultSetMappings()));
    }

    public function testExistanceOfNamedQuery()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->addNamedQuery(array(
            'name'  => 'all',
            'query' => 'SELECT u FROM __CLASS__ u'
        ));

        $this->assertTrue($cm->hasNamedQuery('all'));
        $this->assertFalse($cm->hasNamedQuery('userById'));
    }

    /**
     * @group DDC-1663
     */
    public function testRetrieveOfNamedNativeQuery()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->addNamedNativeQuery(array(
            'name'              => 'find-all',
            'query'             => 'SELECT * FROM cms_users',
            'resultSetMapping'  => 'result-mapping-name',
            'resultClass'       => 'Doctrine\Tests\Models\CMS\CmsUser',
        ));

        $cm->addNamedNativeQuery(array(
            'name'              => 'find-by-id',
            'query'             => 'SELECT * FROM cms_users WHERE id = ?',
            'resultClass'       => '__CLASS__',
            'resultSetMapping'  => 'result-mapping-name',
        ));

        $mapping = $cm->getNamedNativeQuery('find-all');
        $this->assertEquals('SELECT * FROM cms_users', $mapping['query']);
        $this->assertEquals('result-mapping-name', $mapping['resultSetMapping']);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $mapping['resultClass']);

        $mapping = $cm->getNamedNativeQuery('find-by-id');
        $this->assertEquals('SELECT * FROM cms_users WHERE id = ?', $mapping['query']);
        $this->assertEquals('result-mapping-name', $mapping['resultSetMapping']);
        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $mapping['resultClass']);
    }

    /**
     * @group DDC-1663
     */
    public function testRetrieveOfSqlResultSetMapping()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->addSqlResultSetMapping(array(
            'name'      => 'find-all',
            'entities'  => array(
                array(
                    'entityClass'   => '__CLASS__',
                    'fields'        => array(
                        array(
                            'name'  => 'id',
                            'column'=> 'id'
                        ),
                        array(
                            'name'  => 'name',
                            'column'=> 'name'
                        )
                    )
                ),
                array(
                    'entityClass'   => 'Doctrine\Tests\Models\CMS\CmsEmail',
                    'fields'        => array(
                        array(
                            'name'  => 'id',
                            'column'=> 'id'
                        ),
                        array(
                            'name'  => 'email',
                            'column'=> 'email'
                        )
                    )
                )
            ),
            'columns'   => array(
                array(
                    'name' => 'scalarColumn'
                )
            )
        ));

        $mapping = $cm->getSqlResultSetMapping('find-all');

        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $mapping['entities'][0]['entityClass']);
        $this->assertEquals(array('name'=>'id','column'=>'id'), $mapping['entities'][0]['fields'][0]);
        $this->assertEquals(array('name'=>'name','column'=>'name'), $mapping['entities'][0]['fields'][1]);

        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsEmail', $mapping['entities'][1]['entityClass']);
        $this->assertEquals(array('name'=>'id','column'=>'id'), $mapping['entities'][1]['fields'][0]);
        $this->assertEquals(array('name'=>'email','column'=>'email'), $mapping['entities'][1]['fields'][1]);

        $this->assertEquals('scalarColumn', $mapping['columns'][0]['name']);
    }

    /**
     * @group DDC-1663
     */
    public function testExistanceOfSqlResultSetMapping()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->addSqlResultSetMapping(array(
            'name'      => 'find-all',
            'entities'  => array(
                array(
                    'entityClass'   => 'Doctrine\Tests\Models\CMS\CmsUser',
                ),
            ),
        ));

        $this->assertTrue($cm->hasSqlResultSetMapping('find-all'));
        $this->assertFalse($cm->hasSqlResultSetMapping('find-by-id'));
    }

    /**
     * @group DDC-1663
     */
    public function testExistanceOfNamedNativeQuery()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->addNamedNativeQuery(array(
            'name'              => 'find-all',
            'query'             => 'SELECT * FROM cms_users',
            'resultClass'       => 'Doctrine\Tests\Models\CMS\CmsUser',
            'resultSetMapping'  => 'result-mapping-name'
        ));

        $this->assertTrue($cm->hasNamedNativeQuery('find-all'));
        $this->assertFalse($cm->hasNamedNativeQuery('find-by-id'));
    }

    public function testRetrieveOfNamedQuery()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->addNamedQuery(array(
            'name'  => 'userById',
            'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1'
        ));

        $this->assertEquals('SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u WHERE u.id = ?1', $cm->getNamedQuery('userById'));
    }

    /**
     * @group DDC-1663
     */
    public function testRetrievalOfNamedNativeQueries()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->assertEquals(0, count($cm->getNamedNativeQueries()));

        $cm->addNamedNativeQuery(array(
            'name'              => 'find-all',
            'query'             => 'SELECT * FROM cms_users',
            'resultClass'       => 'Doctrine\Tests\Models\CMS\CmsUser',
            'resultSetMapping'  => 'result-mapping-name'
        ));

        $this->assertEquals(1, count($cm->getNamedNativeQueries()));
    }

    /**
     * @expectedException \Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage Query named "userById" in "Doctrine\Tests\Models\CMS\CmsUser" was already declared, but it must be declared only once
     */
    public function testNamingCollisionNamedQueryShouldThrowException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->addNamedQuery(array(
            'name'  => 'userById',
            'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1'
        ));

        $cm->addNamedQuery(array(
            'name'  => 'userById',
            'query' => 'SELECT u FROM __CLASS__ u WHERE u.id = ?1'
        ));
    }

    /**
     * @group DDC-1663
     *
     * @expectedException \Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage Query named "find-all" in "Doctrine\Tests\Models\CMS\CmsUser" was already declared, but it must be declared only once
     */
    public function testNamingCollisionNamedNativeQueryShouldThrowException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->addNamedNativeQuery(array(
            'name'              => 'find-all',
            'query'             => 'SELECT * FROM cms_users',
            'resultClass'       => 'Doctrine\Tests\Models\CMS\CmsUser',
            'resultSetMapping'  => 'result-mapping-name'
        ));

        $cm->addNamedNativeQuery(array(
            'name'              => 'find-all',
            'query'             => 'SELECT * FROM cms_users',
            'resultClass'       => 'Doctrine\Tests\Models\CMS\CmsUser',
            'resultSetMapping'  => 'result-mapping-name'
        ));
    }

    /**
     * @group DDC-1663
     *
     * @expectedException \Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage Result set mapping named "find-all" in "Doctrine\Tests\Models\CMS\CmsUser" was already declared, but it must be declared only once
     */
    public function testNamingCollisionSqlResultSetMappingShouldThrowException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->addSqlResultSetMapping(array(
            'name'      => 'find-all',
            'entities'  => array(
                array(
                    'entityClass'   => 'Doctrine\Tests\Models\CMS\CmsUser',
                ),
            ),
        ));

        $cm->addSqlResultSetMapping(array(
            'name'      => 'find-all',
            'entities'  => array(
                array(
                    'entityClass'   => 'Doctrine\Tests\Models\CMS\CmsUser',
                ),
            ),
        ));
    }

    /**
     * @group DDC-1068
     */
    public function testClassCaseSensitivity()
    {
        $user = new \Doctrine\Tests\Models\CMS\CmsUser();
        $cm = new ClassMetadata('DOCTRINE\TESTS\MODELS\CMS\CMSUSER');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->assertEquals('Doctrine\Tests\Models\CMS\CmsUser', $cm->name);
    }

    /**
     * @group DDC-659
     */
    public function testLifecycleCallbackNotFound()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->addLifecycleCallback('notfound', 'postLoad');

        $this->setExpectedException("Doctrine\ORM\Mapping\MappingException", "Entity 'Doctrine\Tests\Models\CMS\CmsUser' has no method 'notfound' to be registered as lifecycle callback.");
        $cm->validateLifecycleCallbacks(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
    }

    /**
     * @group ImproveErrorMessages
     */
    public function testTargetEntityNotFound()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->mapManyToOne(array('fieldName' => 'address', 'targetEntity' => 'UnknownClass'));

        $this->setExpectedException("Doctrine\ORM\Mapping\MappingException", "The target-entity Doctrine\Tests\Models\CMS\UnknownClass cannot be found in 'Doctrine\Tests\Models\CMS\CmsUser#address'.");
        $cm->validateAssocations();
    }

    /**
     * @group DDC-1663
     *
     * @expectedException \Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage Query name on entity class 'Doctrine\Tests\Models\CMS\CmsUser' is not defined.
     */
    public function testNameIsMandatoryForNamedQueryMappingException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->addNamedQuery(array(
            'query' => 'SELECT u FROM Doctrine\Tests\Models\CMS\CmsUser u',
        ));
    }

    /**
     * @group DDC-1663
     *
     * @expectedException \Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage Query name on entity class 'Doctrine\Tests\Models\CMS\CmsUser' is not defined.
     */
    public function testNameIsMandatoryForNameNativeQueryMappingException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->addNamedQuery(array(
            'query'             => 'SELECT * FROM cms_users',
            'resultClass'       => 'Doctrine\Tests\Models\CMS\CmsUser',
            'resultSetMapping'  => 'result-mapping-name'
        ));
    }

    /**
     * @group DDC-1663
     *
     * @expectedException \Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage Result set mapping named "find-all" in "Doctrine\Tests\Models\CMS\CmsUser requires a entity class name.
     */
    public function testNameIsMandatoryForEntityNameSqlResultSetMappingException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->addSqlResultSetMapping(array(
            'name'      => 'find-all',
            'entities'  => array(
                array(
                    'fields' => array()
                )
            ),
        ));
    }

    /**
     * @expectedException \Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage Discriminator column name on entity class 'Doctrine\Tests\Models\CMS\CmsUser' is not defined.
     */
    public function testNameIsMandatoryForDiscriminatorColumnsMappingException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->setDiscriminatorColumn(array());
    }

    /**
     * @group DDC-984
     * @group DDC-559
     * @group DDC-1575
     */
    public function testFullyQualifiedClassNameShouldBeGivenToNamingStrategy()
    {
        $namingStrategy     = new MyNamespacedNamingStrategy();
        $addressMetadata    = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsAddress', $namingStrategy);
        $articleMetadata    = new ClassMetadata('DoctrineGlobal_Article', $namingStrategy);
        $routingMetadata    = new ClassMetadata('Doctrine\Tests\Models\Routing\RoutingLeg',$namingStrategy);

        $addressMetadata->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $articleMetadata->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $routingMetadata->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $addressMetadata->mapManyToMany(array(
            'fieldName'     => 'user',
            'targetEntity'  => 'CmsUser'
        ));

        $articleMetadata->mapManyToMany(array(
            'fieldName'     => 'author',
            'targetEntity'  => 'Doctrine\Tests\Models\CMS\CmsUser'
        ));

        $this->assertEquals('routing_routingleg', $routingMetadata->table['name']);
        $this->assertEquals('cms_cmsaddress_cms_cmsuser', $addressMetadata->associationMappings['user']['joinTable']['name']);
        $this->assertEquals('doctrineglobal_article_cms_cmsuser', $articleMetadata->associationMappings['author']['joinTable']['name']);
    }

    /**
     * @group DDC-1746
     */
    public function testInvalidCascade()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->setExpectedException("Doctrine\ORM\Mapping\MappingException", "You have specified invalid cascade options for Doctrine\Tests\Models\CMS\CmsUser::\$address: 'invalid'; available options: 'remove', 'persist', 'refresh', 'merge', and 'detach'");

        $cm->mapManyToOne(array('fieldName' => 'address', 'targetEntity' => 'UnknownClass', 'cascade' => array('invalid')));
     }

    /**
     * @group DDC-964
     * @expectedException        Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage Invalid field override named 'invalidPropertyName' for class 'Doctrine\Tests\Models\DDC964\DDC964Admin
     */
    public function testInvalidPropertyAssociationOverrideNameException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\DDC964\DDC964Admin');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->mapManyToOne(array('fieldName' => 'address', 'targetEntity' => 'DDC964Address'));

        $cm->setAssociationOverride('invalidPropertyName', array());
    }

    /**
     * @group DDC-964
     * @expectedException        Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage Invalid field override named 'invalidPropertyName' for class 'Doctrine\Tests\Models\DDC964\DDC964Guest'.
     */
    public function testInvalidPropertyAttributeOverrideNameException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\DDC964\DDC964Guest');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->mapField(array('fieldName' => 'name'));

        $cm->setAttributeOverride('invalidPropertyName', array());
    }

    /**
     * @group DDC-964
     * @expectedException        Doctrine\ORM\Mapping\MappingException
     * @expectedExceptionMessage The column type of attribute 'name' on class 'Doctrine\Tests\Models\DDC964\DDC964Guest' could not be changed.
     */
    public function testInvalidOverrideAttributeFieldTypeException()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\DDC964\DDC964Guest');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);
        $cm->mapField(array('fieldName' => 'name', 'type'=>'string'));

        $cm->setAttributeOverride('name', array('type'=>'date'));
    }

    /**
     * @group DDC-2608
     */
    public function testSetSequenceGeneratorThrowsExceptionWhenSequenceNameIsMissing()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $this->setExpectedException('Doctrine\ORM\Mapping\MappingException');
        $cm->setSequenceGeneratorDefinition(array());
    }

    /**
     * @group DDC-2662
     */
    public function testQuotedSequenceName()
    {
        $cm = new ClassMetadata('Doctrine\Tests\Models\CMS\CmsUser');
        $cm->initializeReflection(new \Doctrine\Common\Persistence\Mapping\RuntimeReflectionService);

        $cm->setSequenceGeneratorDefinition(array('sequenceName' => '`foo`'));

        $this->assertEquals(array('sequenceName' => 'foo', 'quoted' => true), $cm->sequenceGeneratorDefinition);
    }
}

class MyNamespacedNamingStrategy extends \Doctrine\ORM\Mapping\DefaultNamingStrategy
{
    /**
     * {@inheritdoc}
     */
    public function classToTableName($className)
    {
        if (strpos($className, '\\') !== false) {
            $className = str_replace('\\', '_', str_replace('Doctrine\Tests\Models\\', '', $className));
        }

        return strtolower($className);
    }
}


text:
"""
===================
Base Object Classes
===================
"""
from validation.validationresult.resultenum import ResultType
from validation.validators.document_validator import DocumentValidator
from validation.runner import ValidationsRunner
from base.enums import FieldType
from validation.validationresult.result import Result

class MemberTable(dict):
    """
        :type simple_fields: list[str]
        :type complex_fields: list[str]
        :type fields: dict[str,base.field.BaseField | BaseDocument]

        The custom dictionary for ordering and storing fields and embedded documents

        Has three attributes :
            1. ``fields`` in which field values are stored with corresponding key
            2. ``simple_fields`` in which simple fields keys are stored
            3. ``complex_fields`` in which complex fields keys are stored
    """

    def __init__(self):
        """
            :rtype : None

            Creating three extra list attributes :
                1. ``fields``
                2. ``simple_fields``
                3. ``complex_fields``
            in which corresponding attributes key's are stored in order they where writen
        """
        self.simple_fields = []
        """Simple field's keys are stored"""
        self.complex_fields = []
        """Complex field's keys are stored"""
        self.fields = dict()
        """Field's values are stored"""
        super().__init__()

    def __setitem__(self, key, value):
        """
            Appending ``fields`` with corresponding value

            Appending ``simple_field`` and ``complex_field`` with corresponding
            attributes key's
        """
        if key not in self:
            if hasattr(value, 'FIELD_TYPE'):
                if value.FIELD_TYPE == FieldType.Simple:
                    self.simple_fields.append(key)
                else:
                    self.complex_fields.append(key)
                self.fields[key] = value
                return
        # Call superclass
        dict.__setitem__(self, key, value)

class OrderedClass(type):
    """
        Metaclass for maintaining order of attributes defined in class

        .. NOTE::
            Fields added in ``__init__`` function and after creating object aren't ordered

        It has three attributes:
            1. ``fields`` dictionary in which field's values are stored
            2. ``simple_field`` list in which simple fields keys are stored
            3. ``complex_field`` list in which complex fields keys are stored
    """

    # The prepare function
    # noinspection PyMethodOverriding
    @classmethod
    def __prepare__(mcs, name, bases):  # No keywords in this case
        """

        :param name:
        :param bases:
        :return: :py:class:`MemberTable <base.objects.MemberTable>`
        :rtype: MemberTable
        """
        return MemberTable()

    # The metaclass invocation
    def __new__(mcs, name, bases, class_dict):
        # Note that we replace the class_dict with a regular
        # dict before passing it to the superclass, so that we
        # don't continue to record member names after the class
        # has been created.
        """
        :param name
        :type name: str
        :param bases
        :type bases: list
        :param class_dict
        :type class_dict: MemberTable
        :rtype: BaseDocument
        """
        result = type.__new__(mcs, name, bases, dict(class_dict))
        result._simple_fields = class_dict.simple_fields
        result._complex_fields = class_dict.complex_fields
        result._fields = class_dict.fields
        return result

class BaseDocument(metaclass=OrderedClass):
    """
        :type _simple_fields: list[str]
        :type _complex_fields: list[str]
        :type _fields: dict[str,base.field.BaseField | BaseDocument]
        :type _errors: dict
        :type mapper: base.mapper.MapperABC
        :type FIELD_TYPE: FieldType

        Base parser object which handles setting and getting
        simple and fields.
    """
    _simple_fields = []
    _complex_fields = []
    _fields = []
    FIELD_TYPE = FieldType.Complex
    RESULT_TYPE = ResultType.Document
    """``FIELD_TYPE`` attributes value is  :py:class:`FieldType.Complex <base.enums.FieldType>`"""

    @property
    def errors(self):
        """
        :return: error dictionary
        :rtype: dict

        Read only property
        """
        return self._errors

    @errors.setter
    def errors(self):
        pass

    @errors.deleter
    def errors(self):
        pass

    def __init__(self):
        self.runner = ValidationsRunner()
        self._errors = dict()
        """:py:class:`list` list of validator functions"""
        self.mapper = None
        """:py:class:`base.mapper.MapperABC` abstract class implementation"""
        [setattr(self, key, None) for key in self._fields]
        self.__add_validators()
        self.runner.sort_validators()

    def __load_simple_field(self, field_name):
        """
        :param field_name
        :type field_name: str
        :rtype: None
        """
        field = self._fields.get(field_name).load(self.mapper.get_item(field_name))
        setattr(self, field_name, field)

    def __load_complex_field(self, field_name):
        """
            :param field_name
            :type field_name: str
            :rtype: None
            """
        mapper_data = self.mapper.get_item(field_name)
        if mapper_data is None:
            setattr(self, field_name, self._fields.get(field_name).load())
            return
        field = self._fields.get(field_name).load(mapper_data)
        setattr(self, field_name, field)

    def __add_validators(self):
        self.runner.add_validator(DocumentValidator.validate_type)
        self.runner.add_validator(
            DocumentValidator.validate_children,
            dependencies=[DocumentValidator.validate_type.key]
        )

    # todo wrong logic must change everything about mapper
    def fill_mapper_data(self):
        [self.mapper.set_item(field_name, self._fields.get(field_name).dump(getattr(self, field_name))) for field_name
         in
         self._simple_fields]

        [self.mapper.set_item(document_name, getattr(self, document_name).fill_mapper_data()) for document_name in
         self._complex_fields]

        return self.mapper.dump_data

    def load(self, data):
        """
        Loads from raw or preloaded data

        :param data: raw or preloaded data
        :type data: Any
        :return: BaseObject subclass
        """
        if self.mapper is not None:
            self.mapper.load(data)
            [self.__load_simple_field(field_name) for field_name in self._simple_fields]
            [self.__load_complex_field(field_name) for field_name in self._complex_fields]
        else:
            raise AttributeError("mapper isn't defined")
        return self

    # todo move mapper validation for None in __init__
    def dump(self):
        """
            Refills mapper's data from instances
            and then calls :py:attr:`mappers <base.objects.BaseObject.mapper>` ``dump`` function and returns it's result
        """
        if self.mapper is not None:
            self.fill_mapper_data()
        else:
            raise AttributeError("mapper isn't defined")
        return self.mapper.dump()

    def get_fields(self) -> dict:
        return self._fields

    def is_valid(self):
        """
        Calls :py:meth:`validate`

        :return: whether data in object is valid or not
        :rtype: boolFieldType
        """
        return Result.is_valid(self.validate(self))

    def validate(self, data):
        return self.runner.run(self, data)


text:
set -e

test_expected () {
    BASH_DIR=$(dirname_ $BASH_SOURCE)
    PARENT=$(dirname_ $BASH_DIR)
    if [[ $(python $PARENT/first_num.py "$@") == $EXPECTED ]]; then
        echo pass
        return 0
    fi
    echo fail
    echo -n "Expected: ${EXPECTED}, Args: $* "
    echo Actual: $(python $PARENT/first_num.py "$@")
    return 1
}

EXPECTED=3
test_expected 3
test_expected 3 4
test_expected 3 hhh lll
test_expected hhh 3 lll
test_expected hhh lll 3

EXPECTED="hhh lll"
test_expected 3 hhh lll --Invert
test_expected hhh 3 lll --Invert
test_expected hhh lll 3 --Invert
test_expected --Invert 3 hhh lll
test_expected --Invert hhh 3 lll
test_expected --Invert hhh lll 3
test_expected 3 hhh --Invert lll
test_expected hhh 3 --Invert lll
test_expected hhh --Invert lll 3

EXPECTED=""
test_expected hhh lll

EXPECTED="hhh lll"
test_expected hhh lll --Invert
test_expected hhh 3 lll --Invert


text:
function idx= cspselect_equalPerClass(score, ~, nComponents)
%CSPSELECT_EQUALPERCLASS - Select equally many CSP components for each class
%
%Synopsis:
% CI = select_fixedNumber(SCORE, ~, NCOMP)
%
%Arguments:
% SCORE  - score of components
% NCOMPS - number of components (total number depends on MODE)
%
%Returns:
% CI     - index of components
%
%See also processing/proc_csp

idx= [1:nComponents, length(score)-nComponents+1:length(score)]';