text:
<?php declare(strict_types=1);

namespace Php\Cli;

use Php;
use Symfony\Component\Console\Exception\LogicException;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * Merge capabilities of input and output interfaces
 */
class IO extends SymfonyStyle
{
    /**
     * @var int
     */
    public const VERBOSITY =
        self::VERBOSITY_QUIET |
        self::VERBOSITY_NORMAL |
        self::VERBOSITY_VERBOSE |
        self::VERBOSITY_VERY_VERBOSE |
        self::VERBOSITY_DEBUG;

    /**
     * @var InputInterface
     */
    private $inputInterface;

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     */
    public function __construct(InputInterface $input, OutputInterface $output)
    {
        $this->inputInterface = $input;
        parent::__construct($input, $output);
    }

    /**
     * @return InputInterface
     */
    public function getInput(): InputInterface
    {
        return $this->inputInterface;
    }

    /**
     * @see InputInterface::getArguments
     *
     * @param bool $provided
     *
     * @return array
     */
    public function getArguments(bool $provided = false): array
    {
        $arguments = $this->getInput()->getArguments();
        return $provided ? Php::arr($arguments, function ($value, $key) {
            $this->hasArgument($key) && yield $value;
        }) : $arguments;
    }

    /**
     * @see InputInterface::getOptions
     *
     * @param bool $provided
     *
     * @return array
     */
    public function getOptions(bool $provided = false): array
    {
        $options = $this->getInput()->getOptions();
        return $provided ? Php::arr($options, function ($value, $key) {
            $this->hasOption($key) && yield $value;
        }) : $options;
    }

    /**
     * @see InputInterface::getArgument
     *
     * @param string $name
     *
     * @return mixed
     */
    public function getArgument(string $name)
    {
        return $this->getInput()->getArgument($name);
    }

    /**
     * @see InputInterface::getOption
     *
     * @param string $name
     *
     * @return mixed
     */
    public function getOption(string $name)
    {
        return $this->getInput()->getOption($name);
    }

    /**
     * @see InputInterface::hasArgument
     *
     * @param string $name
     *
     * @return bool
     */
    public function hasArgument(string $name): bool
    {
        return $this->getInput()->hasArgument($name);
    }

    /**
     * @see InputInterface::hasOption
     *
     * @param string $name
     *
     * @return bool
     */
    public function hasOption(string $name): bool
    {
        return $this->getInput()->hasOption($name);
    }

    public function get(string $name, $default = null)
    {
        if ($this->hasOption($name)) {
            return $this->getOption($name);
        }
        if ($this->hasArgument($name)) {
            return $this->getArgument($name);
        }
        if (func_num_args() > 1) {
            return $default;
        }
        throw new LogicException($name);
    }

