text:
package edu.kit.aifb.cumulus.store;

import static edu.kit.aifb.cumulus.framework.Environment.BASE_URI;
import static edu.kit.aifb.cumulus.framework.Environment.DATETIME_RANGETYPES;
import static edu.kit.aifb.cumulus.framework.Environment.NUMERIC_RANGETYPES;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.EventObject;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.management.InstanceAlreadyExistsException;

import org.openrdf.model.BNode;
import org.openrdf.model.Literal;
import org.openrdf.model.Statement;
import org.openrdf.model.Value;
import org.openrdf.rio.RDFFormat;
import org.openrdf.rio.RDFHandlerException;
import org.openrdf.rio.RDFParseException;
import org.openrdf.rio.RDFParser;
import org.openrdf.rio.Rio;
import org.openrdf.rio.helpers.RDFHandlerBase;
import org.slf4j.LoggerFactory;

import com.google.common.collect.AbstractIterator;
import com.google.common.util.concurrent.AtomicDouble;

import edu.kit.aifb.cumulus.framework.InitialisationException;
import edu.kit.aifb.cumulus.framework.datasource.DataAccessLayerException;
import edu.kit.aifb.cumulus.framework.datasource.DataAccessLayerFactory;
import edu.kit.aifb.cumulus.framework.datasource.StorageLayout;
import edu.kit.aifb.cumulus.framework.datasource.TripleIndexDAO;
import edu.kit.aifb.cumulus.framework.domain.configuration.Configurable;
import edu.kit.aifb.cumulus.framework.domain.configuration.Configuration;
import edu.kit.aifb.cumulus.framework.domain.configuration.DefaultConfigurator;
import edu.kit.aifb.cumulus.framework.domain.dictionary.ITopLevelDictionary;
import edu.kit.aifb.cumulus.framework.domain.selectivity.ISelectivityEstimator;
import edu.kit.aifb.cumulus.framework.events.ITriplesChangesListener;
import edu.kit.aifb.cumulus.framework.mx.ManageableStore;
import edu.kit.aifb.cumulus.framework.mx.ManagementRegistrar;
import edu.kit.aifb.cumulus.log.Log;
import edu.kit.aifb.cumulus.log.MessageCatalog;
import edu.kit.aifb.cumulus.store.events.AddTripleEvent;
import edu.kit.aifb.cumulus.store.events.FinishedChangesEvent;
import edu.kit.aifb.cumulus.store.events.StartChangesEvent;
import edu.kit.aifb.cumulus.store.sel.HeuristicsBasedSelectivityEstimator;
import edu.kit.aifb.cumulus.util.Util;

/**
 * Supertype lauer for CumulusRDF stores.
 *
 * @author Andreas Wagner
 * @author Andreas Harth
 * @author Andrea Gazzarini
 * @since 1.0
 */
public abstract class Store implements Configurable<Map<String, Object>>, ManageableStore {
	/**
	 * Listener inteface for components interested in store status changes.
	 *
	 * @author Andreas Wagner
	 * @since 1.0
	 */
	class StatusListener implements ITriplesChangesListener {

		private int _runningOperations;

		/**
		 * Returns true if there are running operations.
		 * @return True if there are running operations.
		 */
		public boolean active() {
			return _runningOperations > 0;
		}

		@Override
		public void update(final EventObject event) {
			if (event instanceof StartChangesEvent) {
				_runningOperations++;
			} else if (event instanceof FinishedChangesEvent) {
				_runningOperations--;
			}
		}
	}

	/**
	 * A simple value object that encapsulates a change operation result.
	 *
	 * @author Andrea Gazzarini
	 * @since 1.0.1
	 */
	final class ChangeStatResult {
		private final long _elapsed;
		private final int _affectedCount;

		/**
		 * Builds a new result with the given data.
		 *
		 * @param elapsed the elapsed time of the change.
		 * @param affectedCount how many affected triple / quads by the change.
		 */
		ChangeStatResult(final long elapsed, final int affectedCount) {
			this._elapsed = elapsed;
			this._affectedCount = affectedCount;
		}
	}

	/**
	 * RDFHandler implementor for bulk data load.
	 * The load of data is actually done in chunks, in order to buffer and speedup the
	 * entire process. Callers can specify the size of those chunks with the batchLimit
	 * parameter.
	 *
	 * @author Sebastian Schmidt
	 * @author Andrea Gazzarini
	 * @since 1.0
	 */
	final class RDFBulkLoadHandler extends RDFHandlerBase {

		private final Queue<Future<ChangeStatResult>> _futures;
		private final int _batchLimit;

		private List<Statement> _statementBuffer;

		private long _totalElapsed;
		private int _estimatedCountOfInsertedStatements;

		private boolean _dequeuerEnabled = true;
		private Future<?> _dequeuerFuture;

		private final Runnable _dequeuer = new Runnable() {

			@Override
			public void run() {
				while (_dequeuerEnabled) {
					try {
						final Future<ChangeStatResult> future = _futures.poll();

						if (future != null) {
							final ChangeStatResult result = future.get();
							_estimatedCountOfInsertedStatements += result._affectedCount;
							final double ts = ((double) result._affectedCount / result._elapsed * 1000);
							_loadWorkerThroughput.set(ts);
							_log.debug(
									MessageCatalog._00076_INSERT_STATS,
									result._affectedCount,
									result._elapsed,
									ts);
						}
					} catch (final Exception exception) {
						_log.error(MessageCatalog._00026_NWS_SYSTEM_INTERNAL_FAILURE, exception);
					}
				}
			}
		};

		/**
		 * Creates a new handler with the given threads.
		 *
		 * @param batchLimit the maximum size of a chunk.
		 */
		public RDFBulkLoadHandler(final int batchLimit) {
			this._batchLimit = batchLimit;
			this._futures = new ConcurrentLinkedQueue<Future<ChangeStatResult>>();
		}

		@Override
		public void startRDF() throws RDFHandlerException {
			_dequeuerFuture = _workers.submit(_dequeuer);
			_statementBuffer = new ArrayList<Statement>(_batchLimit);
			_totalElapsed = System.currentTimeMillis();
		}

		@Override
		public void endRDF() throws RDFHandlerException {
			if (_dequeuerEnabled) {
				// Terminate dequeuer
				_dequeuerEnabled = false;

				try {
					// Wait until the dequeuer completes before continuing...
					// This is necessary to ensure that the bulk loading has really been completed once the bulkLoad method returns.
					// If we wouldn't do that, this method might return while the dequeuer is still executing.
					_dequeuerFuture.get();
				} catch (InterruptedException e) {
					_log.error(MessageCatalog._00026_NWS_SYSTEM_INTERNAL_FAILURE, e);
				} catch (ExecutionException e) {
					_log.error(MessageCatalog._00026_NWS_SYSTEM_INTERNAL_FAILURE, e);
				}

				if (_statementBuffer.size() > 0) {
					fireAddForCurrentChunk();
				}

				for (final Future<ChangeStatResult> future : _futures) {
					try {
						final ChangeStatResult result = future.get();
						_estimatedCountOfInsertedStatements += result._affectedCount;
						final double ts = ((double) result._affectedCount / result._elapsed * 1000);
						_loadWorkerThroughput.set(ts);
						_log.debug(
								MessageCatalog._00076_INSERT_STATS,
								result._affectedCount,
								result._elapsed,
								ts);
					} catch (final Exception exception) {
						_log.error(MessageCatalog._00026_NWS_SYSTEM_INTERNAL_FAILURE, exception);
					}
				}

				_totalElapsed = System.currentTimeMillis() - _totalElapsed;
				final double loadThroughput = ((double) _estimatedCountOfInsertedStatements / _totalElapsed * 1000);
				_loadThroughput.set(loadThroughput);
				_log.info(
						MessageCatalog._00083_TOTAL_INSERT_STATS,
						_estimatedCountOfInsertedStatements,
						_totalElapsed,
						loadThroughput);
			}
		}

		@Override
		public void handleStatement(final Statement statement) throws RDFHandlerException {
			_statementBuffer.add(statement);

			if (_statementBuffer.size() >= _batchLimit) {
				fireAddForCurrentChunk();
			}
		}

		/**
		 * Schedules a new asynchronous task for inserting the current chunk.
		 */
		private void fireAddForCurrentChunk() {
			_futures.offer(_workers.submit(new BulkInsertCallable(_statementBuffer)));
			_statementBuffer.clear();
		}
	}

	/**
	 * A {@link Callable} implementation for defining a bulk insert task.
	 *
	 * @author Andrea Gazzarini
	 * @since 1.0.1
	 */
	class BulkInsertCallable implements Callable<ChangeStatResult> {
		private final Iterator<Statement> _statements;
		private final int _statementsCount;

		/**
		 * Builds a new task for a given list of statements.
		 *
		 * @param statements the statement that will be inserted.
		 */
		public BulkInsertCallable(final List<Statement> statements) {
			_statementsCount = statements.size();
			_statements = new ArrayList<Statement>(statements).iterator();
		}

		/**
		 * Executes the chunk insert.
		 *
		 * @return a stat object containing (estimated) inserted triples and elapsed time.
		 * @throws Exception if something goes wrong during the insertion.
		 */
		@Override
		public ChangeStatResult call() throws Exception {
			long begin = System.currentTimeMillis();
			batchInsert(_statements, Integer.MAX_VALUE);
			return new ChangeStatResult(System.currentTimeMillis() - begin, _statementsCount);
		}
	}

	/**
	 * Iterator used in DESCRIBE.
	 *
	 * @author Andreas Wagner
	 * @since 1.0
	 */
	public class DescribeIterator extends AbstractIterator<Statement> {

		private final Value _mResource;
		private final boolean _mInclude2Hop;

		// iterator for pattern with resource as subject
		private final Iterator<Statement> _mSit;
		// iterator for hop patterns
		private Iterator<Statement> _mHit;
		// iterator for pattern with resource as object
		private final Iterator<Statement> _mOit;
		private int _mSubjects;
		private int _mObjects;

		/**
		 * Builds a new Describe iterator with the given data.
		 *
		 * @param resource the target resource.
		 * @param include2Hop
		 * @param subjects max subjects in results.
		 * @param objects max objects in results.
		 * @throws CumulusStoreException in case of CumulusRDF internal failure.
		 */
		public DescribeIterator(final Value resource, final boolean include2Hop, final int subjects, final int objects) throws CumulusStoreException {

			_mResource = resource;
			_mInclude2Hop = include2Hop;
			_mSubjects = subjects;
			_mObjects = objects;

			_mSit = query(new Value[] {_mResource, null, null}, _mSubjects);
			_mOit = query(new Value[] {null, null, _mResource}, _mObjects);
		}