    /**
     * @param iterable $result
     *
     * @return iterable
     */
    public function render(iterable $result): iterable
    {
        foreach ($result as $key => $line) {
            yield $key => $line;
            $line = $line instanceof Renderable ? $line : new Renderable($line);
            $line->toCli($this);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Tests\AppBundle\Form\Editor\Admin\Assignments;

use AppBundle\Entity\Main\NewsletterBlock;
use AppBundle\Entity\Assignments\NewsletterBlockAdvertAssignment;
use AppBundle\Entity\Main\Advert;
use AppBundle\Form\Editor\Admin\Assignments\NewsletterBlockAdvertAssignmentEditorType;
use Symfony\Component\Form\PreloadedExtension;
use Tests\AppBundle\Form\Editor\Admin\Base\SimpleEditorTypeTest;

class NewsletterBlockAdvertAssignmentEditorTypeTest extends SimpleEditorTypeTest {

	const NEWSLETTER_BLOCK_ID = 100;

	const NEWSLETTER_BLOCK_NAME = 'Test newsletterBlock';

	const NEWSLETTER_BLOCK_CHOICES = ['Test newsletterBlock' => self::NEWSLETTER_BLOCK_ID];

	const ADVERT_ID = 100;

	const ADVERT_NAME = 'Test advert';

	const ADVERT_CHOICES = ['Test advert' => self::ADVERT_ID];

	private $newsletterBlockTransformer;

	private $advertTransformer;

	protected function setUp() {
		$this->newsletterBlockTransformer = $this->getEntityTransformerMock($this->getNewsletterBlock(),
				self::NEWSLETTER_BLOCK_ID);
		$this->advertTransformer = $this->getEntityTransformerMock($this->getAdvert(), self::ADVERT_ID);

		parent::setUp();
	}

	protected function getExtensions() {
		$type = new NewsletterBlockAdvertAssignmentEditorType($this->newsletterBlockTransformer,
				$this->advertTransformer);
		return array(new PreloadedExtension(array($type), array()));
	}

	protected function assertEntity($entity) {
		/** @var NewsletterBlockAdvertAssignment $entity */
		parent::assertEntity($entity);

		$this->assertSame(self::NEWSLETTER_BLOCK_ID, $entity->getNewsletterBlock()->getId());
		$this->assertSame(self::NEWSLETTER_BLOCK_NAME, $entity->getNewsletterBlock()->getName());

		$this->assertSame(self::ADVERT_ID, $entity->getAdvert()->getId());
		$this->assertSame(self::ADVERT_NAME, $entity->getAdvert()->getName());
	}

	protected function getFormData() {
		$data = parent::getFormData();

		$data['newsletterBlock'] = self::NEWSLETTER_BLOCK_ID;
		$data['advert'] = self::ADVERT_ID;

		return $data;
	}

	protected function getFormOptions() {
		$options = parent::getFormOptions();

		$options[self::getChoicesName('newsletterBlock')] = self::NEWSLETTER_BLOCK_CHOICES;
		$options[self::getChoicesName('advert')] = self::ADVERT_CHOICES;

		return $options;
	}

	protected function getFormType() {
		return NewsletterBlockAdvertAssignmentEditorType::class;
	}

	protected function getEntity() {
		return new NewsletterBlockAdvertAssignment();
	}

	private function getNewsletterBlock() {
		$mock = new NewsletterBlock();
		$mock->setId(self::NEWSLETTER_BLOCK_ID);
		$mock->setName(self::NEWSLETTER_BLOCK_NAME);

		return $mock;
	}

	private function getAdvert() {
		$mock = new Advert();
		$mock->setId(self::ADVERT_ID);
		$mock->setName(self::ADVERT_NAME);

		return $mock;
	}
}


text:
'use strict';

require('../../env-setup');

var port = require('yargs')
    .usage('Usage: $0 --port <port>')
    .demand(['port'])
    .argv.port;

var bodyParser = require('body-parser');
var multer = require('multer');
var solr = require('solr-client');
var _ = require('underscore');
var async = require('async');

var config = require(global.VX_ROOT + 'worker-config');

var idUtil = require(global.VX_UTILS + 'patient-identifier-utils');
var logUtil = require(global.VX_UTILS + 'log');
var log = logUtil.initialize(config.loggers).get('sync-endpoint');
var nullUtil = require(global.VX_UTILS + 'null-utils');
var PatientIdentifierAPI = require(global.VX_UTILS + 'middleware/patient-identifier-middleware');
var idMiddleware = new PatientIdentifierAPI(log, config);
var JobAPI = require(global.VX_UTILS + 'middleware/job-middleware');
var jobMiddleware = new JobAPI(log, config);
var jobUtil = require(global.VX_UTILS + 'job-utils');

var solrClient = solr.createClient(config.solrClient);
solrClient.autoCommit = true;
solrClient.UPDATE_JSON_HANDLER = 'update';

var jobFactory = function (req) {
    var forcedSync = [];
    if (req && _.isFunction(req.param)) {
        forcedSync = req.param('forcedSync');
    }
    if (forcedSync !== true) {
        try {
            forcedSync = JSON.parse(forcedSync);
        } catch (e) {
            forcedSync = [];
        }
    }
    return jobUtil.createEnterpriseSyncRequest(req.patientIdentifier, req.jpid, forcedSync, req.body.demographics);
};

var PublisherRouter = (require(global.VX_JOBFRAMEWORK + 'publisherRouter')),
    JobStatusUpdater = require(global.VX_JOBFRAMEWORK + 'JobStatusUpdater'),
    JdsClient = require(global.VX_SUBSYSTEMS + 'jds/jds-client'),
    VistaConnector = require(global.VX_SUBSYSTEMS + 'vista/vista-client'),
    jdsClient = new JdsClient(log, config),
    vistaConnector = new VistaConnector(log, config),
    jobStatusUpdater = new JobStatusUpdater(log, config, jdsClient),
    router = new PublisherRouter(logUtil.getAsChild('router', log), config, jobStatusUpdater);

var app = require('express')().use(bodyParser.json())
    .use(multer())
    .use(bodyParser.urlencoded({
        'extended': true
    }));

var doLoadMethods = [
    idMiddleware.validatePatientIdentifier.bind(idMiddleware),
    idMiddleware.getJPID,
    idMiddleware.createJPID,
    jobMiddleware.buildJob.bind(jobMiddleware, jobFactory),
    jobMiddleware.getJobHistory,
    jobMiddleware.jobVerification.bind(jobMiddleware, ['completed', 'error']),
    jobMiddleware.publishJob.bind(jobMiddleware, router),
    function(req, res, next) {
        res.status(202).json(res.job);
        next();
    }
];
var doDemoLoadMethods = [
    validateDemoParams,
    idMiddleware.getJPID,
    idMiddleware.createJPID,
    jobMiddleware.buildJob.bind(jobMiddleware, jobFactory),
    jobMiddleware.getJobHistory,
    jobMiddleware.jobVerification.bind(jobMiddleware, ['completed', 'error']),
    jobMiddleware.publishJob.bind(jobMiddleware, router),
    function(req, res, next) {
        res.status(202).json(res.job);
        next();
    }
];

var getStatusMethods = [
    idMiddleware.validatePatientIdentifier,
    idMiddleware.getJPID,
    getStatusJob,
    jobMiddleware.getJobHistory,
    jobMiddleware.getSyncStatus,
    returnSyncStatus
];

app.get('/sync/status', getStatusMethods);

app.post('/sync/load', doLoadMethods);
app.get('/sync/doLoad', doLoadMethods);

app.post('/sync/clearPatient', [
    idMiddleware.validatePatientIdentifier,
    idMiddleware.getJPID,
    unsyncPatient
]);
app.get('/sync/doClearPatient', [
    idMiddleware.validatePatientIdentifier,
    idMiddleware.getJPID,
    unsyncPatient
]);
app.post('/sync/demographicSync', doDemoLoadMethods);
app.get('/sync/doDemographicSync', doDemoLoadMethods);

app.get('/ping', function(req, res) {
    res.send('ACK');
});

function validateDemoParams(req, res, next) {
    /*{
        'pid': ["","",""],
        'edipi': "",
        'icn': "",
        'demographics': {
            "displayName": "",
            "familyName": "",
            "fullName": "",
            "givenNames": "",
            "genderName": "Male",
            "genderCode": "M",
            "ssn": "",
            "dob": ""
        }
    }*/
    //validate icn
    if(!nullUtil.isNullish(req.body, 'icn')) {
        var isValid = idUtil.isIdFormatValid(['icn', 'pid'], req.body.icn);
        if(!isValid) {
            return res.status(400).send('The patient icn was not in a valid format');
        }
    } else {
        return res.status(400).send('ICN must be provided');
    }
    //vaidate demographics
    if(!nullUtil.isNullish(req.body.demographics)) {
        if(nullUtil.isNullish(req.body.demographics,'displayName')) {
            log.warn('No display name found in demographic record');
        }
        if(nullUtil.isNullish(req.body.demographics,'familyName')) {
            log.warn('No family name found in demographic record');
        }
        if(nullUtil.isNullish(req.body.demographics,'fullName')) {
            log.warn('No full name found in demographic record');
        }
        if(nullUtil.isNullish(req.body.demographics,'givenNames')) {
            log.warn('No given names found in demographic record');
        }
        if(nullUtil.isNullish(req.body.demographics,'genderName')) {
            log.warn('No gender name found in demographic record');
        }
        if(nullUtil.isNullish(req.body.demographics,'genderCode')) {
            log.warn('No genderCode found in demographic record');
        }
        if(nullUtil.isNullish(req.body.demographics,'ssn')) {
            log.warn('No ssn found in demographic record');
        }
        if(nullUtil.isNullish(req.body.demographics,'birthdate')) {
            if(!nullUtil.isNullish(req.body.demographics,'dob')) {
                req.body.demographics.birthdate = req.body.demographics.dob;
            } else {
                log.warn('No birthdate found in demographic record');
            }
        }

        if (nullUtil.isNullish(req.body.demographics, 'address')) {
            log.warn('No address found in demographic record');
        }

        if (nullUtil.isNullish(req.body.demographics, 'telecom')) {
            log.warn('No telecom found in demographic record');
        }

        req.body.demographics.icn = req.body.icn;
    }
    req.body.demographics = _.pick(req.body.demographics, 'icn','displayName','fullname','givenNames','familyName','genderCode','genderName','birthdate','ssn','address','telecom');
    req.patientIdentifier = {value: req.body.icn, type: 'icn'};
    next();
}

function unsyncPatient(req, res) {
    var asyncMethod = (!_.isUndefined(req.param('force'))?async.parallel:async.series);
    if (!_.isUndefined(req.identifiers) && !_.isUndefined(req.identifiers.length)) {
        asyncMethod({
            'clearSolr': function(callback) {
                async.map(req.identifiers, function(identifier, solrCallback) {
                    log.debug('UNSYNC - pid:'+identifier);
                    solrClient.deleteByQuery('pid:'+identifier, solrCallback);
                }, callback);
            },
            'unsubscribeVistaSites': function(callback) {
                async.map(req.identifiers, function(identifier, vistaCallback) {
                    if (idUtil.isPid(identifier)) {
                        if (!_.isUndefined(config.vistaSites[idUtil.extractSiteFromPid(identifier)])) {
                            vistaConnector.unsubscribe(identifier, function(error, response) {
                                if (error || response !== 'success') {
                                    vistaCallback(error);
                                } else {
                                    vistaCallback();
                                }
                            });
                        } else {
                            vistaCallback();
                        }
                    } else {
                        vistaCallback();
                    }
                }, function(error) {
                    callback(error);
                });
            },
            'removePatientFromJds': function(callback) {
                jdsClient.removePatientIdentifier(req.jpid, function(error, response) {
                    if (!error && response.statusCode === 200) {
                        callback();
                    } else {
                        callback(response.body);
                    }
                });
            }
        }, function(error) {
            if (error) {
                res.status(500).json(error);
            } else {
                res.status(202).json({
                    'success': true
                });
            }
        });
    } else {
        res.status(404).send('Patient not found');
    }
}

/**
 * Configure request to retrieve job states
 */
function getStatusJob(req, res, next) {
    log.debug('sync-request-endpoint.getStatus() : Enter');
    if (req.jpid === false) {
        return res.status(404).send('Patient identifier not found [' + req.patientIdentifier.value + ']');
    }
    res.job = {
        'jpid': req.jpid
    };
    res.filter = {
        'filter': '?filter=ne(status,\"completed\")'
    };

    next();
}

/**
 * Assemble sync status response from sync status and job status
 */
function returnSyncStatus(req, res, next) {
    var syncStateJSON = {
        'jpid': res.job.jpid
    };
    syncStateJSON.syncStatus = removeProp(res.syncStatus, 'eventMetaStamp');
    if (typeof res.jobStates !== 'undefined') {
        syncStateJSON.jobStatus = res.jobStates;
    } else {
        syncStateJSON.jobStatus = JSON.parse('[]');
    }
    res.json(syncStateJSON);
    next();
}

function removeProp(obj, propName) {

    for (var p in obj) {

        if (obj.hasOwnProperty(p)) {

            if (p === propName) {
                delete obj[p];

            } else if (typeof obj[p] === 'object') {
                removeProp(obj[p], propName);
            }
        }
    }
    return obj;
}

app.listen(port);
log.info('sync-request endpoint listening on port %s', port);


text:
package com.thunderwarn.thunderwarn.common.slider;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import org.json.JSONObject;

/**
 * Created by Ivo on 28-06-2015.
 */
public abstract class SlidingItem extends LinearLayout{

    public SlidingItem(Context context) {
        super(context);
    }

    public abstract View viewForPosition(ViewGroup container, int position);

}


text:
package org.ojalgo.array.operation;

import org.ojalgo.scalar.Scalar;

public abstract class ApplyLU implements ArrayOperation {

    public static int THRESHOLD = 256;

    public static void invoke(final double[] data, final int structure, final int firstColumn, final int columnLimit, final double[] multipliers,
            final int iterationPoint) {
        for (int j = firstColumn; j < columnLimit; j++) {
            AXPY.invoke(data, j * structure, -data[iterationPoint + j * structure], multipliers, 0, iterationPoint + 1, structure);
        }
    }

    public static <N extends Scalar<N>> void invoke(final N[] data, final int structure, final int firstColumn, final int columnLimit, final N[] multipliers,
            final int iterationPoint) {
        for (int j = firstColumn; j < columnLimit; j++) {
            AXPY.invoke(data, j * structure, data[iterationPoint + j * structure].negate().get(), multipliers, 0, iterationPoint + 1, structure);
        }
    }

}


text:
class Attachment < ActiveRecord::Base
  belongs_to :user
  has_attached_file :file
  do_not_validate_attachment_file_type :file

  scope :latest, -> { order(id: :desc) }

  paginates_per 10

  def image?
    !!(file_content_type =~ /image/)
  end

  def posts
    Post.where('content LIKE ?', "%#{file.url}%").latest
  end
end


text:
/*
 * EAbstractPollingIoConnector.hh
 *
 *  Created on: 2016-3-22
 *      Author: cxxjava@163.com
 */

#ifndef EABSTRACTPOLLINGIOCONNECTOR_HH_
#define EABSTRACTPOLLINGIOCONNECTOR_HH_

#include "./EAbstractIoConnector.hh"
#include "./EAbstractIoSession.hh"
#include "./ESocketSessionConfig.hh"
#include "./EIoProcessor.hh"
#include "./EExceptionMonitor.hh"
#include "./ERuntimeIoException.hh"
#include "./ESimpleIoProcessorPool.hh"
#include "./EDefaultConnectFuture.hh"

namespace efc {
namespace eio {

/**
 * A base class for implementing client transport using a polling strategy. The
 * underlying sockets will be checked in an active loop and woke up when an
 * socket needed to be processed. This class handle the logic behind binding,
 * connecting and disposing the client sockets. A {@link Executor} will be used
 * for running client connection, and an {@link AbstractPollingIoProcessor} will
 * be used for processing connected client I/O operations like reading, writing
 * and closing.
 *
 * All the low level methods for binding, connecting, closing need to be
 * provided by the subclassing implementation.
 *
 * @see NioSocketConnector for a example of implementation
 *
 * @author Apache MINA Project
 */

template<typename H>
abstract class EAbstractPollingIoConnector: public EAbstractIoConnector {
public:
	virtual ~EAbstractPollingIoConnector() {
		if (createdProcessor) {
			delete processor;
		}
        connectorRef.set(null); //!!!
	}

	class ConnectionRequest : public EDefaultConnectFuture {
	private:
		EAbstractPollingIoConnector* owner;

		/** The handle associated with this connection request */
		H handle;

		/** The time up to this connection request will be valid */
		llong deadline;

		/** The callback to call when the session is initialized */
		EIoSessionInitializer* sessionInitializer;

	public:
		ConnectionRequest(H handle, EIoSessionInitializer* callback, EAbstractPollingIoConnector* s) : owner(s) {
			this->handle = handle;
			long timeout = owner->getConnectTimeoutMillis();

			if (timeout <= 0L) {
				this->deadline = ELLong::MAX_VALUE;
			} else {
				this->deadline = ESystem::currentTimeMillis() + timeout;
			}

			this->sessionInitializer = callback;
		}

		H getHandle() {
			return handle;
		}

		llong getDeadline() {
			return deadline;
		}

		EIoSessionInitializer* getSessionInitializer() {
			return sessionInitializer;
		}

		virtual boolean cancel() {
			if (!isDone()) {
				boolean justCancelled = EDefaultConnectFuture::cancel();

				// We haven't cancelled the request before, so add the future
				// in the cancel queue.
				if (justCancelled) {
					sp<ConnectionRequest> self = dynamic_pointer_cast<ConnectionRequest>(this->tosp());
					owner->cancelQueue.add(self);
					owner->startupWorker();
					owner->wakeup();
				}
			}

			return true;
		}
	};

protected:
	volatile boolean selectable;

	/**
	 * Constructor for {@link AbstractPollingIoConnector}. You need to provide a
	 * default session configuration, a class of {@link IoProcessor} which will
	 * be instantiated in a {@link SimpleIoProcessorPool} for better scaling in
	 * multiprocessor systems. The default pool size will be used.
	 *
	 * @see SimpleIoProcessorPool
	 *
	 * @param sessionConfig
	 *            the default configuration for the managed {@link IoSession}
	 * @param processorClass
	 *            a {@link Class} of {@link IoProcessor} for the associated
	 *            {@link IoSession} type.
	 */
	EAbstractPollingIoConnector(EIoSessionConfig* sessionConfig) :
			EAbstractIoConnector(sessionConfig, null) {
		ctor(sessionConfig, null, new ESimpleIoProcessorPool(), true);
	}

	/**
	 * Constructor for {@link AbstractPollingIoConnector}. You need to provide a
	 * default session configuration, a class of {@link IoProcessor} which will
	 * be instantiated in a {@link SimpleIoProcessorPool} for using multiple
	 * thread for better scaling in multiprocessor systems.
	 *
	 * @see SimpleIoProcessorPool
	 *
	 * @param sessionConfig
	 *            the default configuration for the managed {@link IoSession}
	 * @param processorClass
	 *            a {@link Class} of {@link IoProcessor} for the associated
	 *            {@link IoSession} type.
	 * @param processorCount
	 *            the amount of processor to instantiate for the pool
	 */
	EAbstractPollingIoConnector(EIoSessionConfig* sessionConfig, int processorCount) :
			EAbstractIoConnector(sessionConfig, null) {
		ctor(sessionConfig, null, new ESimpleIoProcessorPool(processorCount), true);
	}

	/**
	 * Constructor for {@link AbstractPollingIoConnector}. You need to provide a
	 * default session configuration, a default {@link Executor} will be created
	 * using {@link Executors#newCachedThreadPool()}.
	 *
	 * @see AbstractIoService#AbstractIoService(IoSessionConfig, Executor)
	 *
	 * @param sessionConfig
	 *            the default configuration for the managed {@link IoSession}
	 * @param processor
	 *            the {@link IoProcessor} for processing the {@link IoSession}
	 *            of this transport, triggering events to the bound
	 *            {@link IoHandler} and processing the chains of
	 *            {@link IoFilter}
	 */
	EAbstractPollingIoConnector(EIoSessionConfig* sessionConfig, EIoProcessor* processor) :
		EAbstractIoConnector(sessionConfig, null) {
		ctor(sessionConfig, null, processor, false);
	}

	/**
	 * Constructor for {@link AbstractPollingIoConnector}. You need to provide a
	 * default session configuration and an {@link Executor} for handling I/O
	 * events. If null {@link Executor} is provided, a default one will be
	 * created using {@link Executors#newCachedThreadPool()}.
	 *
	 * @see AbstractIoService#AbstractIoService(IoSessionConfig, Executor)
	 *
	 * @param sessionConfig
	 *            the default configuration for the managed {@link IoSession}
	 * @param executor
	 *            the {@link Executor} used for handling asynchronous execution
	 *            of I/O events. Can be null.
	 * @param processor
	 *            the {@link IoProcessor} for processing the {@link IoSession}
	 *            of this transport, triggering events to the bound
	 *            {@link IoHandler} and processing the chains of
	 *            {@link IoFilter}
	 */
	EAbstractPollingIoConnector(EIoSessionConfig* sessionConfig, EExecutorService* executor, EIoProcessor* processor) :
		EAbstractIoConnector(sessionConfig, executor) {
		ctor(sessionConfig, executor, processor, false);
	}

	/**
	 * {@inheritDoc}
	 */
	void dispose0() THROWS(EException) {
		startupWorker();
		wakeup();
	}

	virtual sp<EConnectFuture> connect0(EInetSocketAddress* remoteAddress, EInetSocketAddress* localAddress,
					EIoSessionInitializer* sessionInitializer) {
		H handle = null;
		boolean success = false;
		ON_FINALLY_NOTHROW(
			if (!success && handle != null) {
				try {
					close(handle);
				} catch (EException& e) {
					EExceptionMonitor::getInstance()->exceptionCaught(e);
				}
			}
		) {
			try {
				handle = newHandle(localAddress);
				if (connect(handle, remoteAddress)) {
					sp<EConnectFuture> future = new EDefaultConnectFuture();
					sp<EAbstractIoSession> session = dynamic_pointer_cast<EAbstractIoSession>(newSession(processor, handle));
					initSession(session, future, sessionInitializer);
					// Forward the remaining process to the IoProcessor.
					session->getProcessor()->add(session);
					success = true;
					return future;
				}

				success = true;
			} catch (EException& e) {
				return EDefaultConnectFuture::newFailedFuture(new EThrowableObject<EException>(e));
			}
        }}

		sp<ConnectionRequest> request = new ConnectionRequest(handle, sessionInitializer, this);
		connectQueue.add(request);
		startupWorker();
		wakeup();

		return dynamic_pointer_cast<EConnectFuture>(request);
	}

	/**
	 * Initialize the polling system, will be called at construction time.
	 *
	 * @throws Exception
	 *             any exception thrown by the underlying system calls
	 */
	virtual void init() THROWS(EException) = 0;

	/**
	 * Destroy the polling system, will be called when this {@link IoConnector}
	 * implementation will be disposed.
	 *
	 * @throws Exception
	 *             any exception thrown by the underlying systems calls
	 */
	virtual void destroy() THROWS(EException) = 0;

	/**
	 * Create a new client socket handle from a local {@link SocketAddress}
	 *
	 * @param localAddress
	 *            the socket address for binding the new client socket
	 * @return a new client socket handle
	 * @throws Exception
	 *             any exception thrown by the underlying systems calls
	 */
	virtual H newHandle(EInetSocketAddress* localAddress) THROWS(EException) = 0;

	/**
	 * Connect a newly created client socket handle to a remote
	 * {@link SocketAddress}. This operation is non-blocking, so at end of the
	 * call the socket can be still in connection process.
	 *
	 * @param handle the client socket handle
	 * @param remoteAddress the remote address where to connect
	 * @return <tt>true</tt> if a connection was established, <tt>false</tt> if
	 *         this client socket is in non-blocking mode and the connection
	 *         operation is in progress
	 * @throws Exception If the connect failed
	 */
	virtual boolean connect(H handle, EInetSocketAddress* remoteAddress) THROWS(EException) = 0;

	/**
	 * Finish the connection process of a client socket after it was marked as
	 * ready to process by the {@link #select(int)} call. The socket will be
	 * connected or reported as connection failed.
	 *
	 * @param handle
	 *            the client socket handle to finish to connect
	 * @return true if the socket is connected
	 * @throws Exception
	 *             any exception thrown by the underlying systems calls
	 */
	virtual boolean finishConnect(H handle) THROWS(EException) = 0;

	/**
	 * Create a new {@link IoSession} from a connected socket client handle.
	 * Will assign the created {@link IoSession} to the given
	 * {@link IoProcessor} for managing future I/O events.
	 *
	 * @param processor
	 *            the processor in charge of this session
	 * @param handle
	 *            the newly connected client socket handle
	 * @return a new {@link IoSession}
	 * @throws Exception
	 *             any exception thrown by the underlying systems calls
	 */
	virtual sp<EIoSession> newSession(EIoProcessor* processor, H handle) THROWS(EException) = 0;

	/**
	 * Close a client socket.
	 *
	 * @param handle
	 *            the client socket
	 * @throws Exception
	 *             any exception thrown by the underlying systems calls
	 */
	virtual void close(H handle) THROWS(EException) = 0;

	/**
	 * Interrupt the {@link #select(int)} method. Used when the poll set need to
	 * be modified.
	 */
	virtual void wakeup() = 0;

	/**
	 * Check for connected sockets, interrupt when at least a connection is
	 * processed (connected or failed to connect). All the client socket
	 * descriptors processed need to be returned by {@link #selectedHandles()}
	 *
	 * @param timeout The timeout for the select() method
	 * @return The number of socket having received some data
	 * @throws Exception any exception thrown by the underlying systems calls
	 */
	virtual int select(int timeout) THROWS(EException) = 0;

	/**
	 * {@link Iterator} for the set of client sockets found connected or failed
	 * to connect during the last {@link #select(int)} call.
	 *
	 * @return the list of client socket handles to process
	 */
	virtual sp<EIterator<H> > selectedHandles() = 0;

	/**
	 * {@link Iterator} for all the client sockets polled for connection.
	 *
	 * @return the list of client sockets currently polled for connection
	 */
	virtual sp<EIterator<H> > allHandles() = 0;

	/**
	 * Register a new client socket for connection, add it to connection polling
	 *
	 * @param handle
	 *            client socket handle
	 * @param request
	 *            the associated {@link ConnectionRequest}
	 * @throws Exception
	 *             any exception thrown by the underlying systems calls
	 */
	virtual void register_(H handle, sp<ConnectionRequest> request) THROWS(EException) = 0;

	/**
	 * get the {@link ConnectionRequest} for a given client socket handle
	 *
	 * @param handle
	 *            the socket client handle
	 * @return the connection request if the socket is connecting otherwise
	 *         null
	 */
	virtual sp<ConnectionRequest> getConnectionRequest(H handle) = 0;

private:
	class Connector : public ERunnable {
	private:
		EAbstractPollingIoConnector<H>* owner;

	public:
		Connector(EAbstractPollingIoConnector<H>* s) : owner(s) {
		}

		virtual void run() {
			ES_ASSERT (owner->connectorRef.get() == this);

			int nHandles = 0;

			while (owner->selectable) {
				try {
					// the timeout for select shall be smaller of the connect
					// timeout or 1 second...
					int timeout = (int) ES_MIN(owner->getConnectTimeoutMillis(), 1000L);
					int selected = owner->select(timeout);

					nHandles += owner->registerNew();

					// get a chance to get out of the connector loop, if we
					// don't have any more handles
					if (nHandles == 0) {
						owner->connectorRef.set(null);

						if (owner->connectQueue.isEmpty()) {
							ES_ASSERT (owner->connectorRef.get() != this);
							break;
						}

						if (!owner->connectorRef.compareAndSet(null, this)) {
							ES_ASSERT (owner->connectorRef.get() != this);
							break;
						}

						ES_ASSERT (owner->connectorRef.get() == this);
					}

					if (selected > 0) {
						nHandles -= owner->processConnections(owner->selectedHandles());
					}

					owner->processTimedOutSessions(owner->allHandles());

					nHandles -= owner->cancelKeys();
				} catch (EClosedSelectorException& cse) {
					// If the selector has been closed, we can exit the loop
					EExceptionMonitor::getInstance()->exceptionCaught(cse);
					break;
				} catch (EException& e) {
					EExceptionMonitor::getInstance()->exceptionCaught(e);

					try {
						EThread::sleep(1000);
					} catch (EInterruptedException& e1) {
						EExceptionMonitor::getInstance()->exceptionCaught(e1);
					}
				}
			}

			if (owner->selectable && owner->isDisposing()) {
				owner->selectable = false;
				ON_FINALLY_NOTHROW(
					ON_FINALLY_NOTHROW(
						owner->disposalFuture->setDone();
					) {
						try {
							SYNCBLOCK(&owner->disposalLock) {
								if (owner->isDisposing()) {
									owner->destroy();
								}
                            }}
						} catch (EException& e) {
							EExceptionMonitor::getInstance()->exceptionCaught(e);
						}
                    }}
				) {
					if (owner->createdProcessor) {
						owner->processor->dispose();
					}
                }}
			}
		}
	};

private:
	EIoProcessor* processor;

	boolean createdProcessor;

	EConcurrentLiteQueue<ConnectionRequest> connectQueue;// = new ConcurrentLinkedQueue<ConnectionRequest>();

	EConcurrentLiteQueue<ConnectionRequest> cancelQueue;// = new ConcurrentLinkedQueue<ConnectionRequest>();

	sp<ServiceOperationFuture> disposalFuture;// = new ServiceOperationFuture();

	/** The connector thread */
	EAtomicReference<Connector*> connectorRef;// = new AtomicReference<Connector>();

	/**
	 * Constructor for {@link AbstractPollingIoAcceptor}. You need to provide a
	 * default session configuration and an {@link Executor} for handling I/O
	 * events. If null {@link Executor} is provided, a default one will be
	 * created using {@link Executors#newCachedThreadPool()}.
	 *
	 * @see AbstractIoService#AbstractIoService(IoSessionConfig, Executor)
	 *
	 * @param sessionConfig
	 *            the default configuration for the managed {@link IoSession}
	 * @param executor
	 *            the {@link Executor} used for handling asynchronous execution
	 *            of I/O events. Can be null.
	 * @param processor
	 *            the {@link IoProcessor} for processing the {@link IoSession}
	 *            of this transport, triggering events to the bound
	 *            {@link IoHandler} and processing the chains of
	 *            {@link IoFilter}
	 * @param createdProcessor
	 *            tagging the processor as automatically created, so it will be
	 *            automatically disposed
	 */
	void ctor(EIoSessionConfig* sessionConfig, EExecutorService* executor, EIoProcessor* processor,
			boolean createdProcessor) {

		if (processor == null) {
			throw EIllegalArgumentException(__FILE__, __LINE__, "processor");
		}

		this->processor = processor;
		this->createdProcessor = createdProcessor;

		this->disposalFuture = new ServiceOperationFuture();

		/* moved to ENioSocketConnector::init()
		ON_FINALLY_NOTHROW(
			if (!selectable) {
				try {
					destroy();
				} catch (EException& e) {
					EExceptionMonitor::getInstance()->exceptionCaught(e);
				}
			}
		) {
			try {
				init();
				selectable = true;
			} catch (ERuntimeException& e) {
				throw e;
			} catch (EException& e) {
				throw ERuntimeIoException(__FILE__, __LINE__, "Failed to initialize.");
			}
		}}
		*/
	}

	void startupWorker() {
        if (!selectable) {
            connectQueue.clear();
            cancelQueue.clear();
        }

        Connector* connector = connectorRef.get();

        if (connector == null) {
            connector = new Connector(this);

            if (connectorRef.compareAndSet(null, connector)) {
                executeWorker(connector);
            } else {
            	delete connector;
            }
        }
    }

    int registerNew() {
        int nHandles = 0;
        for (;;) {
            sp<ConnectionRequest> req = connectQueue.poll();
            if (req == null) {
                break;
            }

            H handle = req->getHandle();
            try {
                register_(handle, req);
                nHandles++;
            } catch (EException& e) {
                req->setException(new EThrowableObject<EException>(e));
                try {
                    close(handle);
                } catch (EException& e2) {
                    EExceptionMonitor::getInstance()->exceptionCaught(e2);
                }
            }
        }
        return nHandles;
    }

    int cancelKeys() {
        int nHandles = 0;

        for (;;) {
            sp<ConnectionRequest> req = cancelQueue.poll();

            if (req == null) {
                break;
            }

            H handle = req->getHandle();

            ON_FINALLY_NOTHROW(
            	nHandles++;
            ) {
				try {
					close(handle);
				} catch (EException& e) {
					EExceptionMonitor::getInstance()->exceptionCaught(e);
				}
            }}
        }

        if (nHandles > 0) {
            wakeup();
        }

        return nHandles;
    }