		@Override
		protected Statement computeNext() {

			if (_mHit != null && _mHit.hasNext()) {
				return _mHit.next();
			}

			if (_mSit != null && _mSit.hasNext()) {

				final Statement statement = _mSit.next();
				final Value object = statement.getObject();
				// if the hop should be included, prime the hop iterator,
				// pattern has the current object as subject
				if (_mInclude2Hop || object instanceof BNode) {
					try {
						_mHit = query(new Value[] {object, null, null}, _mSubjects);
					} catch (CumulusStoreException e) {
						_log.error(e.getMessage());
						_mHit = null;
					}
				}

				return statement;
			}

			if (_mOit != null && _mOit.hasNext()) {

				final Statement statement = _mOit.next();
				final Value object = statement.getObject();
				// if the hop should be included, prime the hop iterator,
				// pattern has the current object as subject
				if (_mInclude2Hop || object instanceof BNode) {
					try {
						_mHit = query(new Value[] {object, null, null}, _mSubjects);
					} catch (CumulusStoreException e) {
						_log.error(e.getMessage());
						_mHit = null;
					}
				}

				return statement;
			}

			return endOfData();
		}
	}

	static final Object DUMMY_SOURCE_EVENT = new Object();

	protected final Log _log = new Log(LoggerFactory.getLogger(getClass()));
	protected final String _id;
	protected TripleIndexDAO _rdfIndexDAO;
	protected ExecutorService _workers;
	protected int _batchLimit = 1000;
	protected boolean _idxRanges;

	protected int _insertRequests;
	protected int _deleteRequests;
	protected int _averageInsertedTriplesPerSec;
	protected int _averageDeletedTriplesPerSec;
	boolean _isOpen;

	protected CounterFactory _counterFactory;

	protected List<ITriplesChangesListener> _changeListeners;
	protected ISelectivityEstimator _selectEstimator;

	ITopLevelDictionary _dictionary;
	DataAccessLayerFactory _factory;

	protected Schema _schema;
	protected StatusListener _status;

	final Configuration<Map<String, Object>> _configurator;

	protected StartChangesEvent _startChangesEvent = StartChangesEvent.newEvent(this);
	protected FinishedChangesEvent _finishedChangesEvent = FinishedChangesEvent.newEvent(this);

	protected AtomicDouble _loadWorkerThroughput = new AtomicDouble();
	protected AtomicDouble _loadThroughput = new AtomicDouble();

	protected AtomicDouble deletedTriplesPerSecond = new AtomicDouble();

	/**
	 * Builds a new anonymous (without identifier) store.
	 */
	public Store() {
		this(UUID.randomUUID().toString());
	}

	/**
	 * Builds a new store with a given identifier.
	 *
	 * @param id the store identifier.
	 */
	public Store(final String id) {
		_id = id;
		_configurator = new DefaultConfigurator(id);
	}

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

	@Override
	public boolean isOpen() {
		return _isOpen;
	}

	/**
	 * Returns the counter factory associated with this store.
	 *
	 * @return the counter factory associated with this store.
	 */
	public CounterFactory getCounterFactory() {
		_counterFactory = CounterFactory.getInstance();
		return _counterFactory;
	}

	/**
	 * Returns the dictionary that is used to translate from ids to the
	 * corresponding nodes and back.
	 *
	 * @return The node dictionary.
	 */
	public ITopLevelDictionary getDictionary() {
		return _dictionary;
	}

	/**
	 * Returns the selectivity estimator that is used by this store.
	 *
	 * @return selectivity estimator
	 */
	public ISelectivityEstimator getSelectivityEstimator() {
		return _selectEstimator;
	}

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

	@Override
	public double getLoadWorkerThroughput() {
		return _loadWorkerThroughput.get();
	}

	@Override
	public double getLoadThroughput() {
		return _loadThroughput.get();
	}

	@Override
	public boolean equals(final Object anotherStore) {
		return anotherStore != null
				&& this.getClass() == anotherStore.getClass()
				&& ((Store) anotherStore)._id.equals(_id);
	}

	/**
	 * Adds all triples (or quads) from the given iterator to the store.
	 *
	 * @param iterator the statements iterator.
	 * @throws CumulusStoreException if the insertion caused an error.
	 */
	public abstract void addData(Iterator<Statement> iterator) throws CumulusStoreException;

	/**
	 * Adds all triples or quads from the given file to the store.
	 *
	 * @param file The file to read from.
	 * @param format The format of the file.
	 * @throws CumulusStoreException If an error occurs during adding the data.
	 * @throws IOException If an error occurs during reading from the given file.
	 */
	public void bulkLoad(final File file, final RDFFormat format) throws CumulusStoreException, IOException {
		if (file == null || !file.canRead()) {
			throw new FileNotFoundException(file != null ? file.getAbsolutePath() : "Null input file");
		}

		_log.debug(MessageCatalog._00046_BATCH_BULK_LOAD_DATA_STARTS, _batchLimit);

		notifyListeners(_startChangesEvent);

		Reader reader = null;
		final RDFParser rdfParser = Rio.createParser(format);
		final RDFBulkLoadHandler handler = new RDFBulkLoadHandler(_batchLimit);

		try {
			reader = new BufferedReader(new FileReader(file), 8192 * 4);
			rdfParser.setRDFHandler(handler);
			rdfParser.parse(reader, BASE_URI);
		} catch (final RDFParseException exception) {
			_log.debug(MessageCatalog._00029_RDF_PARSE_FAILURE, exception);
			try {
				handler.endRDF();
			} catch (RDFHandlerException ignore) {
				_log.debug(MessageCatalog._00029_RDF_PARSE_FAILURE, ignore);
			}
			throw new CumulusStoreException(exception);
		} catch (final RDFHandlerException exception) {
			_log.debug(MessageCatalog._00029_RDF_PARSE_FAILURE, exception);
			throw new CumulusStoreException(exception);
		} finally {

			try {
				handler.endRDF();
			} catch (RDFHandlerException ignore) {
				_log.debug(MessageCatalog._00029_RDF_PARSE_FAILURE, ignore);
			}

			if (reader != null) {
				try {
					reader.close();
				} catch (final Exception ignore) {
					// Ignore
				}
			}
			notifyListeners(_finishedChangesEvent);
		}
	}

	/**
	 * Adds all triples or quads from the file at the given path to the store.<br />
	 * This method uses 2/3 of the connected hosts threads to insert into
	 * Cassandra.
	 *
	 * @param file The path to the file to read from.
	 * @param format The format of the file.
	 * @throws CumulusStoreException If an error occurs during adding the data.
	 * @throws IOException If an error occurs during reading from the given file.
	 */
	public void bulkLoad(final String file, final RDFFormat format) throws CumulusStoreException, IOException {
		bulkLoad(new File(file), format);
	}

	/**
	 * Adds all triples or quads from the given input stream to the store.
	 *
	 * @param inputStream The input stream to read from.
	 * @param format The format of the data from the input stream.
	 * @throws CumulusStoreException If an error occurs during adding the data.
	 * @throws IOException If an error occurs during reading from the given file.
	 */
	public void bulkLoad(final InputStream inputStream, final RDFFormat format) throws CumulusStoreException, IOException {
		_log.debug(MessageCatalog._00046_BATCH_BULK_LOAD_DATA_STARTS, _batchLimit);

		notifyListeners(_startChangesEvent);

		final RDFParser rdfParser = Rio.createParser(format);
		rdfParser.setRDFHandler(new RDFBulkLoadHandler(_batchLimit));

		try {
			rdfParser.parse(inputStream, BASE_URI);
		} catch (final RDFParseException exception) {
			_log.debug(MessageCatalog._00029_RDF_PARSE_FAILURE, exception);
			throw new CumulusStoreException(exception);
		} catch (final RDFHandlerException exception) {
			_log.debug(MessageCatalog._00029_RDF_PARSE_FAILURE, exception);
			throw new CumulusStoreException(exception);
		}

		notifyListeners(_finishedChangesEvent);
	}

	/**
	 * Adds the given triple (or quad) to the store.
	 *
	 * @param triple The triple or quad.
	 * @throws CumulusStoreException If the insertion caused an error.
	 */
	public abstract void addData(Statement triple) throws CumulusStoreException;

	/**
	 * Closes all connections to the underlying storage.
	 */
	public final void close() {
		if (!_isOpen) {
			_log.info(MessageCatalog._00084_STORE_ALREADY_CLOSED, this);
			return;
		}

		if (_selectEstimator != null) {
			_selectEstimator.close();
		}

		if (_counterFactory != null) {
			_counterFactory.close();
		}

		try {
			_rdfIndexDAO.close();
		} catch (final DataAccessLayerException exception) {
			_log.error(MessageCatalog._00093_DATA_ACCESS_LAYER_FAILURE, exception);
		}

		ManagementRegistrar.unregisterStore(
				this,
				String.valueOf(storageLayout()),
				getDataAccessLayerFactory().getUnderlyingStorageInfo());

		_workers.shutdown();

		_dictionary.close();

		_log.info(MessageCatalog._00085_STORE_HAS_BEEN_CLOSED, this);
		_isOpen = false;
	}

	/**
	 *
	 * Return a description for the given resource, i.e., the RDF graph
	 * surrounding the resource.
	 *
	 * @param resource the target resource.
	 * @param include2Hop .
	 * @return a description for the given resource, i.e., the RDF graph surrounding the resource.
	 * @throws CumulusStoreException in case of system internal failure.
	 */
	public Iterator<Statement> describe(final Value resource, final boolean include2Hop) throws CumulusStoreException {
		return describe(resource, include2Hop, Integer.MAX_VALUE, Integer.MAX_VALUE);
	}

	/**
	 *
	 * Return a description for the given resource, i.e., the RDF graph surrounding the resource.
	 *
	 * @param resource the target resource.
	 * @param include2Hop .
	 * @param subjects max number of statements in result that contain the given resource as subject.
	 * @param objects max number of statements in result that contain the given resource as object.
	 * @return a description for the given resource, i.e., the RDF graph surrounding the resource.
	 * @throws CumulusStoreException in case of system internal failure.
	 */
	public Iterator<Statement> describe(final Value resource, final boolean include2Hop, final int subjects, final int objects) throws CumulusStoreException {
		return new DescribeIterator(resource, include2Hop, subjects, objects);
	}

	/**
	 * Returns all RDFS classes in this store.
	 *
	 * @return RDFS classes
	 */
	public abstract Set<Value> getClasses();

	/**
	 * Returns all data-properties in this store.
	 *
	 * @return data-properties
	 */
	public abstract Set<Value> getDataProperties();

	/**
	 * Returns all object-properties in this store.
	 *
	 * @return object-properties
	 */
	public abstract Set<Value> getObjectProperties();

	/**
	 * Returns the prefix / namespaces dictionary of this store.
	 *
	 * @return the prefix / namespaces dictionary of this store.
	 */
	public abstract PersistentMap<String, String> getPrefix2Namespaces();

	/**
	 * Returns the current status of the connected cluster.<br />
	 * That is the status of every pool of the cluster, read/write statistics,
	 * information about the schema and the number of active
	 * additions/deletions.
	 *
	 * @return The status of the connected cluster.
	 */
	public abstract String getStatus();

	/**
	 *
	 * Checks if given value v is a RDF class.
	 *
	 * @param v the value.
	 * @return true if value v is an RDF class.
	 */
	public abstract boolean isClass(Value v);

	/**
	 *
	 * Checks if given value v is a data-property.
	 *
	 * @param v the value.
	 * @return true if value v is a data-property.
	 */
	public abstract boolean isDataProperty(Value v);

	/**
	 *
	 * Checks if given value v is an object-property.
	 *
	 * @param v the value.
	 * @return true if value v is an object-property.
	 */
	public abstract boolean isObjectProperty(Value v);

	/**
	 * Open the store.
	 * After completing this operation, the store instance is supposed to be available.
	 *
	 * @throws CumulusStoreException If the connection cannot be established.
	 */
	public final void open() throws CumulusStoreException {
		if (isOpen()) {
			_log.info(MessageCatalog._00049_STORE_ALREADY_OPEN);
			return;
		}

		try {
			ManagementRegistrar.registerStore(
					this,
					String.valueOf(storageLayout()),
					getDataAccessLayerFactory().getUnderlyingStorageInfo());
		} catch (InstanceAlreadyExistsException exception) {
			_log.error(MessageCatalog._00111_MBEAN_ALREADY_REGISTERED, getId());
			throw new CumulusStoreException(exception);
		} catch (final Exception exception) {
			_log.error(MessageCatalog._00109_UNABLE_TO_REGISTER_MBEAN, exception, getId());
			throw new CumulusStoreException(exception);
		}

		_factory = getDataAccessLayerFactory();

		_log.info(MessageCatalog._00114_UNDERLYING_STORAGE, _id, _factory.getUnderlyingStorageInfo());

		_configurator.configure(_factory);
		_configurator.configure(this);

		try {
			_dictionary = Dictionaries.newDefaultDictionary(_configurator);

			_rdfIndexDAO = getRdfIndexDAO();
			_rdfIndexDAO.initialiseRdfIndex();
		} catch (final DataAccessLayerException exception) {
			_log.error(MessageCatalog._00093_DATA_ACCESS_LAYER_FAILURE, exception);
			throw new CumulusStoreException(exception);
		}

		try {

			_dictionary.initialise(_factory);
			_log.info(MessageCatalog._00090_DICTIONARY_INITIALISED, _dictionary.getClass().getName());
		} catch (final InitialisationException exception) {
			_log.error(MessageCatalog._00092_DICTIONARY_INIT_FAILURE, exception);
			throw new CumulusStoreException(exception);
		}

		try {
			final CounterFactory counterFactory = getCounterFactory();
			counterFactory.initialise(_factory);
		} catch (final InitialisationException exception) {
			_log.error(MessageCatalog._00095_COUNTER_FACTORY_INIT_FAILURE, exception);
			throw new CumulusStoreException(exception);
		}

		_selectEstimator = new HeuristicsBasedSelectivityEstimator(getCounterFactory());
		_status = new StatusListener();
		_changeListeners = new LinkedList<ITriplesChangesListener>();
		_changeListeners.add(_selectEstimator);
		_changeListeners.add(_status);

		openInternal();

		final int howManyWorkers = computeWorkersPoolSize();

		final RejectedExecutionHandler rejectedExecutionHandler = new ThreadPoolExecutor.CallerRunsPolicy();
		_workers = new ThreadPoolExecutor(
				howManyWorkers,
				howManyWorkers,
				0L, TimeUnit.MILLISECONDS,
				new ArrayBlockingQueue<Runnable>(100),
				rejectedExecutionHandler);

		_log.info(MessageCatalog._00047_BATCH_BULK_LOAD_DATA_THREAD_POOL_SIZE, howManyWorkers);

		_isOpen = true;
		_log.info(MessageCatalog._00052_STORE_OPEN);
	}

	/**
	 * Concrete store instances must specify here their startup and open procedures.
	 *
	 * @throws CumulusStoreException If the connection cannot be established.
	 */
	protected abstract void openInternal() throws CumulusStoreException;

	/**
	 * Queries the store for triples or quads. A query is an array of 3 or 4
	 * nodes. A null value represents a variable. This method gives an unlimited
	 * amount of results (Integer.MAX_VALUE).
	 *
	 * @param query
	 *            The query, containing nodes and variables, the array must have
	 *            the form: {s, p, o, c}, c is only used for quad stores.
	 * @return An iterator iterating through the results of the query.
	 * @throws CumulusStoreException
	 *             If an error occurred while executing the query.
	 */
	public abstract Iterator<Statement> query(Value[] query) throws CumulusStoreException;

	/**
	 * Queries the store for triples or quads. A query is an array of 3 or 4
	 * nodes. A null value represents a variable. This amount of results is
	 * limited.
	 *
	 * @param query
	 *            The query, containing nodes and variables, the array must have
	 *            the form: {s, p, o, c}, c is only used for quad stores.
	 * @param limit
	 *            The maximum amount of results to return.
	 * @return An iterator iterating through the results of the query.
	 * @throws CumulusStoreException
	 *             If an error occurred while executing the query.
	 */
	public abstract Iterator<Statement> query(Value[] query, int limit) throws CumulusStoreException;

	/**
	 * Same as {@link #query(Value[], int)}, but returns node ids instead of
	 * plain nodes.
	 *
	 * @param query the triple / quad pattern.
	 * @param limit a limit on the total number of results.
	 * @throws CumulusStoreException If an error occurred while executing the query.
	 * @return an iterator containing query result (as identifiers).
	 */
	protected abstract Iterator<byte[][]> queryAsIDs(Value[] query, int limit) throws CumulusStoreException;

	/**
	 * Same as {@link #query(Value[])}, but returns and takes node ids instead of
	 * plain nodes.
	 *
	 * @param query the triple / quad pattern.
	 * @throws CumulusStoreException If an error occurred while executing the query.
	 * @return an iterator containing query result (as identifiers).
	 */
	public abstract Iterator<byte[][]> queryWithIDs(byte[][] query) throws CumulusStoreException;

	/**
	 * Same as {@link query(Value[], int)}, but returns and takes node ids
	 * instead of plain nodes.
	 *
	 * @param query the triple / quad pattern.
	 * @param limit a limit on the total number of results.
	 * @throws CumulusStoreException If an error occurred while executing the query.
	 * @return an iterator containing query result (as identifiers).
	 */
	protected abstract Iterator<byte[][]> queryWithIDs(byte[][] query, int limit) throws CumulusStoreException;

	/**
	 * Same as {@link query(Value[])}, but takes node ids instead of plain nodes.
	 *
	 * @param query the triple / quad pattern.
	 * @throws CumulusStoreException If an error occurred while executing the query.
	 * @return an iterator containing query result (as identifiers).
	 */
	protected abstract Iterator<byte[][]> queryWithIDs(Value[] query) throws CumulusStoreException;

	/**
	 * Performs a range query on the triple store. A range query is a query that
	 * has at least predicate and a range for the object. It returns all triples
	 * with that predicate and a numeric object in the given range.
	 *
	 * @param query
	 *            The query, must be an array with a length of 2, containing the
	 *            subject (or null if subject is a variable) and the predicate.
	 * @param lowerBound
	 *            The lower bound of the range. Has to be numeric.
	 * @param equalsLower
	 *            True if the lower bound is inclusive (triples having an object
	 *            equal to the lower bound are included), false otherwise.
	 * @param upperBound
	 *            The upper bound of the range. Has to be numeric.
	 * @param equalsUpper
	 *            True if the upper bound is inclusive (triples having an object
	 *            equal to the upper bound are included), false otherwise.
	 * @param reverse
	 *            True if the results should be returned in reverse order.
	 * @param limit
	 *            The maximum amount of results to return.
	 * @return An iterator containing the result of the query.
	 * @throws CumulusStoreException in case of query execution failure.
	 */
	public abstract Iterator<Statement> range(
			Value[] query,
			Literal lowerBound,
			boolean equalsLower,
			Literal upperBound,
			boolean equalsUpper,
			boolean reverse,
			int limit) throws CumulusStoreException;

	/**
	 * Same as {@link #range(Value[], Literal, boolean, Literal, boolean, boolean, int)}, but returns node ids instead of nodes.
	 *
	 * @param query
	 *            The query, must be an array with a length of 2, containing the
	 *            subject (or null if subject is a variable) and the predicate.
	 * @param lowerBound
	 *            The lower bound of the range. Has to be numeric.
	 * @param equalsLower
	 *            True if the lower bound is inclusive (triples having an object
	 *            equal to the lower bound are included), false otherwise.
	 * @param upperBound
	 *            The upper bound of the range. Has to be numeric.
	 * @param equalsUpper
	 *            True if the upper bound is inclusive (triples having an object
	 *            equal to the upper bound are included), false otherwise.
	 * @param reverse
	 *            True if the results should be returned in reverse order.
	 * @param limit
	 *            The maximum amount of results to return.
	 * @return An iterator containing the result (as identifiers) of the query.
	 * @throws DataAccessLayerException in case of data access failure.
	 */
	public abstract Iterator<byte[][]> rangeAsIDs(
			Value[] query,
			Literal lowerBound,
			boolean equalsLower,
			Literal upperBound,
			boolean equalsUpper,
			boolean reverse,
			int limit) throws DataAccessLayerException;

	/**
	 * Performs a range query on the triple store. A range query is a query that
	 * has at least predicate and a range for the object. It returns all triples
	 * with that predicate and a date/time object in the given range.
	 *
	 * @param query
	 *            The query, must be an array with a length of 2, containing the
	 *            subject (or null if subject is a variable) and the predicate.
	 * @param lowerBound
	 *            The lower bound of the range. Has to be date/time.
	 * @param equalsLower
	 *            True if the lower bound is inclusive (triples having an object
	 *            equal to the lower bound are included), false otherwise.
	 * @param upperBound
	 *            The upper bound of the range. Has to be date/time.
	 * @param equalsUpper
	 *            True if the upper bound is inclusive (triples having an object
	 *            equal to the upper bound are included), false otherwise.
	 * @param reverse
	 *            True if the results should be returned in reverse order.
	 * @param limit
	 *            The maximum amount of results to return.
	 * @return An iterator containing the result of the query.
	 * @throws CumulusStoreException
	 */
	public abstract Iterator<Statement> rangeDateTime(
			Value[] query,
			Literal lowerBound,
			boolean equalsLower,
			Literal upperBound,
			boolean equalsUpper,
			boolean reverse,
			int limit) throws CumulusStoreException;

	/**
	 * Same as
	 * {@link #rangeDateTime(Value[], Literal, boolean, Literal, boolean, boolean, int)}
	 * , but returns node ids instead of nodes.
	 * @param query
	 *            The query, must be an array with a length of 2, containing the
	 *            subject (or null if subject is a variable) and the predicate.
	 * @param lowerBound
	 *            The lower bound of the range. Has to be numeric.
	 * @param equalsLower
	 *            True if the lower bound is inclusive (triples having an object
	 *            equal to the lower bound are included), false otherwise.
	 * @param upperBound
	 *            The upper bound of the range. Has to be numeric.
	 * @param equalsUpper
	 *            True if the upper bound is inclusive (triples having an object
	 *            equal to the upper bound are included), false otherwise.
	 * @param reverse
	 *            True if the results should be returned in reverse order.
	 * @param limit
	 *            The maximum amount of results to return.
	 * @return An iterator containing the result (as identifiers) of the query.
	 * @throws DataAccessLayerException
	 */
	public abstract Iterator<byte[][]> rangeDateTimeAsIDs(
			Value[] query,
			Literal lowerBound,
			boolean equalsLower,
			Literal upperBound,
			boolean equalsUpper,
			boolean reverse,
			int limit) throws DataAccessLayerException;