    /**
     * Process the incoming connections, creating a new session for each valid
     * connection.
     */
    int processConnections(sp<EIterator<H> > handlers) {
        int nHandles = 0;

        // Loop on each connection request
        while (handlers->hasNext()) {
            H handle = handlers->next();
            handlers->remove();

            sp<ConnectionRequest> connectionRequest = getConnectionRequest(handle);

            if (connectionRequest == null) {
                continue;
            }

            boolean success = false;
            ON_FINALLY_NOTHROW(
				if (!success) {
					// The connection failed, we have to cancel it.
					cancelQueue.offer(connectionRequest);
				}
            ) {
				try {
					if (finishConnect(handle)) {
						sp<EAbstractIoSession> session = dynamic_pointer_cast<EAbstractIoSession>(newSession(processor, handle));
						initSession(session, connectionRequest, connectionRequest->getSessionInitializer());
						// Forward the remaining process to the IoProcessor.
						session->getProcessor()->add(session);
						nHandles++;
					}
					success = true;
				} catch (EException& e) {
					connectionRequest->setException(new EThrowableObject<EException>(e));
				}
            }}
        }
        return nHandles;
    }

    void processTimedOutSessions(sp<EIterator<H> > handles) {
    	llong currentTime = ESystem::currentTimeMillis();

        while (handles->hasNext()) {
            H handle = handles->next();
            sp<ConnectionRequest> connectionRequest = getConnectionRequest(handle);

            if ((connectionRequest != null) && (currentTime >= connectionRequest->getDeadline())) {
            	EConnectException e(__FILE__, __LINE__, "Connection timed out.");
                connectionRequest->setException(new EThrowableObject<EConnectException>(e));
                cancelQueue.offer(connectionRequest);
            }
        }
    }
};

} /* namespace eio */
} /* namespace efc */
#endif /* EABSTRACTPOLLINGIOCONNECTOR_HH_ */


text:
package com.buildmlearnstore.activities;

import java.util.ArrayList;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import com.actionbarsherlock.app.SherlockActivity;
import com.buildmlearnstore.model.InfoModel;

public class InfoActivity extends SherlockActivity {

	private static ArrayList<String> stringList;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		ListView listView = (ListView) findViewById(R.id.list);
		stringList = InfoModel.getInstance().getListTitleList();

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, stringList);

		listView.setAdapter(adapter);

		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				Intent myIntent = new Intent(view.getContext(),
						InfoDetailActivity.class);
				myIntent.putExtra("detail_title", stringList.get(position));
				startActivity(myIntent);
			}
		});

	}

}