	@Override
	public boolean isRangeIndexesSupportEnabled() {
		return _idxRanges;
	}

	/**
	 * Removes all given triples or quads from the store.
	 *
	 * @param triples An iterator iterating over the triples or quads to delete.
	 * @throws CumulusStoreException If an error occurred during deletion.
	 */
	public abstract void removeData(Iterator<Statement> triples) throws CumulusStoreException;

	/**
	 * Removes the given triple or quad from the store.
	 *
	 * @param pattern An iterator iterating over the triples or quads to delete.
	 * @throws CumulusStoreException If an error occurred during deletion.
	 */
	public abstract void removeData(Value[] pattern) throws CumulusStoreException;

	/**
	 * Same as {@link #removeData(Iterator)}, but taking node ids instead of
	 * plain nodes.
	 *
	 * @param pattern An iterator iterating over the triples or quads to delete.
	 * @throws CumulusStoreException If an error occurred during deletion.
	 */
	protected abstract void removeDataWithIDs(byte[][] pattern) throws CumulusStoreException;

	/**
	 * Same as {@link #removeData(Value[])}, but taking node ids instead of plain
	 * nodes.
	 *
	 * @param triples An iterator iterating over the triples or quads to delete.
	 * @throws CumulusStoreException If an error occurred during deletion.
	 * @throws DataAccessLayerException
	 */
	protected abstract void removeDataWithIDs(Iterator<byte[][]> triples) throws CumulusStoreException, DataAccessLayerException;

	@Override
	public void setDefaultBatchLimit(final int numOfTriplesPerBatch) {
		if (numOfTriplesPerBatch > 0) {
			_batchLimit = numOfTriplesPerBatch;
		}
	}

	@Override
	public int getDefaultBatchLimit() {
		return _batchLimit;
	}

	@Override
	public boolean activeChanges() {
		return _status.active();
	}

	/**
	 * Enables the range indexes on this store instance.
	 * Note that this must be called *before* opening the store.
	 */
	void enableRangeIndexesSupport() {
		if (!isOpen()) {
			_idxRanges = true;
		}
	}

	/**
	 * Clears all data within this store.
	 */
	public void clear() {
		_rdfIndexDAO.clear();
	}

	/**
	 * Returns the layout of this store.
	 *
	 * @return the layout of this store.
	 */
	protected abstract StorageLayout storageLayout();

	/**
	 * Returns the data access layer factory associated with this store.
	 *
	 * @return the data access layer factory associated with this store.
	 */
	protected DataAccessLayerFactory getDataAccessLayerFactory() {
		return DataAccessLayerFactory.getDefaultDataAccessLayerFactory(storageLayout());
	}

	/**
	 * Fires a given event object to registered listeners.
	 *
	 * @param event the event object.
	 */
	void notifyListeners(final EventObject event) {
		for (final ITriplesChangesListener listener : _changeListeners) {
			listener.update(event);
		}
	}

	/**
	 * Inserts the given triples/quads into the store.
	 *
	 * @param nodes an iterator iterating over the triples/quads to insert.
	 * @param batchSize the maximum size of a batch query.
	 * @throws DataAccessLayerException in case of data access failure.
	 */
	void batchInsert(final Iterator<Statement> nodes, final int batchSize) throws DataAccessLayerException {

		final List<byte[][]> triples = new ArrayList<byte[][]>(Math.min(1000, batchSize));

		while (nodes.hasNext()) {
			for (int i = 0; i < batchSize && nodes.hasNext(); i++) {

				byte[][] ids;
				final Statement statement = nodes.next();

				ids = (statement.getContext() != null)
						? _dictionary.getIDs(
								statement.getSubject(),
								statement.getPredicate(),
								statement.getObject(),
								statement.getContext())
						: _dictionary.getIDs(
								statement.getSubject(),
								statement.getPredicate(),
								statement.getObject());

				_rdfIndexDAO.insertTriple(ids);

				if (_idxRanges && statement.getObject() instanceof Literal) {
					final Literal literal = (Literal) statement.getObject();
					if (NUMERIC_RANGETYPES.contains(literal.getDatatype())) {
						try {

							double value = Double.parseDouble(literal.getLabel());
							_rdfIndexDAO.insertRanges(ids, value);
						} catch (final NumberFormatException exception) {
							_log.error(MessageCatalog._00059_BAD_DOUBLE_VALUE, exception, literal);
						}
					} else if (DATETIME_RANGETYPES.contains(literal.getDatatype())) {
						try {

							long value = Util.parseXMLSchemaDateTimeAsMSecs(literal);
							_rdfIndexDAO.insertRanges(ids, value);
						} catch (final NumberFormatException exception) {
							_log.error(MessageCatalog._00060_BAD_LITERAL_VALUE, exception, literal);
						}
					}
				}
				triples.add(ids);
			}

			_rdfIndexDAO.executePendingMutations();
		}

		notifyListeners(new AddTripleEvent(DUMMY_SOURCE_EVENT, triples));
	}

	/**
	 * Returns an RDF index DAO for this (triple) store.
	 *
	 * @return an RDF index DAO for this store.
	 */
	abstract TripleIndexDAO getRdfIndexDAO();

	/**
	 * Computes the max number of workers (i.e. threads) for bulk operations.
	 *
	 * TODO: 3 hosts have been hardcoded because that number comes from a C* specific class (Cluster)
	 * @return the max number of workers (i.e. threads) for bulk operations.
	 */
	protected int computeWorkersPoolSize() {
		return Runtime.getRuntime().availableProcessors()
				+ (int) Math.max(1, (3 / 1.5));
	}

	@Override
	public long triplesCount() {
		return _selectEstimator.triplesCount();
	}
}


text:
const { app, BrowserWindow, globalShortcut } = require('electron')

function createWindow () {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  win.loadFile('index.html')
}

app.whenReady().then(() => {
  globalShortcut.register('Alt+CommandOrControl+I', () => {
    console.log('Electron loves global shortcuts!')
  })
}).then(createWindow)

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

redpajama_set_name: RedPajamaGithub


text:
class DonationCreatedJob < Struct.new(:donation_id)
  def perform
    donation = Donation.find(donation_id)

    raise 'Unknown donation id' if donation.nil?

    Event.create_donation_event!(donation.user)
  end

  def max_attempts
    3
  end

end


text:
from __future__ import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('at_home', '0001_initial'),
    ]

    operations = [
        migrations.AlterModelOptions(
            name='activity',
            options={'ordering': ['order_number']},
        ),
    ]


text:
<md-sidenav-container style="overflow-y: auto;min-height: 100%">
  <md-sidenav #sidenav _course-sidenav mode="side" disableClose opened="true" align="end"
              (close-start)="toggleIcon($event)" (open-start)="toggleIcon($event)" class="course-sidenav">

        <md-spinner *ngIf="courseEnrollmentStatus === RestStatus.PENDING"></md-spinner>
        <button md-raised-button (click)="enroll()" color="accent" *ngIf="courseEnrollmentStatus !== RestStatus.PENDING">Enroll In Course</button>

      <md-card>

        <md-card-content class="course-contents" fxLayout="column">

            Course Contents

          <tree-root #tree [nodes]="exercises" [focused]="true" [options]="treeOptions"
                     (updateData)="selectExercise(courseNode.exerciseId, courseNode.exerciseSlug)"
                     (onActivate)="selectNode($event)">
            <ng-template #treeNodeTemplate let-node let-index="index">
              <md-icon *ngIf="node.data.submissionState === 'completed'">check_circle</md-icon>
              <md-icon *ngIf="node.data.submissionState === 'pending'">help</md-icon>
              <md-icon *ngIf="!node.data.submissionState">radio_button_unchecked</md-icon>
              <md-icon *ngIf="node.data.submissionState === 'rejected'">error</md-icon>
              {{ node.data.name }}
            </ng-template>
          </tree-root>
        </md-card-content>

      </md-card>
      <md-card class="notes" fxFlex="3 1">
        <md-card-content>

            Kuch important Cheezien

            Iss couse se related saare important resources aapko yahan milenge.

        </md-card-content>
        <md-card-actions fxLayout="row" fxLayoutAlign="center center">
          <button md-raised-button (click)="openDialog()" color="primary">
            DEKHO
          </button>
        </md-card-actions>
      </md-card>
      Apne
        Batch Ka Progress dekho

  </md-sidenav>

    <button (click)="sidenav.toggle()" md-fab class="md-fab-top-right" color="primary">
      <md-icon class="md-24" *ngIf="!iconState">fullscreen</md-icon>
      <md-icon class="md-24" *ngIf="iconState">fullscreen_exit</md-icon>
    </button>

      <router-outlet></router-outlet>

      <button md-raised-button
              (click)="previousExercise()"
              color="primary">Previous
      </button>
      <button md-raised-button
              (click)="nextExercise()"
              color="primary">Next
      </button>

</md-sidenav-container>


text:
const _ = require('lodash');
const baseConfig = require('./base');

const config = {
    baseUrl: 'http://computer-database.herokuapp.com/computers',
    specs: ['../tests/*'],

    multiCapabilities: [{
        browserName: 'firefox',
        firefoxOptions: {
            args: ['--disable-infobars'],
            prefs: {
                'geo.enabled': false,
            },
        },
    }, {
        browserName: 'chrome',
        chromeOptions: {
            args: [
                '--disable-infobars',
            ],
            prefs: {
                'profile.password_manager_enabled': false,
                credentials_enable_service: false,
                password_manager_enabled: false,
            },
        },
    }, /* {
     browserName: "internet explorer",
     platform: "ANY",
     version: "11"
     } */],
    maxSessions: 1 //to run browsers one by one
};

exports.config = _.merge(baseConfig.config, config);


text: Track your spendings and monitor them by reports.


text:
"""cell.actors"""
from functools import partial

import sys
import traceback

from itertools import count
from operator import itemgetter

from kombu import Consumer, Exchange, Queue
from kombu.common import collect_replies, maybe_declare, uuid
from kombu.five import items
from kombu.log import Log
from kombu import serialization
from kombu.pools import producers
from kombu.utils import reprcall, reprkwargs, symbol_by_name
from kombu.utils.encoding import safe_repr
from kombu.utils.functional import maybe_list

from . import __version__
from . import exceptions
from cell.exceptions import WrongNumberOfArguments
from .results import AsyncResult
from .utils import cached_property, enum, shortuuid, setattr_default

__all__ = ['Actor']
BUILTIN_FIELDS = {'ver': __version__}

ACTOR_TYPE = enum(
    DIRECT='direct',
    RR='round-robin',
    SCATTER='scatter',
)

class Actor:
    AsyncResult = AsyncResult

    Error = exceptions.CellError
    Next = exceptions.Next
    NoReplyError = exceptions.NoReplyError
    NoRouteError = exceptions.NoRouteError
    NotBoundError = exceptions.NotBoundError

    #: Actor name.
    #: Defaults to the defined class name.
    name = None

    #: Default exchange(direct) used for messages to this actor.
    exchange = None

    #: Default routing key used if no ``to`` argument passed.
    default_routing_key = None

    #: Delivery mode: persistent or transient. Default is persistent.
    delivery_mode = 'persistent'

    #: Set to True to disable acks.
    no_ack = False

    #: List of calling types this actor should handle.
    #: Valid types are:
    #:
    #:     * direct
    #:         Send the message directly to an agent by exact routing key.
    #:     * round-robin
    #:         Send the message to an agent by round-robin.
    #:     * scatter
    #:         Send the message to all of the agents (broadcast).
    types = (ACTOR_TYPE.DIRECT, ACTOR_TYPE.SCATTER, ACTOR_TYPE.RR)

    #: Default serializer used to send messages and reply messages.
    serializer = 'json'

    #: Default timeout in seconds as a float which after
    #: we give up waiting for replies.
    default_timeout = 5.0

    #: Time in seconds as a float which after replies expires.
    reply_expires = 100.0

    #: Exchange used for replies.
    reply_exchange = Exchange('cl.reply', 'direct')

    #: Exchange used for forwarding/binding with other actors.
    outbox_exchange = None

    #: Exchange used for receiving broadcast commands for this actor type.
    _scatter_exchange = None

    #: Exchange used for round-robin commands for this actor type.
    _rr_exchange = None

    #: Should we retry publishing messages by default?
    #: Default: NO
    retry = None

    #: time-to-live for the actor before becoming Idle
    ttl = 20

    idle = 40

    #: Default policy used when retrying publishing messages.
    #: see :meth:`kombu.BrokerConnection.ensure` for a list
    #: of supported keys.
    retry_policy = {'max_retries': 100,
                    'interval_start': 0,
                    'interval_max': 1,
                    'interval_step': 0.2}

    #: returns the next anonymous ticket number
    #: used fo+r identifying related logs.
    ticket_count = count(1)

    #: Additional fields added to reply messages by default.
    default_fields = {}

    #: Map of calling types and their special routing keys.
    type_to_rkey = {'rr': '__rr__',
                    ACTOR_TYPE.RR: '__rr__',
                    ACTOR_TYPE.SCATTER: '__scatter__'}

    meta = {}
    consumer = None

    class state:
        """Placeholder class for actor's supported methods."""
        pass

    def __init__(self, connection=None, id=None, name=None, exchange=None,
                 logger=None, agent=None, outbox_exchange=None,
                 group_exchange=None, **kwargs):
        self.connection = connection
        self.id = id or uuid()
        self.name = name or self.name or self.__class__.__name__
        self.outbox_exchange = outbox_exchange or self.outbox_exchange
        self.agent = agent

        if self.default_fields is None:
            self.default_fields = {}

        # - setup exchanges and queues
        self.exchange = exchange or self.get_direct_exchange()
        if group_exchange:
            self._scatter_exchange = Exchange(
                group_exchange, 'fanout', auto_delete=True)

        typemap = {
            ACTOR_TYPE.DIRECT: [self.get_direct_queue, self._inbox_direct],
            ACTOR_TYPE.RR: [self.get_rr_queue, self._inbox_rr],
            ACTOR_TYPE.SCATTER: [self.get_scatter_queue, self._inbox_scatter]
        }

        self.type_to_queue = {k: v[0] for k, v in items(typemap)}
        self.type_to_exchange = {k: v[1] for k, v in items(typemap)}

        if not self.outbox_exchange:
            self.outbox_exchange = Exchange(
                'cl.%s.output' % self.name, type='topic',
            )
        # - setup logging
        logger_name = self.name
        if self.agent:
            logger_name = '%s#%s' % (self.name, shortuuid(self.id))
        self.log = Log('!<%s>' % logger_name, logger=logger)
        self.state = self.contribute_to_state(self.construct_state())

        # actor specific initialization.
        self.construct()

    def _add_binding(self, source, routing_key='',
                     inbox_type=ACTOR_TYPE.DIRECT):
        source_exchange = Exchange(**source)
        binder = self.get_binder(inbox_type)
        maybe_declare(source_exchange, self.connection.default_channel)
        binder(exchange=source_exchange, routing_key=routing_key)

    def _remove_binding(self, source, routing_key='',
                        inbox_type=ACTOR_TYPE.DIRECT):
        source_exchange = Exchange(**source)
        unbinder = self.get_unbinder(inbox_type)
        unbinder(exchange=source_exchange, routing_key=routing_key)

    def get_binder(self, type):
        if type == ACTOR_TYPE.DIRECT:
            entity = self.type_to_queue[type]()
        elif type in self.types:
            entity = self.type_to_exchange[type]()
        else:
            raise ValueError('Unsupported type: {0}'.format(type))
        binder = entity.bind_to
        # @TODO: Declare probably should not happened here
        entity.maybe_bind(self.connection.default_channel)
        maybe_declare(entity, entity.channel)
        return binder

    def get_unbinder(self, type):
        if type == ACTOR_TYPE.DIRECT:
            entity = self.type_to_queue[type]()
            unbinder = entity.unbind_from
        else:
            entity = self.type_to_exchange[type]()
            unbinder = entity.exchange_unbind
        entity = entity.maybe_bind(self.connection.default_channel)
        # @TODO: Declare probably should not happened here
        return unbinder

    def add_binding(self, source, routing_key='',
                    inbox_type=ACTOR_TYPE.DIRECT):
        self.call('add_binding', {
            'source': source.as_dict(),
            'routing_key': routing_key,
            'inbox_type': inbox_type,
        }, type=ACTOR_TYPE.DIRECT)

    def remove_binding(self, source, routing_key='',
                       inbox_type=ACTOR_TYPE.DIRECT):
        self.call('remove_binding', {
            'source': source.as_dict(),
            'routing_key': routing_key,
            'inbox_type': inbox_type,
        }, type=ACTOR_TYPE.DIRECT)

    def construct(self):
        """Actor specific initialization."""
        pass

    def construct_state(self):
        """Instantiates the state class of this actor."""
        return self.state()

    def on_agent_ready(self):
        pass

    def contribute_to_object(self, obj, map):
        for attr, value in items(map):
            setattr_default(obj, attr, value)
        return obj

    def contribute_to_state(self, state):
        try:
            contribute = state.contribute_to_state
        except AttributeError:
            # set default state attributes.
            return self.contribute_to_object(state, {
                'actor': self,
                'agent': self.agent,
                'connection': self.connection,
                'log': self.log,
                'Next': self.Next,
                'NoRouteError': self.NoRouteError,
                'NoReplyError': self.NoReplyError,
                'add_binding': self._add_binding,
                'remove_binding': self._remove_binding,
            })
        else:
            return contribute(self)

    def send(self, method, args={}, to=None, nowait=False, **kwargs):
        """Call method on agent listening to ``routing_key``.

        See :meth:`call_or_cast` for a full list of supported
        arguments.

        If the keyword argument `nowait` is false (default) it
        will block and return the reply.
j
        """

        if to is None:
            to = self.routing_key
        r = self.call_or_cast(method, args, routing_key=to,
                              nowait=nowait, **kwargs)
        if not nowait:
            return r.get()

    def throw(self, method, args={}, nowait=False, **kwargs):
        """Call method on one of the agents in round robin.

        See :meth:`call_or_cast` for a full list of supported
        arguments.

        If the keyword argument `nowait` is false (default) it
        will block and return the reply.

        """
        r = self.call_or_cast(method, args, type=ACTOR_TYPE.RR,
                              nowait=nowait, **kwargs)
        if not nowait:
            return r

    def scatter(self, method, args={}, nowait=False, timeout=None, **kwargs):
        """Broadcast method to all agents.

        if nowait is False, returns generator to iterate over the results.

        :keyword limit: Limit number of reads from the queue.
            Unlimited by default.
        :keyword timeout: the timeout (in float seconds) waiting for replies.
            Default is :attr:`default_timeout`.

         **Examples**

        ``scatter`` is a generator (if nowait is False)::
            >>> res = scatter()
            >>> res.next() # one event consumed, or timed out.

            >>> res = scatter(limit=2):
            >>> for i in res:  # two events consumed or timeout
            >>>     pass

        See :meth:`call_or_cast` for a full list of supported
        arguments.

        """
        timeout = timeout if timeout is not None else self.default_timeout
        r = self.call_or_cast(method, args, type=ACTOR_TYPE.SCATTER,
                              nowait=nowait, timeout=timeout, **kwargs)
        if not nowait:
            return r.gather(timeout=timeout, **kwargs)

    def call_or_cast(self, method, args={}, nowait=False, **kwargs):
        """Apply remote `method` asynchronously or synchronously depending
        on the value of `nowait`.

        :param method: The name of the remote method to perform.
        :param args: Dictionary of arguments for the method.
        :keyword nowait: If false the call will block until the result
           is available and return it (default), if true the call will be
           non-blocking and no result will be returned.
        :keyword retry: If set to true then message sending will be retried
          in the event of connection failures. Default is decided by the
          :attr:`retry` attributed.
        :keyword retry_policy: Override retry policies.
           See :attr:`retry_policy`.  This must be a dictionary, and keys will
           be merged with the default retry policy.
        :keyword timeout: Timeout to wait for replies in seconds as a float
           (**only relevant in blocking mode**).
        :keyword limit: Limit number of replies to wait for
           (**only relevant in blocking mode**).
        :keyword callback: If provided, this callback will be called for every
          reply received (**only relevant in blocking mode**).
        :keyword \*\*props: Additional message properties.
           See :meth:`kombu.Producer.publish`.

        """
        return (nowait and self.cast or self.call)(method, args, **kwargs)

    def get_scatter_exchange(self):
        """Returns a :class:'kombu.Exchange' for type fanout"""
        return Exchange('cl.scatter.%s' % self.name, 'fanout',
                        auto_delete=True)

    def get_rr_exchange(self):
        """Returns a :class:'kombu.Exchange' instance with type set to fanout.
         The exchange is used for sending in a round-robin style"""
        return Exchange('cl.rr.%s' % self.name, 'fanout', auto_delete=True)

    def get_direct_exchange(self):
        """Returns a :class:'kombu.Exchange' with type direct"""
        return Exchange('cl.%s' % self.name, 'direct', auto_delete=True)

    def get_queues(self):
        return [self.type_to_queue[type]() for type in self.types]

    def get_direct_queue(self):
        """Returns a :class: `kombu.Queue` instance to be used to listen
         for messages send to this specific Actor instance"""
        return Queue(self.id, self.inbox_direct, routing_key=self.routing_key,
                     auto_delete=True)

    def get_scatter_queue(self):
        """Returns a :class: `kombu.Queue` instance for receiving broadcast
        commands for this actor type."""
        return Queue('%s.%s.scatter' % (self.name, self.id),
                     self.inbox_scatter, auto_delete=True)

    def get_rr_queue(self):
        """Returns a :class: `kombu.Queue` instance for receiving round-robin
        commands for this actor type."""
        return Queue(self.inbox_rr.name + '.rr', self.inbox_rr,
                     auto_delete=True)

    def get_reply_queue(self, ticket):
        return Queue(ticket, self.reply_exchange, ticket, auto_delete=True,
                     queue_arguments={
                         'x-expires': int(self.reply_expires * 1000)})

    def Consumer(self, channel, **kwargs):
        """Returns a :class:`kombu.Consumer` instance for this Actor"""
        kwargs.setdefault('no_ack', self.no_ack)
        return Consumer(channel, self.get_queues(),
                        callbacks=[self.on_message], **kwargs)

    def emit(self, method, args={}, retry=None):
        return self.cast(method, args, retry=retry, exchange=self.outbox)

    def cast(self, method, args={}, declare=None, retry=None,
             retry_policy=None, type=None, exchange=None, **props):
        """Send message to actor.  Discarding replies."""
        retry = self.retry if retry is None else retry
        body = {'class': self.name, 'method': method, 'args': args}

        _retry_policy = self.retry_policy
        if retry_policy:  # merge default and custom policies.
            _retry_policy = dict(_retry_policy, **retry_policy)

        if type and type not in self.types:
            raise ValueError('Unsupported type: {0}'.format(type))
        elif not type:
            type = ACTOR_TYPE.DIRECT

        props.setdefault('routing_key', self.routing_key)
        props.setdefault('serializer', self.serializer)
        exchange = exchange or self.type_to_exchange[type]()
        declare = (maybe_list(declare) or []) + [exchange]
        with producers[self._connection].acquire(block=True) as producer:
            return producer.publish(body, exchange=exchange, declare=declare,
                                    retry=retry, retry_policy=retry_policy,
                                    **props)

    def call(self, method, args={}, retry=False, retry_policy=None,
             ticket=None, **props):
        """Send message to the same actor and return :class:`AsyncResult`."""
        ticket = ticket or uuid()
        reply_q = self.get_reply_queue(ticket)
        self.cast(method, args, declare=[reply_q], reply_to=ticket, **props)
        return self.AsyncResult(ticket, self)

    def handle_cast(self, body, message):
        """Handle cast message."""
        self._DISPATCH(body)

    def handle_call(self, body, message):
        """Handle call message."""
        try:
            r = self._DISPATCH(body, ticket=message.properties['reply_to'])
        except self.Next:
            # don't reply, delegate to other agents.
            pass
        else:
            self.reply(message, r)

    def reply(self, req, body, **props):
        with producers[self._connection].acquire(block=True) as producer:
            content_type = req.content_type
            serializer = serialization.registry.type_to_name[content_type]
            return producer.publish(
                body,
                declare=[self.reply_exchange],
                routing_key=req.properties['reply_to'],
                correlation_id=req.properties.get('correlation_id'),
                serializer=serializer,
                **props
            )

    def on_message(self, body, message):
        self.agent.process_message(self, body, message)

    def _on_message(self, body, message):
        """What to do when a message is received.

        This is a kombu consumer callback taking the standard
        ``body`` and ``message`` arguments.

        Note that if the properties of the message contains
        a value for ``reply_to`` then a proper implementation
        is expected to send a reply.

        """
        if message.properties.get('reply_to'):
            handler = self.handle_call
        else:
            handler = self.handle_cast

        def handle():
            # Do not ack the message if an exceptional error occurs,
            # but do ack the message if SystemExit or KeyboardInterrupt
            # is raised, as this is probably intended.
            try:
                handler(body, message)
            except Exception:
                raise
            except BaseException:
                message.ack()
                raise
            else:
                message.ack()
        handle()

    def _collect_replies(self, conn, channel, ticket, *args, **kwargs):
        kwargs.setdefault('timeout', self.default_timeout)

        if 'limit' not in kwargs and self.agent:
            kwargs['limit'] = self.agent.get_default_scatter_limit()
        if 'ignore_timeout' not in kwargs and not kwargs.get('limit', None):
            kwargs.setdefault('ignore_timeout', False)

        return collect_replies(conn, channel, self.get_reply_queue(ticket),
                               *args, **kwargs)

    def lookup_action(self, name):
        try:
            if not name:
                method = self.default_receive
            else:
                method = getattr(self.state, name)
        except AttributeError:
            raise KeyError(name)
        if not callable(method) or name.startswith('_'):
            raise KeyError(method)
        return method

    def default_receive(self, msg_body):
        """Override in the derived classes."""
        pass

    def _DISPATCH(self, body, ticket=None):
        """Dispatch message to the appropriate method
        in :attr:`state`, handle possible exceptions,
        and return a response suitable to be used in a reply.

        To protect from calling special methods it does not dispatch
        method names starting with underscore (``_``).

        This returns the return value or exception error
        with defaults fields in a suitable format to be used
        as a reply.

        The exceptions :exc:`SystemExit` and :exc:`KeyboardInterrupt`
        will not be handled, and will propagate.

        In the case of a successful call the return value will
        be::

            {'ok': return_value, **default_fields}

        If the method raised an exception the return value
        will be::

            {'nok': [repr exc, str traceback], **default_fields}

        :raises KeyError: if the method specified is unknown
        or is a special method (name starting with underscore).

        """
        if ticket:
            sticket = '%s' % (shortuuid(ticket), )
        else:
            ticket = sticket = str(next(self.ticket_counter))
        try:
            method, args = itemgetter('method', 'args')(body)
            self.log.info('#%s --> %s',
                          sticket, self._reprcall(method, args))
            act = self.lookup_action(method)
            r = {'ok': act(args or {})}
            self.log.info('#%s <-- %s', sticket, reprkwargs(r))
        except self.Next:
            raise
        except Exception as exc:
            einfo = sys.exc_info()
            r = {'nok': [safe_repr(exc), self._get_traceback(einfo)]}
            self.log.error('#%s <-- nok=%r', sticket, exc)
        return dict(self._default_fields, **r)

    def _get_traceback(self, exc_info):
        return ''.join(traceback.format_exception(*exc_info))

    def _reprcall(self, method, args):
        return '%s.%s' % (self.name, reprcall(method, (), args))

    def bind(self, connection, agent=None):
        return self.__class__(connection, self.id,
                              self.name, self.exchange, agent=agent)

    def is_bound(self):
        return self.connection is not None

    def __copy__(self):
        cls, args = self.__reduce__()
        return cls(*args)

    def __reduce__(self):
        return (self.__class__, (self.connection, self.id,
                                 self.name, self.exchange))

    @property
    def outbox(self):
        return self.outbox_exchange

    def _inbox_rr(self):
        if not self._rr_exchange:
            self._rr_exchange = self.get_rr_exchange()
        return self._rr_exchange

    @property
    def inbox_rr(self):
        return self._inbox_rr()

    def _inbox_direct(self):
        return self.exchange

    @property
    def inbox_direct(self):
        return self._inbox_direct()

    def _inbox_scatter(self):
        if not self._scatter_exchange:
            self._scatter_exchange = self.get_scatter_exchange()
        return self._scatter_exchange

    @property
    def inbox_scatter(self):
        return self._inbox_scatter()

    @property
    def _connection(self):
        if not self.is_bound():
            raise self.NotBoundError('Actor is not bound to any connection.')
        return self.connection

    @cached_property
    def _default_fields(self):
        return dict(BUILTIN_FIELDS, **self.default_fields)

    @property
    def routing_key(self):
        if self.default_routing_key:
            return self.default_routing_key
        else:
            return self.id

class ActorProxy:
    """An actor wrapper that represents an actor started remotely.

        ActroProxy is created as a result of spawning an Actor.
        The :py:meth:`~agents.dAgent.spawn` returns an instance of ActorProxy

    *Examples*

    .. code-block:: python

        class GreetingActor(Actor):
            class state:
                def greet(who = 'world'):
                    print 'hello %s' %who

        gr_proxy = agent.spawns(GreetingActor)

        # All of the below are valid calls for gr_proxy
        gr_proxy.call.greet()
        gr_proxy.call.greet({'who':'Foo'})
        gr_proxy.throw.greet()
        gr_proxy.scatter.greet()
    """

    def __init__(self, name, id, async_start_result=None, **kwargs):
        kwargs.update({'id': id})
        self._actor = symbol_by_name(name)(**kwargs)
        self.id = self._actor.id
        self.async_start_result = async_start_result

    class state:
        def __init__(self, parent, id, func):
            self.parent = parent
            self.id = id
            self.func = func

        def __call__(self, *args, **kw):
            if not args:
                raise WrongNumberOfArguments(
                    'No arguments given to %s' % self.func)
            try:
                meth = getattr(self.parent.state, args[0]).__name__
            except AttributeError:
                if kw.get('typed', True):
                    raise
                else:
                    meth = args[0]
            return self.func(meth, *args[1:], **kw)

        def __getattr__(self, name):
            return partial(
                self.func, getattr(self.parent.state, name).__name__)

    @cached_property
    def call(self):
        return self.state(self._actor, self.id, self._actor.call)

    @cached_property
    def throw(self):
        return self.state(self._actor, self.id, self._actor.throw)

    @cached_property
    def send(self):
        return self.state(self._actor, self.id, self._actor.send)

    @cached_property
    def scatter(self):
        return self.state(self._actor, self.id, self._actor.scatter)

    def __getattr__(self, name):
        return getattr(self._actor, name)

    # Notify when the actor is started
    def wait_to_start(self, **kwargs):
        return self.async_start_result.result(**kwargs)


text:
#import <UIKit/UIKit.h>

@interface SCAnimatingCGViewController : UIViewController

@property (weak, nonatomic) IBOutlet UIView *arrowContainer;
- (IBAction)handleCreateArrowsButtonPressed:(id)sender;

@end


text:
package org.openehealth.ipf.platform.camel.test.performance.process;

import static org.apache.commons.lang3.Validate.notNull;

import java.util.Date;
import java.util.concurrent.TimeUnit;

import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.Processor;
import org.openehealth.ipf.commons.test.performance.Measurement;
import org.openehealth.ipf.commons.test.performance.MeasurementHistory;
import org.openehealth.ipf.commons.test.performance.Timestamp;
import org.openehealth.ipf.commons.test.performance.dispatcher.MeasurementDispatcher;

import static org.openehealth.ipf.commons.test.performance.utils.MeasurementHistoryXMLUtils.marshall;
import static org.openehealth.ipf.commons.test.performance.utils.MeasurementHistoryXMLUtils.unmarshall;

/**
 *
 * Puts a MeasurementHistory in the inbound message header, with a
 * measurement with time the result of {@link #getCurrentTimestamp()}, on
 * {@link #process(Exchange)}. Provides methods for modification and access of
 * the measurement history object, in the inbound message header of the
 * exchange. The measurement history object is stored as a String.
 *
 * @author Mitko Kolev
 */
public class TimeProcessor implements Processor {

    public static final String MEASUREMENT_HISTORY_HEADER_KEY = "performance.measurement.history";

    private MeasurementDispatcher dispatcher;

    /*
     * (non-Javadoc)
     *
     * @see org.apache.camel.Processor#process(org.apache.camel.Exchange)
     */
    @Override
    public void process(Exchange exchange) throws Exception {
        notNull(exchange, "The exchange must not be null!");
        Date now = new Date();
        Measurement measurement = new Measurement(getCurrentTimestamp());

        MeasurementHistory history = getMeasurementHistoryFromMessageHeader(exchange);
        if (history == null) {// the first time
            history = new MeasurementHistory(now);
            history.add(measurement);
            enrichMessageHeaderWithMeasurementHistory(exchange, history);
        } else {
            history.add(measurement);
            enrichMessageHeaderWithMeasurementHistory(exchange, history);
        }
    }

    /**
     * @return a
     *         Timestamp object with value System.nanoTime() - the best system precision.
     *
     */
    public Timestamp getCurrentTimestamp() {
        return new Timestamp(System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    /**
     * Returns the MeasurementHistory object contained in the
     * inbound message header with name {@link #MEASUREMENT_HISTORY_HEADER_KEY}.
     * The initial MeasurementHistory object in the message header
     * must be created from a TimeProcessor. Note that some Camel
     * components filter some message headers (for example the JMS camel
     * component filters headers with raw Java serializable values).
     *
     * @param exchange
     *            the exchange that contains the measurement history object.
     * @return a measurement history object, if such exists in the inbound
     *         message header. If no header with name
     *         {@link #MEASUREMENT_HISTORY_HEADER_KEY} is found, returns null
     */
    public MeasurementHistory getMeasurementHistory(Exchange exchange) {
        notNull(exchange, "The exchange must not be null!");
        return getMeasurementHistoryFromMessageHeader(exchange);
    }

    protected void enrichMessageHeaderWithMeasurementHistory(Exchange exchange,
            MeasurementHistory measurementHistory) {
        exchange.getIn().removeHeader(MEASUREMENT_HISTORY_HEADER_KEY);
        String measurementHistoryString = marshall(measurementHistory);
        exchange.getIn().setHeader(MEASUREMENT_HISTORY_HEADER_KEY,
                measurementHistoryString);

    }

    protected void removeMeasurementHistoryHeader(Exchange exchange) {
        exchange.getIn().removeHeader(MEASUREMENT_HISTORY_HEADER_KEY);
    }

    protected MeasurementHistory getMeasurementHistoryFromMessageHeader(
            Exchange exchange) {
        Message inMessage = exchange.getIn();

        String measurementHistoryXML = (String) inMessage
                .getHeader(MEASUREMENT_HISTORY_HEADER_KEY);
        if (measurementHistoryXML == null) {
            return null;
        } else {
            return unmarshall(measurementHistoryXML);
        }
    }

    /**
     * Sets the MeasurementDispatcher, which will be used by the
     * processor subclasses to dispatch their measurement histories.
     *
     * @param dispatcher
     *            a MeasurementDispatcher instance
     */
    public void setMeasurementDispatcher(MeasurementDispatcher dispatcher) {
        notNull(dispatcher, "The dispatcher must not be null!");
        this.dispatcher = dispatcher;
    }

    /**
     * @return the contained MeasurementDispatcher instance.
     */
    public MeasurementDispatcher getMeasurementDispatcher() {
        return dispatcher;
    }
}


text:
import unittest
import mock
import requests
from mock import patch
from requests import exceptions as req_exc

from oslo_serialization import jsonutils

from infoblox_client import connector
from infoblox_client import exceptions

class TestInfobloxConnector(unittest.TestCase):
    def setUp(self):
        super(TestInfobloxConnector, self).setUp()

        self.default_opts = self._prepare_options()
        self.connector = connector.Connector(self.default_opts)

    @staticmethod
    def _prepare_options():
        opts = mock.Mock()
        opts.host = 'infoblox.example.org'
        opts.wapi_version = '1.1'
        opts.username = 'admin'
        opts.password = 'password'
        opts.ssl_verify = False
        opts.silent_ssl_warnings = True
        opts.http_pool_connections = 10
        opts.http_pool_maxsize = 10
        opts.http_request_timeout = 10
        opts.max_retries = 3
        opts.max_results = None
        return opts

    def test_create_object(self):
        objtype = 'network'
        payload = {'ip': '0.0.0.0'}

        with patch.object(requests.Session, 'post',
                          return_value=mock.Mock()) as patched_create:
            patched_create.return_value.status_code = 201
            patched_create.return_value.content = '{}'
            self.connector.create_object(objtype, payload)
            patched_create.assert_called_once_with(
                'https://infoblox.example.org/wapi/v1.1/network',
                data=jsonutils.dumps(payload),
                headers=self.connector.DEFAULT_HEADER,
                timeout=self.default_opts.http_request_timeout,
            )

    def test_create_object_with_extattrs(self):
        objtype = 'network'
        payload = {'extattrs': {'Subnet ID': {'value': 'fake_subnet_id'}},
                   'ip': '0.0.0.0'}
        with patch.object(requests.Session, 'post',
                          return_value=mock.Mock()) as patched_create:
            patched_create.return_value.status_code = 201
            patched_create.return_value.content = '{}'
            self.connector.create_object(objtype, payload)
            patched_create.assert_called_once_with(
                'https://infoblox.example.org/wapi/v1.1/network',
                data=jsonutils.dumps(payload),
                headers=self.connector.DEFAULT_HEADER,
                timeout=self.default_opts.http_request_timeout,
            )

    def test_create_object_raises_member_assigned(self):
        nios_error = (
            '{ "Error": "AdmConDataError: None (IBDataConflictError:'
            'IB.Data.Conflict:Member 10.39.12.91 is assigned to another '
            'network view \'test2\')",'
            '"code": "Client.Ibap.Data.Conflict",'
            '"text": "Member 10.39.12.91 is assigned to another '
            'network view \'test2\'"}')
        with patch.object(requests.Session, 'post',
                          return_value=mock.Mock()) as patched_create:
            patched_create.return_value.status_code = 400
            patched_create.return_value.content = nios_error
            self.assertRaises(exceptions.InfobloxMemberAlreadyAssigned,
                              self.connector.create_object,
                              'network', {'network': '192.178.1.0/24'})

    def test_get_object(self):
        objtype = 'network'
        payload = {'ip': '0.0.0.0'}

        with patch.object(requests.Session, 'get',
                          return_value=mock.Mock()) as patched_get:
            patched_get.return_value.status_code = 200
            patched_get.return_value.content = '{}'
            self.connector.get_object(objtype, payload)
            patched_get.assert_called_once_with(
                'https://infoblox.example.org/wapi/v1.1/network?ip=0.0.0.0',
                headers=self.connector.DEFAULT_HEADER,
                timeout=self.default_opts.http_request_timeout,
            )

    def test_get_objects_with_extattrs(self):
        objtype = 'network'
        payload = {'ip': '0.0.0.0'}
        extattrs = {
            'Subnet ID': {'value': 'fake_subnet_id'}
        }
        with patch.object(requests.Session, 'get',
                          return_value=mock.Mock()) as patched_get:
            patched_get.return_value.status_code = 200
            patched_get.return_value.content = '{}'
            self.connector.get_object(objtype, payload, extattrs=extattrs)
            patched_get.assert_called_once_with(
                'https://infoblox.example.org/wapi/'
                'v1.1/network?*Subnet ID=fake_subnet_id&ip=0.0.0.0',
                headers=self.connector.DEFAULT_HEADER,
                timeout=self.default_opts.http_request_timeout,
            )

    def test_get_objects_with_max_results(self):
        objtype = 'network'
        with patch.object(requests.Session, 'get',
                          return_value=mock.Mock()) as patched_get:
            patched_get.return_value.status_code = 200
            patched_get.return_value.content = '{}'
            self.connector.get_object(objtype, {}, max_results=20)
            patched_get.assert_called_once_with(
                'https://infoblox.example.org/wapi/'
                'v1.1/network?_max_results=20',
                headers=self.connector.DEFAULT_HEADER,
                timeout=self.default_opts.http_request_timeout,
            )

    def test_get_objects_with_max_results_as_connector_opt(self):
        objtype = 'network'
        with patch.object(requests.Session, 'get',
                          return_value=mock.Mock()) as patched_get:
            patched_get.return_value.status_code = 200
            patched_get.return_value.content = '{}'

            opts = self._prepare_options()
            opts.max_results = 10
            conn = connector.Connector(opts)
            conn.get_object(objtype, {})
            patched_get.assert_called_once_with(
                'https://infoblox.example.org/wapi/'
                'v1.1/network?_max_results=10',
                headers=self.connector.DEFAULT_HEADER,
                timeout=self.default_opts.http_request_timeout,
            )

    def test_max_results_priority(self):
        objtype = 'network'
        with patch.object(requests.Session, 'get',
                          return_value=mock.Mock()) as patched_get:
            patched_get.return_value.status_code = 200
            patched_get.return_value.content = '{}'

            opts = self._prepare_options()
            opts.max_results = 10
            conn = connector.Connector(opts)
            # max_results passed to get_object should have higher priority
            # over max_results connector option
            conn.get_object(objtype, {}, max_results=-20)
            patched_get.assert_called_once_with(
                'https://infoblox.example.org/wapi/'
                'v1.1/network?_max_results=-20',
                headers=self.connector.DEFAULT_HEADER,
                timeout=self.default_opts.http_request_timeout,
            )

    def test_update_object(self):
        ref = 'network'
        payload = {'ip': '0.0.0.0'}

        with patch.object(requests.Session, 'put',
                          return_value=mock.Mock()) as patched_update:
            patched_update.return_value.status_code = 200
            patched_update.return_value.content = '{}'
            self.connector.update_object(ref, payload)
            patched_update.assert_called_once_with(
                'https://infoblox.example.org/wapi/v1.1/network',
                data=jsonutils.dumps(payload),
                headers=self.connector.DEFAULT_HEADER,
                timeout=self.default_opts.http_request_timeout,
            )

    def test_delete_object(self):
        ref = 'network'
        with patch.object(requests.Session, 'delete',
                          return_value=mock.Mock()) as patched_delete:
            patched_delete.return_value.status_code = 200
            patched_delete.return_value.content = '{}'
            self.connector.delete_object(ref)
            patched_delete.assert_called_once_with(
                'https://infoblox.example.org/wapi/v1.1/network',
                headers=self.connector.DEFAULT_HEADER,
                timeout=self.default_opts.http_request_timeout,
            )

    def test_construct_url_absolute_path_fails(self):
        pathes = ('/starts_with_slash', '', None)
        for path in pathes:
            self.assertRaises(ValueError,
                              self.connector._construct_url, path)

    def test_construct_url_with_query_params_and_extattrs(self):
        query_params = {'some_option': 'some_value'}
        ext_attrs = {'Subnet ID': {'value': 'fake_subnet_id'}}
        url = self.connector._construct_url('network',
                                            query_params=query_params,
                                            extattrs=ext_attrs)
        self.assertEqual('https://infoblox.example.org/wapi/v1.1/network?'
                         '*Subnet ID=fake_subnet_id&some_option=some_value',
                         url)

    def test_construct_url_with_force_proxy(self):
        ext_attrs = {'Subnet ID': {'value': 'fake_subnet_id'}}
        url = self.connector._construct_url('network',
                                            extattrs=ext_attrs,
                                            force_proxy=True)
        self.assertEqual('https://infoblox.example.org/wapi/v1.1/network?'
                         '*Subnet ID=fake_subnet_id&_proxy_search=GM',
                         url)

    def test_get_object_with_proxy_flag(self):
        self.connector._get_object = mock.MagicMock(return_value=False)
        self.connector._construct_url = mock.MagicMock()
        self.connector.cloud_api_enabled = True

        result = self.connector.get_object('network', force_proxy=True)

        self.assertEqual(None, result)
        self.connector._construct_url.assert_called_with('network', {},
                                                         None, True)
        self.connector._get_object.called_with('network',
                                               self.connector._construct_url)

    def test_get_object_without_proxy_flag(self):
        self.connector._get_object = mock.MagicMock(return_value=False)
        self.connector._construct_url = mock.MagicMock()
        self.connector.cloud_api_enabled = True

        result = self.connector.get_object('network')

        self.assertEqual(None, result)
        construct_calls = [mock.call('network', {}, None, False),
                           mock.call('network', {}, None, force_proxy=True)]
        self.connector._construct_url.assert_has_calls(construct_calls)

    def test__get_object_search_error_return_none(self):
        response = mock.Mock()
        response.status_code = '404'
        response.content = 'Object not found'
        self.connector.session = mock.Mock()
        self.connector.session.get.return_value = response

        url = 'http://some-url/'
        self.assertEqual(None, self.connector._get_object('network', url))

class TestInfobloxConnectorStaticMethods(unittest.TestCase):
    def test_neutron_exception_is_raised_on_any_request_error(self):
        # timeout exception raises InfobloxTimeoutError
        f = mock.Mock()
        f.__name__ = 'mock'
        f.side_effect = req_exc.Timeout
        self.assertRaises(exceptions.InfobloxTimeoutError,
                          connector.reraise_neutron_exception(f))

        # all other request exception raises InfobloxConnectionError
        supported_exceptions = [req_exc.HTTPError,
                                req_exc.ConnectionError,
                                req_exc.ProxyError,
                                req_exc.SSLError,
                                req_exc.TooManyRedirects,
                                req_exc.InvalidURL]

        for ex in supported_exceptions:
            f.side_effect = ex
            self.assertRaises(exceptions.InfobloxConnectionError,
                              connector.reraise_neutron_exception(f))

    def test_exception_raised_for_non_authorized(self):
        response = mock.Mock()
        response.status_code = requests.codes.UNAUTHORIZED
        self.assertRaises(exceptions.InfobloxBadWAPICredential,
                          connector.Connector._validate_authorized,
                          response)

    def test_no_exceptions_for_ok_statuses(self):
        response = mock.Mock()
        ok_statuses = (requests.codes.OK,
                       requests.codes.CREATED,
                       requests.codes.ACCEPTED)
        for status_code in ok_statuses:
            response.status_code = status_code
            connector.Connector._validate_authorized(response)

    def test_non_cloud_api_detection(self):
        wapi_not_cloud = ('1.4.1', '1.9/', '1.99', 'asd', 'v1.4')
        for url in wapi_not_cloud:
            self.assertFalse(connector.Connector.is_cloud_wapi(url))

    def test_cloud_api_detection(self):
        wapi_cloud = ('2.1/', '/2.0/', '2.0.1',
                      '3.0/', '11.0.1/', 'v2.1', 'v2.0')
        for url in wapi_cloud:
            self.assertTrue(connector.Connector.is_cloud_wapi(url))

    def test_allow_options_as_dict(self):
        opts = dict(host='infoblox.example.org',
                    wapi_version='1.1',
                    username='admin',
                    password='password',
                    ssl_verify=False,
                    silent_ssl_warnings=True,
                    max_results=50,
                    http_pool_connections=10,
                    http_pool_maxsize=10,
                    http_request_timeout=10)
        conn = connector.Connector(opts)
        self.assertEqual(opts['host'], conn.host)
        self.assertEqual(opts['wapi_version'], conn.wapi_version)
        self.assertEqual(opts['username'], conn.username)
        self.assertEqual(opts['password'], conn.password)
        self.assertEqual(opts['ssl_verify'], conn.ssl_verify)
        self.assertEqual(opts['silent_ssl_warnings'],
                         conn.silent_ssl_warnings)
        self.assertEqual(opts['max_results'],
                         conn.max_results)
        self.assertEqual(opts['http_pool_connections'],
                         conn.http_pool_connections)
        self.assertEqual(opts['http_pool_maxsize'], conn.http_pool_maxsize)
        self.assertEqual(opts['http_request_timeout'],
                         conn.http_request_timeout)

    def test_incomplete_options_raises_exception(self):
        opts = dict(host='infoblox.example.org',
                    wapi_version='1.1')
        self.assertRaises(exceptions.InfobloxConfigException,
                          connector.Connector, opts)

    def test_default_options(self):
        opts = dict(host='infoblox.example.org',
                    username='admin',
                    password='password')
        conn = connector.Connector(opts)
        self.assertEqual(False, conn.ssl_verify)
        self.assertEqual(False, conn.silent_ssl_warnings)
        self.assertEqual(10, conn.http_request_timeout)
        self.assertEqual(10, conn.http_pool_connections)
        self.assertEqual(10, conn.http_pool_maxsize)
        self.assertEqual(3, conn.max_retries)
        self.assertEqual('1.4', conn.wapi_version)
        self.assertEqual(None, conn.max_results)

    def test_blank_values_not_allowed(self):
        base_dict = {'host': '192.168.1.15',
                     'username': 'admin',
                     'password': 'pass'}
        for field in base_dict:
            test_dict = base_dict.copy()
            test_dict[field] = None
            self.assertRaises(exceptions.InfobloxConfigException,
                              connector.Connector, test_dict)

    def test_is_cloud_wapi_raises_exception(self):
        for value in (None, '', 0, 1, self, 1.2):
            self.assertRaises(ValueError,
                              connector.Connector.is_cloud_wapi,
                              value)

    def test__parse_reply_raises_connection_error(self):
        request = mock.Mock()
        request.content = (''
                           'Some error reply\n')
        self.assertRaises(exceptions.InfobloxConnectionError,
                          connector.Connector._parse_reply,
                          request)

    def test__parse_reply(self):
        request = mock.Mock()
        request.content = (
            '[{"_ref": "network/ZG5zLm5ldHdvcmskMTAuNDAuMjUuMC8yNC8w:'
            '10.40.25.0/24/default","network": "10.40.25.0/24",'
            '"network_view": "default"}]')
        expected_reply = [
            {'_ref': "network/ZG5zLm5ldHdvcmskMTAuNDAuMjUuMC8yNC8w"
                     ":10.40.25.0/24/default",
             'network': "10.40.25.0/24",
             'network_view': "default"}]

        parsed_reply = connector.Connector._parse_reply(request)
        self.assertEqual(expected_reply, parsed_reply)


text:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
    }

	public function index()
	{
        if (!isset($_SESSION['logged_in']))
        {
            $this->load->view('login/login');
        }
        else {

            if ((($_SESSION['level']) == 'admin')) {
                $this->load->view('admin/admin');
            }
            else {
                $this->load->view('login/login');
            }
        }
	}
    public function patients(){
        $this->load->view('admin/patient/index');
    }
    public function prescription(){
        $this->load->view('admin/prescription/index');
    }

    public function addPatients()
    {

        $data['patients'] = "";
        $this->load->view('admin/patient/addPatients');

    }

    public function addPatientInfo(){

        if(
            $this->input->post('name') != "" &&
            $this->input->post('age') != "" &&
            $this->input->post('occupation') != "" &&
            $this->input->post('contact') != "" &&
            $this->input->post('address') != "" &&
            $this->input->post('gender') != ""
        )
        {
            $data['name'] = $this->input->post('name');
            $data['age'] = $this->input->post('age');
            $data['contact'] = $this->input->post('contact');
            $data['address'] = $this->input->post('address');
            $data['gender'] = $this->input->post('gender');
            $data['occupation'] = $this->input->post('occupation');

            $this->Patients_model->insert_patient($data);

        }
        else{

        }
       redirect("admin");

    }

    public function PatientInfo(){
        $patients = $this->Patients_model->get_all_patients();
        $data['patients'] = $patients;
        $this->load->view('admin/patient/PatientInfo', $data);
    }
    public function editPatientInfo(){

        if(
            $this->input->post('id') != "" &&
            $this->input->post('name') != "" &&
            $this->input->post('age') != "" &&
            $this->input->post('occupation') != "" &&
            $this->input->post('contact') != "" &&
            $this->input->post('address') != "" &&
           $this->input->post('date') != "" &&
            $this->input->post('gender') != ""
        )
        {
            $data['id'] = $this->input->post('id');
            $data['name'] = $this->input->post('name');
            $data['age'] = $this->input->post('age');
            $data['contact'] = $this->input->post('contact');
            $data['address'] = $this->input->post('address');
            $data['gender'] = $this->input->post('gender');
            $data['occupation'] = $this->input->post('occupation');
            $data['date'] = $this->input->post('date');

            $this->Patients_model->edit_patient($data);

        }
        else{

        }
        redirect('admin','refresh');

    }

    public function DeletePatient(){
        $id=$_POST['ID'];
        $this->Patients_model->delete_patient($id);
    }
}


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

namespace Magpie.Compilation
{
    /// <summary>
    /// A named type declaration.
    /// </summary>
    public class NamedType : IUnboundDecl
    {
        public Position Position { get; private set; }

        public string Name { get; private set; }
        public IUnboundDecl[] TypeArgs { get { return mTypeArgs; } }

        public bool IsGeneric { get { return mTypeArgs.Length > 0; } }

        public NamedType(string name)
        {
            Position = Position.None;
            Name = name;
            mTypeArgs = new IUnboundDecl[0];
        }

        public NamedType(string name, IEnumerable<IUnboundDecl> typeArgs)
        {
            Position = Position.None;
            Name = name;
            mTypeArgs = typeArgs.ToArray();
        }

        public NamedType(Position position, string name, IEnumerable<IUnboundDecl> typeArgs)
        {
            Position = position;
            Name = name;
            if (typeArgs != null)
            {
                mTypeArgs = typeArgs.ToArray();
            }
        }

        public override string ToString()
        {
            if (mTypeArgs.Length > 0) return Name + "[" + mTypeArgs.JoinAll(", ") + "]";

            return Name;
        }

        #region IUnboundDecl Members

        TReturn IUnboundDecl.Accept<TReturn>(IUnboundDeclVisitor<TReturn> visitor)
        {
            return visitor.Visit(this);
        }

        #endregion

        private IUnboundDecl[] mTypeArgs;
    }
}


text:
<?php

/**
 * FILE: model.php
 *
 * @AUTHOR: LTD shalvasoft
 * @AUTHOR: Shalva Kvaratskhelia
 * PROJECT: MVC
 * VERSION: 1.0.0
 */

    class model	implements interfaces\model_interface{

        /**
         * connecting to database
         *
         * @return database
         */
        public function db (){
            return new database();
        }
    }