text:
require 'spec_helper'

describe Distribot do
  describe '.debug' do
    it 'allows true and false values' do
      Distribot.debug = true
      expect(Distribot.debug).to be_truthy
      Distribot.debug = false
      expect(Distribot.debug).to be_falsey
    end
  end

  describe '.configure' do
    it 'executes the given block and uses the result as the configuration' do
      Distribot.reset_configuration!
      Distribot.configuration
      Distribot.configure do |config|
        config.foo=:bar
      end
      expect(Distribot.configuration.foo).to eq :bar
    end
  end

  describe '.redis' do
    context 'when configuration.redis_url' do
      context 'is nil' do
        before do
          Distribot.reset_configuration!
          Distribot.configure do |config|
            config.redis_url = nil
          end
        end
        it 'returns a new Redis instance without argument' do
          expect(Redis).to receive(:new).with(no_args){ 'HELLO' }
          expect(Distribot.redis).to eq 'HELLO'
        end
      end
      context 'is given' do
        before do
          @redis_url = 'redis://foo:6379/0'
          Distribot.reset_configuration!
          Distribot.configure do |config|
            config.redis_url = @redis_url
          end
        end
        it 'returns a new Redis instance' do
          expect(Redis).to receive(:new).with(url: @redis_url){ 'HELLO' }
          expect(Distribot.redis).to eq 'HELLO'
        end
      end
    end
  end

  describe '.connector' do
    before do
      Distribot.configure do |config|
        config.rabbitmq_url = 'fake-rabbit-url'
      end
    end
    it 'returns a BunnyConnector' do
      expect(Distribot::BunnyConnector).to receive(:new).with('fake-rabbit-url'){ 'connector' }
      expect(Distribot.connector).to eq 'connector'
    end
  end

  describe '.queue_exists?(name)' do
    context 'when the queue exists' do
      before do
        @queue_name = "queue-#{SecureRandom.uuid}"
        expect(Distribot).to receive(:connector) do
          connector = double('connector')
          expect(connector).to receive(:queue_exists?).with(@queue_name){ true }
          connector
        end
      end
      it 'returns true' do
        expect(Distribot.queue_exists?(@queue_name)).to be_truthy
      end
    end
    context 'when the queue does not exist' do
      before do
        @queue_name = "queue-#{SecureRandom.uuid}"
        expect(Distribot).to receive(:connector) do
          connector = double('connector')
          expect(connector).to receive(:queue_exists?).with(@queue_name){ false }
          connector
        end
      end
      it 'returns false' do
        expect(Distribot.queue_exists?(@queue_name)).to be_falsey
      end
    end
  end

  describe '.subscribe(queue_name, options={}, &block)' do
    before do
      @topic = "queue-#{SecureRandom.uuid}"
      expect(Distribot).to receive(:connector) do
        connector = double('connector')
        expect(connector).to receive(:subscribe).with(@topic, {}) do |&block|
          block.call( hello: 'world' )
        end
        connector
      end
    end
    it 'subscribes properly' do
      Distribot.subscribe(@topic) do |message|
        expect(message).to have_key :hello
        expect(message[:hello]).to eq 'world'
      end
    end
  end

  describe '.subscribe_multi(topic, options={}, &block)' do
    before do
      @topic = "queue-#{SecureRandom.uuid}"
      expect(Distribot).to receive(:connector) do
        connector = double('connector')
        expect(connector).to receive(:subscribe_multi).with(@topic, {}) do |&block|
          block.call( hello: 'world' )
        end
        connector
      end
    end
    it 'subscribes properly' do
      Distribot.subscribe_multi(@topic) do |message|
        expect(message).to have_key :hello
        expect(message[:hello]).to eq 'world'
      end
    end
  end

  describe '.publish!(topic, data)' do
    before do
      @topic = SecureRandom.uuid
      @data = { id: SecureRandom.uuid }
      expect(Distribot).to receive(:connector) do
        connector = double('connector')
        expect(connector).to receive(:publish).with(@topic, @data)
        connector
      end
    end
    it 'publishes the message to the topic' do
      Distribot.publish!(@topic, @data)
    end
  end

  describe '.broadcast!(topic, data)' do
    before do
      @topic = SecureRandom.uuid
      @data = { id: SecureRandom.uuid }
      expect(Distribot).to receive(:connector) do
        connector = double('connector')
        expect(connector).to receive(:broadcast).with(@topic, @data)
        connector
      end
    end
    it 'publishes the message to the topic' do
      Distribot.broadcast!(@topic, @data)
    end
  end

end


text:
<?php

// We don't use groups in the current Auth approach, where things are filtered
// based on the controller and not in the actions. This is commited here so
// that it is available the day we need to use the Acl component to filter on
// actions. Then we will need AROs and ACOs, and there are functions in here
// that are very handy to generate these.

class GroupsController extends AppController
{
	public $name = 'Groups';
	public $helpers = array('Html', 'Form');
	public $uses = array();

	public function beforeFilter()
	{
		parent::beforeFilter();
		// Enable this to add more groups manually
		// $this->Auth->allow('*');
	}

	public function index()
	{
		$this->Group->recursive = 0;
		$this->set('groups', $this->paginate());
	}

	public function view($id = null)
	{
		if (!$id) {
			$this->flashError(__('Invalid Group', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('group', $this->Group->read(null, $id));
	}

	public function add()
	{
		if (!empty($this->data)) {
			$this->Group->create();
			if ($this->Group->save($this->data)) {
				$this->flashError(__('The Group has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->flashError(__('The Group could not be saved. Please, try again.', true));
			}
		}
	}

	public function edit($id = null)
	{
		if (!$id && empty($this->data)) {
			$this->flashError(__('Invalid Group', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->Group->save($this->data)) {
				$this->flashError(__('The Group has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->flashError(__('The Group could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->Group->read(null, $id);
		}
	}

	public function delete($id = null)
	{
		if (!$id) {
			$this->flashError(__('Invalid id for Group', true));
			$this->redirect(array('action' => 'index'));
		}
		if ($this->Group->del($id)) {
			$this->flashError(__('Group deleted', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->flashError(__('The Group could not be deleted. Please, try again.', true));
		$this->redirect(array('action' => 'index'));
	}

	/** Copy all LDAP groups to a local table. We don't need this if we
	 * Auth->autorize = 'controller', that's only necessary for 'actions' */

	public function admin_store_ldap_groups()
	{
		if (!Configure::read('debug')) {
			return $this->_stop();
		}
		$this->loadModel('LdapUser');

		$groups = $this->LdapUser->getGroups();

		foreach ($groups as $g) {
			$save['id'] = $g['gidnumber'];
			$save['name'] = $g['cn'];
			$this->Group->save($save);
		}
	}

	/** We don't need AROs and ACOs this if we
	 * Auth->autorize = 'controller', that's only necessary for 'actions' */

	/** This function is used to generate an ACO table everytime
	 * we need to add new objects, because we have new controllers or methods
	 * inside them. It is quite tedious, but right now it is the best way to
	 * ensure security.
	 * Because we are using cake's ACL to handle groups only, and these are
	 * static metadata, the ACO and ARO tables can be then exported just as
	 * metadata to the metadata.sql file, so that we don't need to run this
	 * procedure and the initDB below on every installation. See
	 * http://agilo.toltech.nl/trac/wiki/HandleDatabaseEntries.
	 * http://book.cakephp.org/complete/641/Simple-Acl-controlled-Application

	 * Make function _private to deactivate it
	 */

	public function admin_build_acl()
	{
		if (!Configure::read('debug')) {
			return $this->_stop();
		}
		$log = array();

		$aco =& $this->Acl->Aco;
		$root = $aco->node('controllers');
		if (!$root) {
			$aco->create(array('parent_id' => null, 'model' => null, 'alias' => 'controllers'));
			$root = $aco->save();
			$root['Aco']['id'] = $aco->id;
			$log[] = 'Created Aco node for controllers';
		} else {
			$root = $root[0];
		}

		App::import('Core', 'File');
		$Controllers = Configure::listObjects('controller');
		$appIndex = array_search('App', $Controllers);
		if ($appIndex !== false) {
			unset($Controllers[$appIndex]);
		}
		$baseMethods = get_class_methods('Controller');
		$baseMethods[] = 'buildAcl';

		$Plugins = $this->_getPluginControllerNames();
		$Controllers = array_merge($Controllers, $Plugins);

		// look at each controller in app/controllers
		foreach ($Controllers as $ctrlName) {
			$methods = $this->_getClassMethods($this->_getPluginControllerPath($ctrlName));

			// Do all Plugins First
			if ($this->_isPlugin($ctrlName)) {
				$pluginNode = $aco->node('controllers/'.$this->_getPluginName($ctrlName));
				if (!$pluginNode) {
					$aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginName($ctrlName)));
					$pluginNode = $aco->save();
					$pluginNode['Aco']['id'] = $aco->id;
					$log[] = 'Created Aco node for '.$this->_getPluginName($ctrlName).' Plugin';
				}
			}
			// find / make controller node
			$controllerNode = $aco->node('controllers/'.$ctrlName);
			if (!$controllerNode) {
				if ($this->_isPlugin($ctrlName)) {
					$pluginNode = $aco->node('controllers/'.$this->_getPluginName($ctrlName));
					$aco->create(array('parent_id' => $pluginNode['0']['Aco']['id'], 'model' => null, 'alias' => $this->_getPluginControllerName($ctrlName)));
					$controllerNode = $aco->save();
					$controllerNode['Aco']['id'] = $aco->id;
					$log[] = 'Created Aco node for '.$this->_getPluginControllerName($ctrlName).' '.$this->_getPluginName($ctrlName).' Plugin Controller';
				} else {
					$aco->create(array('parent_id' => $root['Aco']['id'], 'model' => null, 'alias' => $ctrlName));
					$controllerNode = $aco->save();
					$controllerNode['Aco']['id'] = $aco->id;
					$log[] = 'Created Aco node for '.$ctrlName;
				}
			} else {
				$controllerNode = $controllerNode[0];
			}

			//clean the methods. to remove those in Controller and private actions.
			foreach ($methods as $k => $method) {
				if (strpos($method, '_', 0) === 0) {
					unset($methods[$k]);
					continue;
				}
				if (in_array($method, $baseMethods)) {
					unset($methods[$k]);
					continue;
				}
				$methodNode = $aco->node('controllers/'.$ctrlName.'/'.$method);
				if (!$methodNode) {
					$aco->create(array('parent_id' => $controllerNode['Aco']['id'], 'model' => null, 'alias' => $method));
					$methodNode = $aco->save();
					$log[] = 'Created Aco node for '.$ctrlName.'/'.$method;
				}
			}
		}
		if (count($log)>0) {
			debug($log);
		}
	}

	public function _getClassMethods($ctrlName = null)
	{
		App::import('Controller', $ctrlName);
		if (strlen(strstr($ctrlName, '.')) > 0) {
			// plugin's controller
			$num = strpos($ctrlName, '.');
			$ctrlName = substr($ctrlName, $num+1);
		}
		$ctrlclass = $ctrlName.'Controller';
		$methods = get_class_methods($ctrlclass);

		// Add scaffold defaults if scaffolds are being used
		$properties = get_class_vars($ctrlclass);
		if (array_key_exists('scaffold', $properties)) {
			if ($properties['scaffold'] == 'admin') {
				$methods = array_merge($methods, array('admin_add', 'admin_edit', 'admin_index', 'admin_view', 'admin_delete'));
			} else {
				$methods = array_merge($methods, array('add', 'edit', 'index', 'view', 'delete'));
			}
		}
		return $methods;
	}

	public function _isPlugin($ctrlName = null)
	{
		$arr = String::tokenize($ctrlName, '/');
		if (count($arr) > 1) {
			return true;
		} else {
			return false;
		}
	}

	public function _getPluginControllerPath($ctrlName = null)
	{
		$arr = String::tokenize($ctrlName, '/');
		if (count($arr) == 2) {
			return $arr[0].'.'.$arr[1];
		} else {
			return $arr[0];
		}
	}

	public function _getPluginName($ctrlName = null)
	{
		$arr = String::tokenize($ctrlName, '/');
		if (count($arr) == 2) {
			return $arr[0];
		} else {
			return false;
		}
	}

	public function _getPluginControllerName($ctrlName = null)
	{
		$arr = String::tokenize($ctrlName, '/');
		if (count($arr) == 2) {
			return $arr[1];
		} else {
			return false;
		}
	}

	/**
	 * Get the names of the plugin controllers ...
	 *
	 * This function will get an array of the plugin controller names, and
	 * also makes sure the controllers are available for us to get the
	 * method names by doing an App::import for each plugin controller.
	 *
	 * @return array of plugin names.
	 *
	 */
	public function _getPluginControllerNames()
	{
		App::import('Core', 'File', 'Folder');
		$paths = Configure::getInstance();
		$folder =& new Folder();
		$folder->cd(APP.'plugins');

		// Get the list of plugins
		$Plugins = $folder->read();
		$Plugins = $Plugins[0];
		$arr = array();

		// Loop through the plugins
		foreach ($Plugins as $pluginName) {
			// Change directory to the plugin
			$didCD = $folder->cd(APP.'plugins'.DS.$pluginName.DS.'controllers');
			// Get a list of the files that have a file name that ends
			// with controller.php
			$files = $folder->findRecursive('.*_controller\.php');

			// Loop through the controllers we found in the plugins directory
			foreach ($files as $fileName) {
				// Get the base file name
				$file = basename($fileName);

				// Get the controller name
				$file = Inflector::camelize(substr($file, 0, strlen($file)-strlen('_controller.php')));
				if (!preg_match('/^'.Inflector::humanize($pluginName).'App/', $file)) {
					if (!App::import('Controller', $pluginName.'.'.$file)) {
						debug('Error importing '.$file.' for plugin '.$pluginName);
					} else {
						/// Now prepend the Plugin name ...
						// This is required to allow us to fetch the method names.
						$arr[] = Inflector::humanize($pluginName)."/".$file;
					}
				}
			}
		}
		return $arr;
	}

	// http://localhost/regenboog/admin/groups/list_all_methods

	public function admin_list_all_methods()
	{
		if (!Configure::read('debug')) {
			return $this->_stop();
		}

		App::import('Core', 'File');
		$Controllers = Configure::listObjects('controller');
		$appIndex = array_search('App', $Controllers);
		if ($appIndex !== false) {
			unset($Controllers[$appIndex]);
		}
		$baseMethods = get_class_methods('Controller');
		$baseMethods[] = 'buildAcl';

		$Plugins = $this->_getPluginControllerNames();
		$Controllers = array_merge($Controllers, $Plugins);

		// look at each controller in app/controllers
		foreach ($Controllers as $ctrlName) {
			$methods = $this->_getClassMethods($this->_getPluginControllerPath($ctrlName));

			//clean the methods, to remove those in Controller and private
			//actions.
			foreach ($methods as $k => $method) {
				if (strpos($method, '_', 0) === 0) {
					unset($methods[$k]);
					continue;
				}
				if (in_array($method, $baseMethods)) {
					unset($methods[$k]);
					continue;
				}
				$methodNode = 'controllers/'.$ctrlName.'/'.$method;
				$log[] = $methodNode;
			}
		}
		debug($log);
	}

	public function admin_initDB_methods()
	{
		if (!Configure::read('debug')) {
			return $this->_stop();
		}

		/** Patterns are regular expressions, so 'edit' enables actions like
		   "edit" but also "edit_secret". A more restrictive pattern, only for
		   the edit method, is "^edit$"
		   admin_, _private and base methods are ignored anyway.
		   */

		$enable_patterns = array(
			GROUP_PORTIER => array(
					"Registraties" => array( ".*" ),
					),
			GROUP_MLO => array(
					"Intakes" => array( ".*" ),
					"Klanten" => array( ".*" ),
					"Registraties" => array( ".*" ),
					),
			GROUP_MAATSCHAPPELIJK => array(
					"Intakes" => array( ".*" ),
					"Klanten" => array( ".*" ),
					"MaatschappelijkWerken" => array( ".*" ),
					),
			GROUP_HI5 => array(
					"Intakes" => array( ".*" ),
					"Klanten" => array( ".*" ),
					"HiFive" => array( ".*" ),
					),
			GROUP_ADMIN => array(
					"Intakes" => array( ".*" ),
					"Klanten" => array( ".*" ),
					"HiFive" => array( ".*" ),
					"MaatschappelijkWerken" => array( ".*" ),
					"Registraties" => array( ".*" ),
					),
			);

		$log = array();

		// Build first an array of all methods in controllers.

		App::import('Core', 'File');
		$Controllers = Configure::listObjects('controller');
		$appIndex = array_search('App', $Controllers);
		if ($appIndex !== false) {
			unset($Controllers[$appIndex]);
		}
		$baseMethods = get_class_methods('Controller');
		$baseMethods[] = 'buildAcl';

		$Plugins = $this->_getPluginControllerNames();
		$Controllers = array_merge($Controllers, $Plugins);

		// look at each controller in app/controllers
		foreach ($Controllers as $ctrlName) {
			$methods = $this->_getClassMethods($this->_getPluginControllerPath($ctrlName));

			//clean the methods, to remove those in Controller and private
			//actions.
			foreach ($methods as $k => $method) {
				if (strpos($method, '_', 0) === 0) {
					unset($methods[$k]);
					continue;
				}
				if (strpos($method, 'admin_', 0) === 0) {
					unset($methods[$k]);
					continue;
				}
				if (in_array($method, $baseMethods)) {
					unset($methods[$k]);
					continue;
				}
				$methodNode = 'controllers/'.$ctrlName.'/'.$method;

				$methodNodes[$ctrlName][$method] = $methodNode;
			}
		}

		$group =& $this->Group;
		foreach ($enable_patterns as $group_id => $controllers) {
			$group->id = $group_id;
			$this->Acl->deny($group, 'controllers');
			$log[] = "Deny group $group_id access to all controllers -----";

			foreach ($controllers as $controller => $patterns) {
				foreach ($patterns as $pattern) {
					foreach ($methodNodes[$controller] as $method => $node) {
						if (preg_match("/$pattern/", $method)) {
							$this->Acl->allow($group, $node);
							$log[] = "Granted $group_id access for $node";
						}
					}
				}
			}
		}

		if (count($log)>0) {
			debug($log);
		}
	}

	/**
	 * clear_cache Clear all caches intensively. The purpose is to force a
	 * restart without having to restart apache.
	 *
	 * @access public For administrators.
	 * @return void
	 */
	public function clear_cache()
	{

		// Clear contents of cache directories
		clearCache(null, 'views');
		clearCache(null, 'models');
		clearCache(null, 'persistent');

		// clear keys from memory cache
		Cache::clear();

		// Extra cleaning if we use APC:
		if (function_exists('apc_clear_cache')) {
			apc_clear_cache();
			apc_clear_cache('opcode');
			debug(apc_cache_info());
		}

		if (in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) {
			echo "Local access.\n";
		}

		echo "The cache has been cleared.\n";
		die;
	}
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace server\tests\units\unix;

require __DIR__ . '/../../runner.php';

use
	atoum,
	server\unix,
	server\unix\user as testedClass
;

class user extends atoum
{
	public function test__construct()
	{
		$this
			->if($user = new testedClass())
			->then
				->castToString($user)->isEmpty()
				->variable($user->getUid())->isNull()
				->variable($user->getGid())->isNull()
				->object($user->getHome())->isEqualTo(new unix\user\home())
				->variable($user->getHomePath())->isNull()

			->if($this->function->posix_getpwnam = false)
			->then
				->exception(function() use (& $login) { new testedClass($login = uniqid()); })
					->isInstanceOf('server\unix\user\exception')
					->hasMessage('User \'' . $login . '\' does not exist')

			->if(
				$this->function->posix_getpwnam = array('uid' => $uid = rand(1, PHP_INT_MAX), 'gid' => $gid = rand(1, PHP_INT_MAX), 'dir' => $dir = uniqid()),
				$user = new testedClass($login = uniqid())
			)
			->then
				->castToString($user)->isEqualTo($login)
				->integer($user->getUid())->isEqualTo($uid)
				->integer($user->getGid())->isEqualTo($gid)
				->object($user->getHome())->isEqualTo(new unix\user\home($dir))
				->string($user->getHomePath())->isEqualTo($dir)
		;
	}

	public function testSetHome()
	{
		$this
			->if($user = new testedClass())
			->then
				->object($user->setHome($home = new unix\user\home()))->isIdenticalTo($user)
				->object($user->getHome())->isIdenticalTo($home)
				->object($user->setHome())->isIdenticalTo($user)
				->object($user->getHome())
					->isNotIdenticalTo($home)
					->isEqualTo(new unix\user\home())
		;
	}

	public function testSetHomePath()
	{
		$this
			->given(
				$user = new testedClass(),
				$user->setHome($home = new \mock\server\unix\user\home())
			)
			->then
				->object($user->setHomePath($path = uniqid()))->isIdenticalTo($user)
				->mock($home)->call('setPath')->withArguments($path)->once()
		;
	}

	public function testSetLogin()
	{
		$this
			->given($user = new testedClass())

			->if($this->function->posix_getpwnam = false)
			->then
				->exception(function() use ($user, & $login) { $user->setLogin($login = uniqid()); })
					->isInstanceOf('server\unix\user\exception')
					->hasMessage('User \'' . $login . '\' does not exist')

			->if(
				$this->function->posix_getpwnam = array('uid' => $uid = rand(1, PHP_INT_MAX), 'gid' => $gid = rand(1, PHP_INT_MAX), 'dir' => $dir = uniqid())
			)
			->then
				->object($user->setLogin($login = uniqid()))->isIdenticalTo($user)
				->castToString($user)->isEqualTo($login)
				->integer($user->getUid())->isEqualTo($uid)
				->integer($user->getGid())->isEqualTo($gid)
				->string($user->getHomePath())->isEqualTo($dir)

			->if(
				$user->setHomePath(uniqid()),
				$this->function->posix_getpwnam = array('uid' => $otherUid = rand(1, PHP_INT_MAX), 'gid' => $otherGid = rand(1, PHP_INT_MAX), 'dir' => $otherDir = uniqid())
			)
			->then
				->object($user->setLogin($otherLogin = uniqid()))->isIdenticalTo($user)
				->castToString($user)->isEqualTo($otherLogin)
				->integer($user->getUid())->isEqualTo($otherUid)
				->integer($user->getGid())->isEqualTo($otherGid)
				->string($user->getHomePath())->isEqualTo($otherDir)
		;
	}

	public function testGoToHome()
	{
		$this
			->given(
				$user = new testedClass(),
				$user->setHome($home = new \mock\server\unix\user\home())
			)

			->if($this->calling($home)->go->isFluent())
			->then
				->object($user->goToHome())->isEqualTo($user)
				->mock($home)->call('go')->once()

			->if($this->calling($home)->go->throw = $exception = new \exception())
			->then
				->exception(function() use ($user) { $user->goToHome(); })
					->isInstanceOf('server\unix\user\exception')
					->hasMessage($exception->getMessage())
		;
	}
}


text:
package main

import (
	"github.com/Craig-Macomber/election/msg"
	"github.com/Craig-Macomber/election/server"
	"github.com/Craig-Macomber/election/server/ballot"
	"github.com/Craig-Macomber/election/server/vote"
	"github.com/Craig-Macomber/election/server/voterlist"
)

const maxLength = 4096

func main() {
	handlers := server.HandlerMap{
		msg.SignatureRequest:    server.BlockHandler(ballot.HandelSignatureRequest, maxLength),
		msg.Vote:                server.BlockHandler(vote.HandelSignatureRequest, maxLength),
		msg.KeySignatureRequest: server.BlockHandler(voterlist.HandelSignatureRequest, maxLength),
	}
	server.Start(handlers)
}


text:
@interface V8HorizontalPickerView () {
	UIScrollView *_scrollView;
}

// collection of widths of each element.
@property (nonatomic, strong) NSMutableArray *elementWidths;

@property (nonatomic, assign) NSInteger elementPadding;

// state keepers
@property (nonatomic, assign) BOOL dataHasBeenLoaded;
@property (nonatomic, assign) BOOL scrollSizeHasBeenSet;
@property (nonatomic, assign) BOOL scrollingBasedOnUserInteraction;

// keep track of which elements are visible for tiling
@property (nonatomic, assign) NSInteger firstVisibleElement;
@property (nonatomic, assign) NSInteger lastVisibleElement;

@end

#pragma mark - Implementation
@implementation V8HorizontalPickerView : UIView

#pragma mark - Init/Dealloc
- (id)initWithFrame:(CGRect)frame {
	self = [super initWithFrame:frame];
	if (self) {
		[self initSetup];
	}
	return self;
}

- (id)initWithCoder:(NSCoder *)theCoder {
	self = [super initWithCoder:theCoder];
	if (self) {
		[self initSetup];
	}
	return self;
}

- (void)dealloc {
	_scrollView.delegate = nil;
	self.delegate = nil;
	self.dataSource = nil;
}

- (void)initSetup {
	self.elementWidths = [NSMutableArray array];

	[self addScrollView];

	self.textColor   = [UIColor blackColor];
	self.elementFont = [UIFont systemFontOfSize:12.0f];

	_currentSelectedIndex     = -1; // nothing is selected yet
	_numberOfElements         = 0;

	self.elementPadding       = 0;
	self.dataHasBeenLoaded    = NO;
	self.scrollSizeHasBeenSet = NO;
	self.scrollingBasedOnUserInteraction = NO;

	self.selectionPoint = CGPointZero;
	self.indicatorPosition = V8HorizontalPickerIndicatorBottom;

	self.firstVisibleElement = -1;
	self.lastVisibleElement  = -1;

	self.scrollEdgeViewPadding = 0.0f;

	self.autoresizesSubviews = YES;
}

#pragma mark - LayoutSubViews
- (void)layoutSubviews {
	[super layoutSubviews];
	BOOL adjustWhenFinished = NO;

	if (CGPointEqualToPoint(self.selectionPoint, CGPointZero)) {
		// default to the center
		self.selectionPoint = CGPointMake(self.frame.size.width / 2, 0.0f);
	}

	if (!self.dataHasBeenLoaded) {
		[self collectData];
	}
	if (!self.scrollSizeHasBeenSet) {
		adjustWhenFinished = YES;
		[self updateScrollContentInset];
		[self setTotalWidthOfScrollContent];
	}

	SEL titleForElementSelector = @selector(horizontalPickerView:titleForElementAtIndex:);
	SEL viewForElementSelector  = @selector(horizontalPickerView:viewForElementAtIndex:);
	SEL setSelectedSelector     = @selector(setSelectedElement:);

	CGRect visibleBounds   = [self bounds];
	CGRect scaledViewFrame = CGRectZero;

	// remove any subviews that are no longer visible
	for (UIView *view in [_scrollView subviews]) {
		scaledViewFrame = [_scrollView convertRect:[view frame] toView:self];

		// if the view doesn't intersect, it's not visible, so we can recycle it
		if (!CGRectIntersectsRect(scaledViewFrame, visibleBounds)) {
			[view removeFromSuperview];
		} else { // if it is still visible, update it's selected state
			if ([view respondsToSelector:setSelectedSelector]) {
				// view's tag is it's index
				BOOL isSelected = (self.currentSelectedIndex == [self indexForElement:view]);
				if (isSelected) {
					// if this view is set to be selected, make sure it is over the selection point
					NSInteger currentIndex = [self nearestElementToCenter];
					isSelected = (currentIndex == self.currentSelectedIndex);
				}
				// casting to V8HorizontalPickerLabel so we can call this without all the NSInvocation jazz
				[(V8HorizontalPickerLabel *)view setSelectedElement:isSelected];
			}
		}
	}

	// find needed elements by looking at left and right edges of frame
	CGPoint offset = _scrollView.contentOffset;
	NSInteger firstNeededElement = [self nearestElementToPoint:CGPointMake(offset.x, 0.0f)];
	NSInteger lastNeededElement  = [self nearestElementToPoint:CGPointMake(offset.x + visibleBounds.size.width, 0.0f)];

	// add any views that have become visible
	UIView *view = nil;
	CGRect tmpViewFrame = CGRectZero;
	CGPoint itemViewCenter = CGPointZero;
	for (NSInteger i = firstNeededElement; i <= lastNeededElement; i++) {
		view = nil; // paranoia
		view = [_scrollView viewWithTag:[self tagForElementAtIndex:i]];
		if (!view) {
			if (i < self.numberOfElements) { // make sure we are not requesting data out of range
				if (self.delegate && [self.delegate respondsToSelector:titleForElementSelector]) {
					NSString *title = [self.delegate horizontalPickerView:self titleForElementAtIndex:i];
					view = [self labelForForElementAtIndex:i withTitle:title];
				} else if (self.delegate && [self.delegate respondsToSelector:viewForElementSelector]) {
					view = [self.delegate horizontalPickerView:self viewForElementAtIndex:i];
					// move view's center to the center of item's ideal frame
					tmpViewFrame = [self frameForElementAtIndex:i];
					itemViewCenter = CGPointMake((tmpViewFrame.size.width / 2.0f) + tmpViewFrame.origin.x, (tmpViewFrame.size.height / 2.0f));
					view.center = itemViewCenter;
				}

				if (view) {
					// use the index as the tag so we can find it later
					view.tag = [self tagForElementAtIndex:i];
					[_scrollView addSubview:view];
				}
			}
		}
	}

	// add the left or right edge views if visible
	CGRect viewFrame = CGRectZero;
	if (self.leftScrollEdgeView) {
		viewFrame = [self frameForLeftScrollEdgeView];
		scaledViewFrame = [_scrollView convertRect:viewFrame toView:self];
		if (CGRectIntersectsRect(scaledViewFrame, visibleBounds) && ![self.leftScrollEdgeView isDescendantOfView:_scrollView]) {
			self.leftScrollEdgeView.frame = viewFrame;
			[_scrollView addSubview:self.leftScrollEdgeView];
		}
	}
	if (self.rightScrollEdgeView) {
		viewFrame = [self frameForRightScrollEdgeView];
		scaledViewFrame = [_scrollView convertRect:viewFrame toView:self];
		if (CGRectIntersectsRect(scaledViewFrame, visibleBounds) && ![self.rightScrollEdgeView isDescendantOfView:_scrollView]) {
			self.rightScrollEdgeView.frame = viewFrame;
			[_scrollView addSubview:self.rightScrollEdgeView];
		}
	}

	// save off what's visible now
	self.firstVisibleElement = firstNeededElement;
	self.lastVisibleElement  = lastNeededElement;

	// determine if scroll view needs to shift in response to resizing?
	if (self.currentSelectedIndex > -1 && [self centerOfElementAtIndex:self.currentSelectedIndex] != [self currentCenter].x) {
		if (adjustWhenFinished) {
			[self scrollToElement:self.currentSelectedIndex animated:NO];
		} else if (self.numberOfElements <= self.currentSelectedIndex) {
			// if currentSelectedIndex no longer exists, select what is currently centered
			_currentSelectedIndex = [self nearestElementToCenter];
			[self scrollToElement:self.currentSelectedIndex animated:NO];
		}
	}
}

#pragma mark - Getters and Setters
- (void)setDelegate:(id)newDelegate {
	if (self.delegate != newDelegate) {
		_delegate = newDelegate;
		[self collectData];
	}
}

- (void)setDataSource:(id)newDataSource {
	if (self.dataSource != newDataSource) {
		_dataSource = newDataSource;
		[self collectData];
	}
}

- (void)setSelectionPoint:(CGPoint)point {
	if (!CGPointEqualToPoint(point, self.selectionPoint)) {
		_selectionPoint = point;
		[self updateScrollContentInset];
	}
}

// allow the setting of this views background color to change the scroll view
- (void)setBackgroundColor:(UIColor *)newColor {
	[super setBackgroundColor:newColor];
	_scrollView.backgroundColor = newColor;
	// TODO: set all subviews as well?
}

- (void)setIndicatorPosition:(V8HorizontalPickerIndicatorPosition)position {
	if (self.indicatorPosition != position) {
		_indicatorPosition = position;
		[self drawPositionIndicator];
	}
}

- (void)setSelectionIndicatorView:(UIView *)indicatorView {
	if (self.selectionIndicatorView != indicatorView) {
		if (self.selectionIndicatorView) {
			[self.selectionIndicatorView removeFromSuperview];
		}
		_selectionIndicatorView = indicatorView;

		[self drawPositionIndicator];
	}
}

- (void)setLeftEdgeView:(UIView *)leftView {
	if (self.leftEdgeView != leftView) {
		if (self.leftEdgeView) {
			[self.leftEdgeView removeFromSuperview];
		}
		_leftEdgeView = leftView;

		CGRect tmpFrame = self.leftEdgeView.frame;
		tmpFrame.origin.x = 0.0f;
		tmpFrame.origin.y = 0.0f;
		self.leftEdgeView.frame = tmpFrame;
		[self addSubview:self.leftEdgeView];
	}
}

- (void)setRightEdgeView:(UIView *)rightView {
	if (self.rightEdgeView != rightView) {
		if (self.rightEdgeView) {
			[self.rightEdgeView removeFromSuperview];
		}
		_rightEdgeView = rightView;

		CGRect tmpFrame = self.rightEdgeView.frame;
		tmpFrame.origin.x = self.frame.size.width - tmpFrame.size.width;
		tmpFrame.origin.y = 0.0f;
		self.rightEdgeView.frame = tmpFrame;
		[self addSubview:self.rightEdgeView];
	}
}

- (void)setLeftScrollEdgeView:(UIView *)leftView {
	if (self.leftScrollEdgeView != leftView) {
		if (self.leftScrollEdgeView) {
			[self.leftScrollEdgeView removeFromSuperview];
		}
		_leftScrollEdgeView = leftView;

		self.scrollSizeHasBeenSet = NO;
		[self setNeedsLayout];
	}
}

- (void)setRightScrollEdgeView:(UIView *)rightView {
	if (self.rightScrollEdgeView != rightView) {
		if (self.rightScrollEdgeView) {
			[self.rightScrollEdgeView removeFromSuperview];
		}
		_rightScrollEdgeView = rightView;

		self.scrollSizeHasBeenSet = NO;
		[self setNeedsLayout];
	}
}

- (void)setFrame:(CGRect)newFrame {
	if (!CGRectEqualToRect(self.frame, newFrame)) {
		// causes recalulation of offsets, etc based on new size
		self.scrollSizeHasBeenSet = NO;
	}
	[super setFrame:newFrame];
}

#pragma mark - Data Fetching Methods
- (void)reloadData {
	// remove all scrollview subviews and "recycle" them
	for (UIView *view in [_scrollView subviews]) {
		[view removeFromSuperview];
	}

	self.firstVisibleElement = NSIntegerMax;
	self.lastVisibleElement  = NSIntegerMin;

	[self collectData];
}

- (void)collectData {
	self.scrollSizeHasBeenSet = NO;
	self.dataHasBeenLoaded    = NO;

	[self getNumberOfElementsFromDataSource];
	[self getElementWidthsFromDelegate];
	[self setTotalWidthOfScrollContent];
	[self updateScrollContentInset];

	self.dataHasBeenLoaded = YES;
	[self setNeedsLayout];
}

#pragma mark - Scroll To Element Method
- (void)scrollToElement:(NSInteger)index animated:(BOOL)animate {
	_currentSelectedIndex = index;
	int x = [self centerOfElementAtIndex:index] - self.selectionPoint.x;
	[_scrollView setContentOffset:CGPointMake(x, 0) animated:animate];

	// notify delegate of the selected index
	SEL delegateCall = @selector(horizontalPickerView:didSelectElementAtIndex:);
	if (self.delegate && [self.delegate respondsToSelector:delegateCall]) {
		[self.delegate horizontalPickerView:self didSelectElementAtIndex:index];
	}

#if (__IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_4_3)
	[self setNeedsLayout];
#endif
}

#pragma mark - UIScrollViewDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	if (self.scrollingBasedOnUserInteraction) {
		// NOTE: sizing and/or changing orientation of control might cause scrolling
		//		 not initiated by user. do not update current selection in these
		//		 cases so that the view state is properly preserved.

		// set the current item under the center to "highlighted" or current
		_currentSelectedIndex = [self nearestElementToCenter];
	}

#if (__IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_4_3)
	[self setNeedsLayout];
#endif
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
	self.scrollingBasedOnUserInteraction = YES;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
	// only do this if we aren't decelerating
	if (!decelerate) {
		[self scrollToElementNearestToCenter];
	}
}

//- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView { }

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
	[self scrollToElementNearestToCenter];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
	self.scrollingBasedOnUserInteraction = NO;
}

#pragma mark - View Creation Methods (Internal Methods)
- (void)addScrollView {
	if (_scrollView == nil) {
		_scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
		_scrollView.delegate = self;
		_scrollView.scrollEnabled = YES;
		_scrollView.scrollsToTop  = NO;
		_scrollView.showsVerticalScrollIndicator   = NO;
		_scrollView.showsHorizontalScrollIndicator = NO;
		_scrollView.bouncesZoom  = NO;
		_scrollView.alwaysBounceHorizontal = YES;
		_scrollView.alwaysBounceVertical   = NO;
		_scrollView.minimumZoomScale = 1.0; // setting min/max the same disables zooming
		_scrollView.maximumZoomScale = 1.0;
		_scrollView.contentInset = UIEdgeInsetsZero;
		_scrollView.decelerationRate = 0.1; //UIScrollViewDecelerationRateNormal;
		_scrollView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
		_scrollView.autoresizesSubviews = YES;

		UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(scrollViewTapped:)];
		[_scrollView addGestureRecognizer:tapRecognizer];

		[self addSubview:_scrollView];
	}
}

- (void)drawPositionIndicator {
	CGRect indicatorFrame = self.selectionIndicatorView.frame;
	CGFloat x = self.selectionPoint.x - (indicatorFrame.size.width / 2);
	CGFloat y;

	switch (self.indicatorPosition) {
		case V8HorizontalPickerIndicatorTop: {
			y = 0.0f;
			break;
		}
		case V8HorizontalPickerIndicatorBottom: {
			y = self.frame.size.height - indicatorFrame.size.height;
			break;
		}
		default:
			break;
	}

	// properly place indicator image in view relative to selection point
	CGRect tmpFrame = CGRectMake(x, y, indicatorFrame.size.width, indicatorFrame.size.height);
	self.selectionIndicatorView.frame = tmpFrame;
	[self addSubview:self.selectionIndicatorView];
}

// create a UILabel for this element.
- (V8HorizontalPickerLabel *)labelForForElementAtIndex:(NSInteger)index withTitle:(NSString *)title {
	CGRect labelFrame     = [self frameForElementAtIndex:index];
	V8HorizontalPickerLabel *elementLabel = [[V8HorizontalPickerLabel alloc] initWithFrame:labelFrame];

	elementLabel.textAlignment   = NSTextAlignmentCenter;
	elementLabel.backgroundColor = self.backgroundColor;
	elementLabel.text            = title;
	elementLabel.font            = self.elementFont;

	elementLabel.normalStateColor   = self.textColor;
	elementLabel.selectedStateColor = self.selectedTextColor;

	// show selected status if this element is the selected one and is currently over selectionPoint
	NSInteger currentIndex = [self nearestElementToCenter];
	elementLabel.selectedElement = (self.currentSelectedIndex == index) && (currentIndex == self.currentSelectedIndex);

	return elementLabel;
}

#pragma mark - DataSource Calling Method (Internal Method)
- (void)getNumberOfElementsFromDataSource {
	SEL dataSourceCall = @selector(numberOfElementsInHorizontalPickerView:);
	if (self.dataSource && [self.dataSource respondsToSelector:dataSourceCall]) {
		_numberOfElements = [self.dataSource numberOfElementsInHorizontalPickerView:self];
	} else {
		_numberOfElements = 0;
	}
}

#pragma mark - Delegate Calling Method (Internal Method)
- (void)getElementWidthsFromDelegate {
	SEL delegateCall = @selector(horizontalPickerView:widthForElementAtIndex:);
	[self.elementWidths removeAllObjects];
	for (int i = 0; i < self.numberOfElements; i++) {
		if (self.delegate && [self.delegate respondsToSelector:delegateCall]) {
			NSInteger width = [self.delegate horizontalPickerView:self widthForElementAtIndex:i];
			[self.elementWidths addObject:[NSNumber numberWithInteger:width]];
		}
	}
}

#pragma mark - View Calculation and Manipulation Methods (Internal Methods)
// what is the total width of the content area?
- (void)setTotalWidthOfScrollContent {
	NSInteger totalWidth = 0;

	totalWidth += [self leftScrollEdgeWidth];
	totalWidth += [self rightScrollEdgeWidth];

	// sum the width of all elements
	for (NSNumber *width in self.elementWidths) {
		totalWidth += [width intValue];
		totalWidth += self.elementPadding;
	}
	// TODO: is this necessary?
	totalWidth -= self.elementPadding; // we add "one too many" in for loop

	if (_scrollView) {
		// create our scroll view as wide as all the elements to be included
		_scrollView.contentSize = CGSizeMake(totalWidth, self.bounds.size.height);
		self.scrollSizeHasBeenSet = YES;
	}
}

// reset the content inset of the scroll view based on centering first and last elements.
- (void)updateScrollContentInset {
	// update content inset if we have element widths
	if ([self.elementWidths count] != 0) {
		CGFloat scrollerWidth = _scrollView.frame.size.width;

		CGFloat halfFirstWidth = 0.0f;
		CGFloat halfLastWidth  = 0.0f;
		if ( [self.elementWidths count] > 0 ) {
			halfFirstWidth = [[self.elementWidths objectAtIndex:0] floatValue] / 2.0;
			halfLastWidth  = [[self.elementWidths lastObject] floatValue]      / 2.0;
		}

		// calculating the inset so that the bouncing on the ends happens more smooothly
		// - first inset is the distance from the left edge to the left edge of the
		//     first element when that element is centered under the selection point.
		//     - represented below as the # area
		// - last inset is the distance from the right edge to the right edge of
		//     the last element when that element is centered under the selection point.
		//     - represented below as the * area
		//
		//        Selection
		//  +---------|---------------+
		//  |####| Element |**********| << UIScrollView
		//  +-------------------------+
		CGFloat firstInset = self.selectionPoint.x - halfFirstWidth;
		firstInset -= [self leftScrollEdgeWidth];
		CGFloat lastInset  = (scrollerWidth - self.selectionPoint.x) - halfLastWidth;
		lastInset -= [self rightScrollEdgeWidth];

		_scrollView.contentInset = UIEdgeInsetsMake(0, firstInset, 0, lastInset);
	}
}

// what is the left-most edge of the element at the given index?
- (NSInteger)offsetForElementAtIndex:(NSInteger)index {
	NSInteger offset = 0;
	if (index >= [self.elementWidths count]) {
		return 0;
	}

	offset += [self leftScrollEdgeWidth];

	for (int i = 0; i < index && i < [self.elementWidths count]; i++) {
		offset += [[self.elementWidths objectAtIndex:i] intValue];
		offset += self.elementPadding;
	}
	return offset;
}

// return the tag for an element at a given index
- (NSInteger)tagForElementAtIndex:(NSInteger)index {
	return (index + 1) * 10;
}

// return the index given an element's tag
- (NSInteger)indexForElement:(UIView *)element {
	return (element.tag / 10) - 1;
}

// what is the center of the element at the given index?
- (NSInteger)centerOfElementAtIndex:(NSInteger)index {
	if (index >= [self.elementWidths count]) {
		return 0;
	}

	NSInteger elementOffset = [self offsetForElementAtIndex:index];
	NSInteger elementWidth  = [[self.elementWidths objectAtIndex:index] intValue] / 2;
	return elementOffset + elementWidth;
}

// what is the frame for the element at the given index?
- (CGRect)frameForElementAtIndex:(NSInteger)index {
	CGFloat width = 0.0f;
	if ([self.elementWidths count] > index) {
		width = [[self.elementWidths objectAtIndex:index] intValue];
	}
	return CGRectMake([self offsetForElementAtIndex:index], 0.0f, width, self.frame.size.height);
}

// what is the frame for the left scroll edge view?
- (CGRect)frameForLeftScrollEdgeView {
	if (self.leftScrollEdgeView) {
		CGFloat scrollHeight = _scrollView.contentSize.height;
		CGFloat viewHeight   = self.leftScrollEdgeView.frame.size.height;
		return CGRectMake(0.0f, ((scrollHeight / 2.0f) - (viewHeight / 2.0f)),
						  self.leftScrollEdgeView.frame.size.width, viewHeight);
	} else {
		return CGRectZero;
	}
}

// what is the width of the left edge of the scroll area?
- (CGFloat)leftScrollEdgeWidth {
	if (self.leftScrollEdgeView) {
		CGFloat width = self.leftScrollEdgeView.frame.size.width;
		width += self.scrollEdgeViewPadding;
		return width;
	}
	return 0.0f;
}

// what is the frame for the right scroll edge view?
- (CGRect)frameForRightScrollEdgeView {
	if (self.rightScrollEdgeView) {
		CGFloat scrollWidth  = _scrollView.contentSize.width;
		CGFloat scrollHeight = _scrollView.contentSize.height;
		CGFloat viewWidth  = self.rightScrollEdgeView.frame.size.width;
		CGFloat viewHeight = self.rightScrollEdgeView.frame.size.height;
		return CGRectMake(scrollWidth - viewWidth, ((scrollHeight / 2.0f) - (viewHeight / 2.0f)),
						  viewWidth, viewHeight);
	} else {
		return CGRectZero;
	}
}

// what is the width of the right edge of the scroll area?
- (CGFloat)rightScrollEdgeWidth {
	if (self.rightScrollEdgeView) {
		CGFloat width = self.rightScrollEdgeView.frame.size.width;
		width += self.scrollEdgeViewPadding;
		return width;
	}
	return 0.0f;
}

// what is the "center", relative to the content offset and adjusted to selection point?
- (CGPoint)currentCenter {
	CGFloat x = _scrollView.contentOffset.x + self.selectionPoint.x;
	return CGPointMake(x, 0.0f);
}

// what is the element nearest to the center of the view?
- (NSInteger)nearestElementToCenter {
	return [self nearestElementToPoint:[self currentCenter]];
}

// what is the element nearest to the given point?
- (NSInteger)nearestElementToPoint:(CGPoint)point {
	for (int i = 0; i < self.numberOfElements; i++) {
		CGRect frame = [self frameForElementAtIndex:i];
		if (CGRectContainsPoint(frame, point)) {
			return i;
		} else if (point.x < frame.origin.x) {
			// if the center is before this element, go back to last one,
			//     unless we're at the beginning
			if (i > 0) {
				return i - 1;
			} else {
				return 0;
			}
			break;
		} else if (point.x > frame.origin.y) {
			// if the center is past the last element, scroll to it
			if (i == self.numberOfElements - 1) {
				return i;
			}
		}
	}
	return 0;
}

// similar to nearestElementToPoint: however, this method does not look past beginning/end
- (NSInteger)elementContainingPoint:(CGPoint)point {
	for (int i = 0; i < self.numberOfElements; i++) {
		CGRect frame = [self frameForElementAtIndex:i];
		if (CGRectContainsPoint(frame, point)) {
			return i;
		}
	}
	return -1;
}

// move scroll view to position nearest element under the center
- (void)scrollToElementNearestToCenter {
	[self scrollToElement:[self nearestElementToCenter] animated:YES];
}

#pragma mark - Tap Gesture Recognizer Handler Method
// use the gesture recognizer to slide to element under tap
- (void)scrollViewTapped:(UITapGestureRecognizer *)recognizer {
	if (recognizer.state == UIGestureRecognizerStateRecognized) {
		CGPoint tapLocation    = [recognizer locationInView:_scrollView];
		NSInteger elementIndex = [self elementContainingPoint:tapLocation];
		if (elementIndex != -1) { // point not in element
			[self scrollToElement:elementIndex animated:YES];
		}
	}
}

@end

// ------------------------------------------------------------------------
#pragma mark - Picker Label Implementation
@implementation V8HorizontalPickerLabel : UILabel

- (void)setSelectedElement:(BOOL)selected {
	if (self.selectedElement != selected) {
		if (selected) {
			self.textColor = self.selectedStateColor;
		} else {
			self.textColor = self.normalStateColor;
		}
		_selectedElement = selected;
		[self setNeedsLayout];
	}
}

- (void)setNormalStateColor:(UIColor *)color {
	if (self.normalStateColor != color) {
		_normalStateColor = color;
		self.textColor = self.normalStateColor;
		[self setNeedsLayout];
	}
}

@end


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

package bitmanipulation;

import java.util.ArrayList;
import java.util.List;

/**
 * <pre>
 * check 'Done?' firstly
 *  1 can save:
 *          if (word.length() == 0) { //
 *              r.add(word);
 *              return r;
 *          }
 *         As "" == new String("", 0, 0));
 *  2 check stop in one place, make code structure more clear.
 */
public class Leetcode320GeneralizedAbbreviation3_2 {
    // runtime:
    private static List<String> r;
    private static char[] chars;

    private static char[] abbr;

    public static List<String> generateAbbreviations(String word) {
        r = new ArrayList();
        if (word == null) {
            return r;
        }

        chars = word.toCharArray();
        abbr = new char[word.length()];
        abbrBy(0, 0);
        return r;
    }

    private static void abbrBy(final int fillACharTo, final int byCur) {
        if (byCur == chars.length) {
            r.add(new String(abbr, 0, fillACharTo));
            return;
        }

        abbr[fillACharTo] = chars[byCur];
        abbrBy(fillACharTo + 1, byCur + 1);

        int w10 = 1;
        while (w10 <= chars.length - byCur) {
            int cw = w10;
            int fillACharNumTo = fillACharTo;

            if (cw >= 10) {
                abbr[fillACharNumTo++] = (char) (cw / 10 + '0');
                cw = cw - cw / 10 * 10;
            }
            abbr[fillACharNumTo] = (char) (cw + '0');

            int nextFrom = byCur + w10;
            if (nextFrom == chars.length) {
                abbrBy(fillACharNumTo + 1, nextFrom);
            } else {
                abbr[fillACharNumTo + 1] = chars[nextFrom];
                abbrBy(fillACharNumTo + 2, nextFrom + 1);
            }
            w10++;
        }
    }
}


text:
<video id="media" controls>
</video>

<script>
    Media = document.getElementById("media");
    Media.src = "/VideoCMS/video_download";
</script>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SecureUWPChannel.Serialization;

namespace SecureUWPChannel.Interfaces
{
    public interface IOCallbackAsync
    {
        Task SendDHEncryptedMessage(String Message);
        Task<String> ReceiveDHEncryptedMessage(String PublicKey);
    }
}


text:
<resources>
    <declare-styleable name="ProcessButton">
        <attr name="progressText" format="string" />
        <attr name="completeText" format="string" />
        <attr name="colorProgress" format="color" />
        <attr name="colorComplete" format="color" />
    </declare-styleable>

    <declare-styleable name="FlatButton">
        <attr name="colorPressed" format="color" />
        <attr name="colorNormal" format="color" />
    </declare-styleable>
</resources>


text:
import { connect } from 'react-redux';
import { clearCompleted, applyFilter } from './footerActions';
import { ALL, ACTIVE, COMPLETED } from './../../state/filterTypes';

import Footer from './Footer.view';

const mapStateToProps = state => ({
  showFooter: state.get('todos').size !== 0,
  canClearCompleted: state.get('todos').some(todo => todo.get('complete')),
  numIncomplete: state.get('todos').reduce((count, todo) => !todo.get('complete') && !todo.get('isDeleted') ? count + 1 : count, 0),
  numTotal: state.get('todos').reduce((count, todo) => todo.get('text') ? count + 1 : count, 0),
  numInDeleted: state.get('todos').reduce((count, todo) => todo.get('isDeleted') ? count + 1 : count, 0),
  showAll: state.get('filter') === ALL,
  showActive: state.get('filter') === ACTIVE,
  showCompleted: state.get('filter') === COMPLETED
});

const mapDispatchToProps = dispatch => ({
  clearCompleted: () => {
    dispatch(clearCompleted());
  },
  filterAll: () => {
    dispatch(applyFilter(ALL));
  },
  filterActive: () => {
    dispatch(applyFilter(ACTIVE));
  },
  filterCompleted: () => {
    dispatch(applyFilter(COMPLETED));
  }
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(Footer);


text:
from tools.docco.rl_doc_utils import *

heading1("Writing your own $Flowable$ Objects")
disc("""
Flowables are intended to be an open standard for creating
reusable report content, and you can easily create your
own objects.  We hope that over time we will build up
a library of contributions, giving reportlab users a
rich selection of charts, graphics and other "report
widgets" they can use in their own reports. This section
shows you how to create your own flowables.""")

todo("""we should put the Figure class in the
standard library, as it is a very useful base.""")

heading2("A very simple $Flowable$")

disc("""
Recall the $hand$ function from the $pdfgen$ section of this user guide which
generated a drawing of a hand as a closed figure composed from Bezier curves.
""")
illust(examples.hand, "a hand")
disc("""
To embed this or any other drawing in a Platypus flowable we must define a
subclass of $Flowable$
with at least a $wrap$ method and a $draw$ method.
""")
eg(examples.testhandannotation)
disc("""
The $wrap$ method must provide the size of the drawing -- it is used by
the Platypus mainloop to decide whether this element fits in the space remaining
on the current frame.  The $draw$ method performs the drawing of the object after
the Platypus mainloop has translated the $(0,0)$ origin to an appropriate location
in an appropriate frame.
""")
disc("""
Below are some example uses of the $HandAnnotation$ flowable.
""")

from reportlab.lib.colors import blue, pink, yellow, cyan, brown
from reportlab.lib.units import inch

handnote()

disc("""The default.""")

handnote(size=inch)

disc("""Just one inch high.""")

handnote(xoffset=3*inch, size=inch, strokecolor=blue, fillcolor=cyan)

disc("""One inch high and shifted to the left with blue and cyan.""")

heading2("Modifying a Built in $Flowable$")
disc("""To modify an existing flowable, you should create a derived class
and override the methods you need to change to get the desired behaviour""")
disc("""As an example to create a rotated image you need to override the wrap
and draw methods of the existing Image class""")
import os
from reportlab.platypus import *
I = '../images/replogo.gif'

EmbeddedCode("""
class RotatedImage(Image):
    def wrap(self,availWidth,availHeight):
        h, w = Image.wrap(self,availHeight,availWidth)
        return w, h
    def draw(self):
        self.canv.rotate(90)
        Image.draw(self)
I = RotatedImage('%s')
I.hAlign = 'CENTER'
""" % I,'I')


text:
<?php

require_once dirname(__FILE__).'/../lib/product_to_contentGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/product_to_contentGeneratorHelper.class.php';

/**
 * product_to_content actions.
 *
 * @package    CMS
 * @subpackage product_to_content
 * @author     Lkhagva-Ochir Narmandakh
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class product_to_contentActions extends autoProduct_to_contentActions
{
    public function preExecute()
    {
        $this->getUser()->setFlash('mainmenu', 'content');
        parent::preExecute();
    }
}


text:
<link rel="import" href="../paper-input/paper-input.hmtl">
<link rel="import" href="./filho-cordova.html">

<dom-module id="hello-cordova">
    <template>

Oi <filho-cordova name="{{name}}"></filho-cordova>

         Link do perfil
        <paper-input label="Escreva seu nome" value={{name}} type="search"></paper-input>
        <paper-input label="Escreva seu perfil" value={{link}} type="search"></paper-input>
    </template>

</dom-module>


text:
nohup dstat -tcm --output /home/panfengfeng/trace_log/in-memory/movies/readwhilewriting_wiredtiger_no_lsm_3_over_99 2 > nohup.out &

file=/datainssd/publicdata/movies/movies.txt
record_num=7911684
read_num=7911684
cachesize=3110962490
dirname=/mnt/datamemory
ratio=99

rm -rf $dirname/*
echo "####Now, running wiredtiger benchmark"
echo 3 > /proc/sys/vm/drop_caches
free -m
date
../../db_movies_wiredtiger_overwrite --benchmarks=fillrandom --num=$record_num --db=$dirname --use_lsm=0 --resource_data=$file
free -m
date
du -s -b $dirname
echo "####wiredtiger benchmark finish"

echo "####Now, running wiredtiger benchmark"
echo 3 > /proc/sys/vm/drop_caches
free -m
date
../../db_movies_wiredtiger_overwrite --benchmarks=readwhilewriting --num=$record_num --reads=$read_num --db=$dirname --use_lsm=0 --cache_size=$cachesize --use_existing_db=1 --threads=8 --resource_data=$file --read_ratio=$ratio
free -m
date
echo "####wiredtiger benchmark finish"
du -s -b $dirname

dstatpid=`ps aux | grep dstat | awk '{if($0 !~ "grep"){print $2}}'`
for i in $dstatpid
do
        kill -9 $i
done


text:
package org.moskito.central.storage.tsdb;

import org.configureme.annotations.Configure;
import org.configureme.annotations.ConfigureMe;

/**
 * OpenTSDBStorageConfigEntry class.
 *
 * @author esmakula
 * @since 10.10.13
 */
@ConfigureMe
public class OpenTSDBStorageConfigEntry {
	/**
	 * Included interval names, comma separated or '*'.
	 */
	@Configure
	private String includedIntervals;

	/**
	 * Excluded interval names, comma separated.
	 */
	@Configure
	private String excludedIntervals;

	/**
	 * Included producer names, comma separated or '*'.
	 */
	@Configure
	private String includedProducers;

	/**
	 * Excluded producer names, comma separated.
	 */
	@Configure
	private String excludedProducers;

	/**
	 * Included stat names, comma separated or '*'.
	 */
	@Configure
	private String includedStats;

	/**
	 * Excluded stat names, comma separated.
	 */
	@Configure
	private String excludedStats;

	public String getIncludedIntervals() {
		return includedIntervals;
	}

	public void setIncludedIntervals(String includedIntervals) {
		this.includedIntervals = includedIntervals;
	}

	public String getExcludedIntervals() {
		return excludedIntervals;
	}

	public void setExcludedIntervals(String excludedIntervals) {
		this.excludedIntervals = excludedIntervals;
	}

	public String getIncludedProducers() {
		return includedProducers;
	}

	public void setIncludedProducers(String includedProducers) {
		this.includedProducers = includedProducers;
	}

	public String getExcludedProducers() {
		return excludedProducers;
	}

	public void setExcludedProducers(String excludedProducers) {
		this.excludedProducers = excludedProducers;
	}

	public String getIncludedStats() {
		return includedStats;
	}

	public void setIncludedStats(String includedStats) {
		this.includedStats = includedStats;
	}

	public String getExcludedStats() {
		return excludedStats;
	}

	public void setExcludedStats(String excludedStats) {
		this.excludedStats = excludedStats;
	}

	@Override
	public String toString() {
		return "OpenTSDBStorageConfigEntry{" +
				"includedIntervals='" + includedIntervals + '\'' +
				", excludedIntervals='" + excludedIntervals + '\'' +
				", includedProducers='" + includedProducers + '\'' +
				", excludedProducers='" + excludedProducers + '\'' +
				", includedStats='" + includedStats + '\'' +
				", excludedStats='" + excludedStats + '\'' +
				'}';
	}
}


text:
python samples/xml_context_writer.py
cat person_context.xml


text:
struct AVLNode {
    long val;
    int rightNodes;
    int high;
    AVLNode* left;
    AVLNode* right;
    AVLNode(long v): val(v), rightNodes(0), high(0), left(nullptr), right(nullptr) {}
};
struct AVLTree {
public:
    AVLNode* root;
    void insert(long value) {
        root = helpInsert(root, value);
    }
    int findMax(long key) {
        return helpFind(root, key);
    }
    AVLTree(long v) {
        root = new AVLNode(v);
    }
private:
    AVLNode* rotateLeft (AVLNode* root) {
        AVLNode* tmp = root->left;
        root->left = tmp->right;
        tmp->right = root;
        tmp->rightNodes += root->rightNodes + 1;
        root->high = max(height(root->left), height(root->right)) + 1;
        tmp->high = max(height(tmp->left), height(tmp->right)) + 1;
        return tmp;
    }
    AVLNode* rotateRight (AVLNode* root) {
        AVLNode* tmp = root->right;
        root->right = tmp->left;
        tmp->left = root;
        root->rightNodes -= (tmp->rightNodes + 1);
        root->high = max(height(root->left), height(root->right)) + 1;
        tmp->high = max(height(tmp->left), height(tmp->right)) + 1;
        return tmp;
    }
    AVLNode* doubleLeft (AVLNode* root) {
        root->left = rotateRight(root->left);
        return rotateLeft(root);
    }
    AVLNode* doubleRight (AVLNode* root) {
        root->right = rotateLeft(root->right);
        return rotateRight(root);
    }
    int height(AVLNode* avl) {
        if (!avl) return -1;
        else return avl->high;
    }
    AVLNode* helpInsert(AVLNode* root, long value) {
        if (!root) {
            root = new AVLNode(value);
        }
        else if (value < root->val) {
            root->left = helpInsert(root->left, value);
            if (height(root->left) - height(root->right) == 2) {
                if (value < root->left->val) {
                    root = rotateLeft(root);
                }
                else {
                    root = doubleLeft(root);
                }
            }
        }
        else {
            ++root->rightNodes;
            root->right = helpInsert(root->right, value);
            if (height(root->right) - height(root->left) == 2) {
                if (value >= root->right->val) {
                    root = rotateRight(root);
                }
                else {
                    root = doubleRight(root);
                }
            }
        }
        root->high = max(height(root->left), height(root->right)) + 1;
        return root;
    }
    int helpFind(AVLNode* root, long key) {
        if (!root) return -1;
        int res = 0;
        while (root) {
            if (root->val > key) {
                res += root->rightNodes + 1;
                root = root->left;
            }
            else {
                root = root->right;
            }
        }
        return res;
    }
};
class Solution {
public:
    int reversePairs(vector<int>& nums) {
        if (nums.size() < 2) return 0;
        AVLTree avl(nums[0]);
        int res = 0;
        for (int j = 1; j < nums.size(); ++j) {
            res += avl.findMax(2 * static_cast<long>(nums[j]));
            avl.insert(static_cast<long>(nums[j]));
        }
        return res;
    }
};


text:
#pragma once
#ifndef EXEC_H
#define EXEC_H

#include <sys/stat.h>
#include <sys/types.h>
#include <errno.h>
#include <unistd.h>
#include "parser.h"
#include "display.h"
#include "draw.h"
#include "stack.h"
#include "symtab.h"
#include "y.tab.h"

/*
 * vary_node holds a pointer to a knob in the SYMTAB, the next value for the
 * knob, and a pointer to the next vary_node in its linked list
 */
struct vary_node {
    SYMTAB *knob;
    double next_value;
    struct vary_node *next;
};

/* _screen holds all the colors/pixels that have been drawn */
extern screen _screen;
/* num_frames holds the number of frames specified for the current animation */
extern int num_frames;
/* basename specifies the base name of the frame image files */
extern char *basename;
/* Array of vary_node linked-lists */
extern struct vary_node **vary_knobs;

/*======== screen exec() ==========
Inputs:     char return_screen
Returns:
Executes the mdl commands (opcodes in the global op array).
If return_screen is TRUE (i.e. not 0), then the screen that results from
executing the mdl commands is returned.
=================================*/
screen exec(char return_screen);

/*======== void parse_animation_cmds() ==========
Inputs:
Returns:
Parses the animation-related mdl commands and sets the necessary knobs and other
variables needed for later execution.
===============================================*/
void parse_animation_cmds();

/*======== void exec_animation() ==========
Inputs:
Returns:
Creates an animation by iteratively executing the mdl commands and saving the
resulting frames to a `frames/` folder in the current directory.
=========================================*/
void exec_animation();

/*======== void apply_trans_and_draw() ==========
Inputs:     struct matrix **tmp
            struct stack *s
            screen *_screen
            color *c
            struct matrix **pts
Returns:
Applies the topmost transformation matrix in the stack to the `pts` matrix and
draws the resulting points to the screen. Automatically handles freeing and
reallocating the `pts` matrix.
===============================================*/
void apply_trans_and_draw(struct matrix **tmp,
                          struct stack *s,
                          screen *_screen,
                          color *c,
                          struct matrix **pts);

/*======== void get_vary_knobs_tail() ==========
Inputs:     int frame
Returns:
A utility function to get the tail of the `vary_knobs` array linked list for the
specified frame.
==============================================*/
struct vary_node *get_vary_knobs_tail(int frame);

/*======== char vary_node_uniq() ==========
Inputs:     int frame
            SYMTAB *knob
Returns:
A utility function to determine if a SYMTAB *knob is not already in the
`vary_node` linked list for the given frame number. Returns FALSE (0) if the
knob is not in a vary_node, and TRUE (1) otherwise.
=========================================*/
char vary_node_uniq(int frame, SYMTAB *knob);

/*======== char allocate_vary_knobs() ==========
Inputs:
Returns:
A utility function to allocate and initialize the `vary_knobs` array.
==============================================*/
void allocate_vary_knobs();

/*======== char free_exec_screen() ==========
Inputs:
Returns:
A utility function to free the `_screen` used in exec().
===========================================*/
void free_exec_screen();

/*======== char free_vary_knobs() ==========
Inputs:
Returns:
A utility function to free the `vary_knobs` array.
==========================================*/
void free_vary_knobs();

/*======== char free_all() ==========
Inputs:
Returns:
A utility function to free all known currently allocated memory. This should be
called prior to exiting.
===================================*/
void free_all();
#endif


text:
require 'spec_helper'

describe "Modules" do
  context "A custom module with a main-apps controller" do
    before { authorize_as_admin }

    it "should have a button in main_navigation, pointing to the configured controller" do
      Alchemy::Modules.register_module(
        {
          name: 'events',
          navigation: {
            icon: 'icon events',
            name: 'Events',
            controller: '/admin/events',
            action: 'index'
          }
        })
      visit '/admin'
      click_on 'Events'
      expect(page).not_to have_content('Upps!')
    end

  end
end


text:
set -o errexit
set -o nounset
set -o pipefail

KUBE_ROOT=$(dirname "${BASH_SOURCE}")/../..

: ${KUBECTL:=${KUBE_ROOT}/cluster/kubectl.sh}
: ${KUBE_CONFIG_FILE:="config-test.sh"}

export KUBECTL KUBE_CONFIG_FILE

source "${KUBE_ROOT}/cluster/kube-util.sh"

prepare-e2e

#TODO(colhom): spec and implement federated version of this
${KUBECTL} get nodes --no-headers | wc -l


text:
.class public Landroid/app/Application;
.super Landroid/content/ContextWrapper;
.source "Application.java"

# interfaces
.implements Landroid/content/ComponentCallbacks2;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Landroid/app/Application$ActivityLifecycleCallbacks;,
        Landroid/app/Application$OnProvideAssistDataListener;
    }
.end annotation

# instance fields
.field private mActivityLifecycleCallbacks:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Landroid/app/Application$ActivityLifecycleCallbacks;",
            ">;"
        }
    .end annotation
.end field

.field private mAssistCallbacks:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Landroid/app/Application$OnProvideAssistDataListener;",
            ">;"
        }
    .end annotation
.end field

.field private mComponentCallbacks:Ljava/util/ArrayList;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "Ljava/util/ArrayList",
            "<",
            "Landroid/content/ComponentCallbacks;",
            ">;"
        }
    .end annotation
.end field

.field public mLoadedApk:Landroid/app/LoadedApk;

# direct methods
.method public constructor <init>()V
    .locals 2

    .prologue
    const/4 v1, 0x0

    .line 81
    invoke-direct {p0, v1}, Landroid/content/ContextWrapper;-><init>(Landroid/content/Context;)V

    .line 47
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    .line 46
    iput-object v0, p0, Landroid/app/Application;->mComponentCallbacks:Ljava/util/ArrayList;

    .line 49
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    .line 48
    iput-object v0, p0, Landroid/app/Application;->mActivityLifecycleCallbacks:Ljava/util/ArrayList;

    .line 50
    iput-object v1, p0, Landroid/app/Application;->mAssistCallbacks:Ljava/util/ArrayList;

    .line 80
    return-void
.end method

.method private collectActivityLifecycleCallbacks()[Ljava/lang/Object;
    .locals 3

    .prologue
    .line 267
    const/4 v0, 0x0

    .line 268
    .local v0, "callbacks":[Ljava/lang/Object;
    iget-object v2, p0, Landroid/app/Application;->mActivityLifecycleCallbacks:Ljava/util/ArrayList;

    monitor-enter v2

    .line 269
    :try_start_0
    iget-object v1, p0, Landroid/app/Application;->mActivityLifecycleCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v1}, Ljava/util/ArrayList;->size()I

    move-result v1

    if-lez v1, :cond_0

    .line 270
    iget-object v1, p0, Landroid/app/Application;->mActivityLifecycleCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v1}, Ljava/util/ArrayList;->toArray()[Ljava/lang/Object;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v0

    .end local v0    # "callbacks":[Ljava/lang/Object;
    :cond_0
    monitor-exit v2

    .line 273
    return-object v0

    .line 268
    .restart local v0    # "callbacks":[Ljava/lang/Object;
    :catchall_0
    move-exception v1

    monitor-exit v2

    throw v1
.end method

.method private collectComponentCallbacks()[Ljava/lang/Object;
    .locals 3

    .prologue
    .line 257
    const/4 v0, 0x0

    .line 258
    .local v0, "callbacks":[Ljava/lang/Object;
    iget-object v2, p0, Landroid/app/Application;->mComponentCallbacks:Ljava/util/ArrayList;

    monitor-enter v2

    .line 259
    :try_start_0
    iget-object v1, p0, Landroid/app/Application;->mComponentCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v1}, Ljava/util/ArrayList;->size()I

    move-result v1

    if-lez v1, :cond_0

    .line 260
    iget-object v1, p0, Landroid/app/Application;->mComponentCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v1}, Ljava/util/ArrayList;->toArray()[Ljava/lang/Object;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    move-result-object v0

    .end local v0    # "callbacks":[Ljava/lang/Object;
    :cond_0
    monitor-exit v2

    .line 263
    return-object v0

    .line 258
    .restart local v0    # "callbacks":[Ljava/lang/Object;
    :catchall_0
    move-exception v1

    monitor-exit v2

    throw v1
.end method

# virtual methods
.method final attach(Landroid/content/Context;)V
    .locals 1
    .param p1, "context"    # Landroid/content/Context;

    .prologue
    .line 187
    invoke-virtual {p0, p1}, Landroid/app/Application;->attachBaseContext(Landroid/content/Context;)V

    .line 188
    invoke-static {p1}, Landroid/app/ContextImpl;->getImpl(Landroid/content/Context;)Landroid/app/ContextImpl;

    move-result-object v0

    iget-object v0, v0, Landroid/app/ContextImpl;->mPackageInfo:Landroid/app/LoadedApk;

    iput-object v0, p0, Landroid/app/Application;->mLoadedApk:Landroid/app/LoadedApk;

    .line 186
    return-void
.end method

.method dispatchActivityCreated(Landroid/app/Activity;Landroid/os/Bundle;)V
    .locals 3
    .param p1, "activity"    # Landroid/app/Activity;
    .param p2, "savedInstanceState"    # Landroid/os/Bundle;

    .prologue
    .line 192
    invoke-direct {p0}, Landroid/app/Application;->collectActivityLifecycleCallbacks()[Ljava/lang/Object;

    move-result-object v0

    .line 193
    .local v0, "callbacks":[Ljava/lang/Object;
    if-eqz v0, :cond_0

    .line 194
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_0

    .line 195
    aget-object v2, v0, v1

    check-cast v2, Landroid/app/Application$ActivityLifecycleCallbacks;

    invoke-interface {v2, p1, p2}, Landroid/app/Application$ActivityLifecycleCallbacks;->onActivityCreated(Landroid/app/Activity;Landroid/os/Bundle;)V

    .line 194
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 191
    .end local v1    # "i":I
    :cond_0
    return-void
.end method

.method dispatchActivityDestroyed(Landroid/app/Activity;)V
    .locals 3
    .param p1, "activity"    # Landroid/app/Activity;

    .prologue
    .line 248
    invoke-direct {p0}, Landroid/app/Application;->collectActivityLifecycleCallbacks()[Ljava/lang/Object;

    move-result-object v0

    .line 249
    .local v0, "callbacks":[Ljava/lang/Object;
    if-eqz v0, :cond_0

    .line 250
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_0

    .line 251
    aget-object v2, v0, v1

    check-cast v2, Landroid/app/Application$ActivityLifecycleCallbacks;

    invoke-interface {v2, p1}, Landroid/app/Application$ActivityLifecycleCallbacks;->onActivityDestroyed(Landroid/app/Activity;)V

    .line 250
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 247
    .end local v1    # "i":I
    :cond_0
    return-void
.end method

.method dispatchActivityPaused(Landroid/app/Activity;)V
    .locals 3
    .param p1, "activity"    # Landroid/app/Activity;

    .prologue
    .line 220
    invoke-direct {p0}, Landroid/app/Application;->collectActivityLifecycleCallbacks()[Ljava/lang/Object;

    move-result-object v0

    .line 221
    .local v0, "callbacks":[Ljava/lang/Object;
    if-eqz v0, :cond_0

    .line 222
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_0

    .line 223
    aget-object v2, v0, v1

    check-cast v2, Landroid/app/Application$ActivityLifecycleCallbacks;

    invoke-interface {v2, p1}, Landroid/app/Application$ActivityLifecycleCallbacks;->onActivityPaused(Landroid/app/Activity;)V

    .line 222
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 219
    .end local v1    # "i":I
    :cond_0
    return-void
.end method

.method dispatchActivityResumed(Landroid/app/Activity;)V
    .locals 3
    .param p1, "activity"    # Landroid/app/Activity;

    .prologue
    .line 211
    invoke-direct {p0}, Landroid/app/Application;->collectActivityLifecycleCallbacks()[Ljava/lang/Object;

    move-result-object v0

    .line 212
    .local v0, "callbacks":[Ljava/lang/Object;
    if-eqz v0, :cond_0

    .line 213
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_0

    .line 214
    aget-object v2, v0, v1

    check-cast v2, Landroid/app/Application$ActivityLifecycleCallbacks;

    invoke-interface {v2, p1}, Landroid/app/Application$ActivityLifecycleCallbacks;->onActivityResumed(Landroid/app/Activity;)V

    .line 213
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 210
    .end local v1    # "i":I
    :cond_0
    return-void
.end method

.method dispatchActivitySaveInstanceState(Landroid/app/Activity;Landroid/os/Bundle;)V
    .locals 3
    .param p1, "activity"    # Landroid/app/Activity;
    .param p2, "outState"    # Landroid/os/Bundle;

    .prologue
    .line 238
    invoke-direct {p0}, Landroid/app/Application;->collectActivityLifecycleCallbacks()[Ljava/lang/Object;

    move-result-object v0

    .line 239
    .local v0, "callbacks":[Ljava/lang/Object;
    if-eqz v0, :cond_0

    .line 240
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_0

    .line 241
    aget-object v2, v0, v1

    check-cast v2, Landroid/app/Application$ActivityLifecycleCallbacks;

    invoke-interface {v2, p1, p2}, Landroid/app/Application$ActivityLifecycleCallbacks;->onActivitySaveInstanceState(Landroid/app/Activity;Landroid/os/Bundle;)V

    .line 240
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 237
    .end local v1    # "i":I
    :cond_0
    return-void
.end method

.method dispatchActivityStarted(Landroid/app/Activity;)V
    .locals 3
    .param p1, "activity"    # Landroid/app/Activity;

    .prologue
    .line 202
    invoke-direct {p0}, Landroid/app/Application;->collectActivityLifecycleCallbacks()[Ljava/lang/Object;

    move-result-object v0

    .line 203
    .local v0, "callbacks":[Ljava/lang/Object;
    if-eqz v0, :cond_0

    .line 204
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_0

    .line 205
    aget-object v2, v0, v1

    check-cast v2, Landroid/app/Application$ActivityLifecycleCallbacks;

    invoke-interface {v2, p1}, Landroid/app/Application$ActivityLifecycleCallbacks;->onActivityStarted(Landroid/app/Activity;)V

    .line 204
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 201
    .end local v1    # "i":I
    :cond_0
    return-void
.end method

.method dispatchActivityStopped(Landroid/app/Activity;)V
    .locals 3
    .param p1, "activity"    # Landroid/app/Activity;

    .prologue
    .line 229
    invoke-direct {p0}, Landroid/app/Application;->collectActivityLifecycleCallbacks()[Ljava/lang/Object;

    move-result-object v0

    .line 230
    .local v0, "callbacks":[Ljava/lang/Object;
    if-eqz v0, :cond_0

    .line 231
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_0

    .line 232
    aget-object v2, v0, v1

    check-cast v2, Landroid/app/Application$ActivityLifecycleCallbacks;

    invoke-interface {v2, p1}, Landroid/app/Application$ActivityLifecycleCallbacks;->onActivityStopped(Landroid/app/Activity;)V

    .line 231
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 228
    .end local v1    # "i":I
    :cond_0
    return-void
.end method

.method dispatchOnProvideAssistData(Landroid/app/Activity;Landroid/os/Bundle;)V
    .locals 3
    .param p1, "activity"    # Landroid/app/Activity;
    .param p2, "data"    # Landroid/os/Bundle;

    .prologue
    .line 278
    monitor-enter p0

    .line 279
    :try_start_0
    iget-object v2, p0, Landroid/app/Application;->mAssistCallbacks:Ljava/util/ArrayList;
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    if-nez v2, :cond_0

    monitor-exit p0

    .line 280
    return-void

    .line 282
    :cond_0
    :try_start_1
    iget-object v2, p0, Landroid/app/Application;->mAssistCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v2}, Ljava/util/ArrayList;->toArray()[Ljava/lang/Object;
    :try_end_1
    .catchall {:try_start_1 .. :try_end_1} :catchall_0

    move-result-object v0

    .local v0, "callbacks":[Ljava/lang/Object;
    monitor-exit p0

    .line 284
    if-eqz v0, :cond_1

    .line 285
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_1

    .line 286
    aget-object v2, v0, v1

    check-cast v2, Landroid/app/Application$OnProvideAssistDataListener;

    invoke-interface {v2, p1, p2}, Landroid/app/Application$OnProvideAssistDataListener;->onProvideAssistData(Landroid/app/Activity;Landroid/os/Bundle;)V

    .line 285
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 278
    .end local v0    # "callbacks":[Ljava/lang/Object;
    .end local v1    # "i":I
    :catchall_0
    move-exception v2

    monitor-exit p0

    throw v2

    .line 276
    .restart local v0    # "callbacks":[Ljava/lang/Object;
    :cond_1
    return-void
.end method

.method public onConfigurationChanged(Landroid/content/res/Configuration;)V
    .locals 3
    .param p1, "newConfig"    # Landroid/content/res/Configuration;

    .prologue
    .line 109
    invoke-direct {p0}, Landroid/app/Application;->collectComponentCallbacks()[Ljava/lang/Object;

    move-result-object v0

    .line 110
    .local v0, "callbacks":[Ljava/lang/Object;
    if-eqz v0, :cond_0

    .line 111
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_0

    .line 112
    aget-object v2, v0, v1

    check-cast v2, Landroid/content/ComponentCallbacks;

    invoke-interface {v2, p1}, Landroid/content/ComponentCallbacks;->onConfigurationChanged(Landroid/content/res/Configuration;)V

    .line 111
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 108
    .end local v1    # "i":I
    :cond_0
    return-void
.end method

.method public onCreate()V
    .locals 0

    .prologue
    .line 94
    return-void
.end method

.method public onLowMemory()V
    .locals 3

    .prologue
    .line 119
    invoke-direct {p0}, Landroid/app/Application;->collectComponentCallbacks()[Ljava/lang/Object;

    move-result-object v0

    .line 120
    .local v0, "callbacks":[Ljava/lang/Object;
    if-eqz v0, :cond_0

    .line 121
    const/4 v1, 0x0

    .local v1, "i":I
    :goto_0
    array-length v2, v0

    if-ge v1, v2, :cond_0

    .line 122
    aget-object v2, v0, v1

    check-cast v2, Landroid/content/ComponentCallbacks;

    invoke-interface {v2}, Landroid/content/ComponentCallbacks;->onLowMemory()V

    .line 121
    add-int/lit8 v1, v1, 0x1

    goto :goto_0

    .line 118
    .end local v1    # "i":I
    :cond_0
    return-void
.end method

.method public onTerminate()V
    .locals 0

    .prologue
    .line 104
    return-void
.end method

.method public onTrimMemory(I)V
    .locals 4
    .param p1, "level"    # I

    .prologue
    .line 129
    invoke-direct {p0}, Landroid/app/Application;->collectComponentCallbacks()[Ljava/lang/Object;

    move-result-object v1

    .line 130
    .local v1, "callbacks":[Ljava/lang/Object;
    if-eqz v1, :cond_1

    .line 131
    const/4 v2, 0x0

    .local v2, "i":I
    :goto_0
    array-length v3, v1

    if-ge v2, v3, :cond_1

    .line 132
    aget-object v0, v1, v2

    .line 133
    .local v0, "c":Ljava/lang/Object;
    instance-of v3, v0, Landroid/content/ComponentCallbacks2;

    if-eqz v3, :cond_0

    .line 134
    check-cast v0, Landroid/content/ComponentCallbacks2;

    .end local v0    # "c":Ljava/lang/Object;
    invoke-interface {v0, p1}, Landroid/content/ComponentCallbacks2;->onTrimMemory(I)V

    .line 131
    :cond_0
    add-int/lit8 v2, v2, 0x1

    goto :goto_0

    .line 128
    .end local v2    # "i":I
    :cond_1
    return-void
.end method

.method public registerActivityLifecycleCallbacks(Landroid/app/Application$ActivityLifecycleCallbacks;)V
    .locals 2
    .param p1, "callback"    # Landroid/app/Application$ActivityLifecycleCallbacks;

    .prologue
    .line 153
    iget-object v1, p0, Landroid/app/Application;->mActivityLifecycleCallbacks:Ljava/util/ArrayList;

    monitor-enter v1

    .line 154
    :try_start_0
    iget-object v0, p0, Landroid/app/Application;->mActivityLifecycleCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v0, p1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v1

    .line 152
    return-void

    .line 153
    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method public registerComponentCallbacks(Landroid/content/ComponentCallbacks;)V
    .locals 2
    .param p1, "callback"    # Landroid/content/ComponentCallbacks;

    .prologue
    .line 141
    iget-object v1, p0, Landroid/app/Application;->mComponentCallbacks:Ljava/util/ArrayList;

    monitor-enter v1

    .line 142
    :try_start_0
    iget-object v0, p0, Landroid/app/Application;->mComponentCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v0, p1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v1

    .line 140
    return-void

    .line 141
    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method public registerOnProvideAssistDataListener(Landroid/app/Application$OnProvideAssistDataListener;)V
    .locals 1
    .param p1, "callback"    # Landroid/app/Application$OnProvideAssistDataListener;

    .prologue
    .line 165
    monitor-enter p0

    .line 166
    :try_start_0
    iget-object v0, p0, Landroid/app/Application;->mAssistCallbacks:Ljava/util/ArrayList;

    if-nez v0, :cond_0

    .line 167
    new-instance v0, Ljava/util/ArrayList;

    invoke-direct {v0}, Ljava/util/ArrayList;-><init>()V

    iput-object v0, p0, Landroid/app/Application;->mAssistCallbacks:Ljava/util/ArrayList;

    .line 169
    :cond_0
    iget-object v0, p0, Landroid/app/Application;->mAssistCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v0, p1}, Ljava/util/ArrayList;->add(Ljava/lang/Object;)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit p0

    .line 164
    return-void

    .line 165
    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method

.method public unregisterActivityLifecycleCallbacks(Landroid/app/Application$ActivityLifecycleCallbacks;)V
    .locals 2
    .param p1, "callback"    # Landroid/app/Application$ActivityLifecycleCallbacks;

    .prologue
    .line 159
    iget-object v1, p0, Landroid/app/Application;->mActivityLifecycleCallbacks:Ljava/util/ArrayList;

    monitor-enter v1

    .line 160
    :try_start_0
    iget-object v0, p0, Landroid/app/Application;->mActivityLifecycleCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v0, p1}, Ljava/util/ArrayList;->remove(Ljava/lang/Object;)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v1

    .line 158
    return-void

    .line 159
    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method public unregisterComponentCallbacks(Landroid/content/ComponentCallbacks;)V
    .locals 2
    .param p1, "callback"    # Landroid/content/ComponentCallbacks;

    .prologue
    .line 147
    iget-object v1, p0, Landroid/app/Application;->mComponentCallbacks:Ljava/util/ArrayList;

    monitor-enter v1

    .line 148
    :try_start_0
    iget-object v0, p0, Landroid/app/Application;->mComponentCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v0, p1}, Ljava/util/ArrayList;->remove(Ljava/lang/Object;)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    monitor-exit v1

    .line 146
    return-void

    .line 147
    :catchall_0
    move-exception v0

    monitor-exit v1

    throw v0
.end method

.method public unregisterOnProvideAssistDataListener(Landroid/app/Application$OnProvideAssistDataListener;)V
    .locals 1
    .param p1, "callback"    # Landroid/app/Application$OnProvideAssistDataListener;

    .prologue
    .line 174
    monitor-enter p0

    .line 175
    :try_start_0
    iget-object v0, p0, Landroid/app/Application;->mAssistCallbacks:Ljava/util/ArrayList;

    if-eqz v0, :cond_0

    .line 176
    iget-object v0, p0, Landroid/app/Application;->mAssistCallbacks:Ljava/util/ArrayList;

    invoke-virtual {v0, p1}, Ljava/util/ArrayList;->remove(Ljava/lang/Object;)Z
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    :cond_0
    monitor-exit p0

    .line 173
    return-void

    .line 174
    :catchall_0
    move-exception v0

    monitor-exit p0

    throw v0
.end method


text:
package org.apache.nifi.encrypt;

import javax.crypto.SecretKey;

/**
 * Secret Key Provider for Property Encryption
 */
interface PropertySecretKeyProvider {
    /**
     * Get Secret Key using Property Encryption Method with provided password
     *
     * @param propertyEncryptionMethod Property Encryption Method
     * @param password Password used to derive Secret Key
     * @return Derived Secret Key
     */
    SecretKey getSecretKey(PropertyEncryptionMethod propertyEncryptionMethod, String password);
}


text: source /usr/local/pythonenv/pandas-env/bin/activate


text:
package gr.iti.mklab.visual.examples;

import gr.iti.mklab.visual.extraction.AbstractFeatureExtractor;
import gr.iti.mklab.visual.extraction.ColorSURFExtractor;
import gr.iti.mklab.visual.extraction.ImageScaling;
import gr.iti.mklab.visual.extraction.RootSIFTExtractor;
import gr.iti.mklab.visual.extraction.SIFTExtractor;
import gr.iti.mklab.visual.extraction.SURFExtractor;
import gr.iti.mklab.visual.utilities.FeatureIO;
import gr.iti.mklab.visual.utilities.ImageIOGreyScale;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FilenameFilter;

import javax.imageio.ImageIO;

/**
 * Extracts features from images (.jpg or .png files) contained in a directory and writes them in a file for
 * each image. The feature files are written in a directory (named by the name of the feature) that is created
 * (if it does not already exist) in the parent directory of the directory were the images reside.
 *
 * @author Eleftherios Spyromitros-Xioufis
 *
 */
public class FeatureExtraction {

	/**
	 *
	 * @param args
	 *            [0] Full path to the images folder.
	 * @param args
	 *            [1] Maximum number of images to perform feature extraction on, i.e. only the top N images
	 *            returned by File.list will be processed.
	 * @param args
	 *            [2] Number of images to be skipped from extraction (usually 0).
	 * @param args
	 *            [3] Maximum number of pixels that each image will be scaled to (e.g. 196608 for 512x384).
	 * @param args
	 *            [4] Type of features to extract (surf/sift/rootsift/csurf).
	 * @param args
	 *            [5] Whether the features should be written in textual format (txt) / binary format (bin) or
	 *            not written (no).
	 * @throws Exception
	 */
	public static void main(String args[]) throws Exception {

		String imageFolder = args[0];
		int totalImages = Integer.parseInt(args[1]);
		int skipImages = Integer.parseInt(args[2]);
		int maxPixels = Integer.parseInt(args[3]);
		String featureType = args[4];
		String format = args[5];

		ImageScaling scale = new ImageScaling(maxPixels);
		AbstractFeatureExtractor featureExtractor;
		if (featureType.equals("surf")) {
			featureExtractor = new SURFExtractor();
		} else if (featureType.equals("sift")) {
			featureExtractor = new SIFTExtractor();
		} else if (featureType.equals("rootsift")) {
			featureExtractor = new RootSIFTExtractor();
		} else if (featureType.equals("csurf")) {
			featureExtractor = new ColorSURFExtractor();
		} else {
			throw new Exception("Wrong feature type provided.");
		}

		// --------------Load the image files-------------
		File dir = new File(imageFolder);
		FilenameFilter filter = new FilenameFilter() {
			public boolean accept(File dir, String name) {
				if (name.endsWith(".jpg") || name.endsWith(".png"))
					return true;
				else
					return false;
			}
		};
		String[] files = dir.list(filter);

		// create a folder for writing the features
		String featuresFolder = imageFolder + "../" + maxPixels + "_" + featureType;
		File file = new File(featuresFolder);
		if (!file.exists()) {
			if (file.mkdir()) {
				System.out.println("Directory is created!");
			} else {
				System.out.println("Failed to create directory!");
			}
		}

		double totalReadingTime = 0;
		double totalScalingTime = 0;
		double totalWritingTime = 0;
		int extractedCount = 0;
		int limit = Math.min(files.length, totalImages);
		// --------------Extract features for each image-------------
		for (int i = skipImages; i < limit; i++) {
			long start = System.currentTimeMillis();
			System.out.print("Processing image " + (i + 1) + ": ");
			BufferedImage image;
			long startReading = System.currentTimeMillis();
			try { // first try reading with the default class
				image = ImageIO.read(new File(imageFolder + files[i]));
			} catch (IllegalArgumentException e) { // if it fails retry with the corrected class
				// This exception is probably because of a grayscale jpeg image.
				System.out.println("Exception: " + e.getMessage() + " | Image: " + files[i]);
				image = ImageIOGreyScale.read(new File(imageFolder + files[i]));
			} catch (Exception e) { // skip extraction an other exception is thrown
				System.out.println("Exception: " + e.getMessage() + " | Image: " + files[i]);
				continue;
			}
			if (image == null) {
				System.out.println("Null image: " + files[i]);
				continue;
			}
			totalReadingTime += System.currentTimeMillis() - startReading;

			long startScaling = System.currentTimeMillis();
			image = scale.maxPixelsScaling(image);
			totalScalingTime += System.currentTimeMillis() - startScaling;

			double[][] features = featureExtractor.extractFeatures(image);

			// sanity check
			for (int k = 0; k < features.length; k++) {
				if (String.valueOf(features[k][0]).equals("NaN")) {
					System.out.println("NaN feature " + (k + 1) + " in image " + files[i]);
				}
			}

			String imageFileExtension;
			if (files[i].endsWith("jpg")) {
				imageFileExtension = "jpg";
			} else {
				imageFileExtension = "png";
			}
			// write features to file
			long startWring = System.currentTimeMillis();
			if (format.equals("bin")) {
				String featuresFileName = featuresFolder + "/"
						+ files[i].split("\\." + imageFileExtension)[0] + "." + featureType + "b";
				FeatureIO.writeBinary(featuresFileName, features);
			} else if (format.equals("txt")) {
				String featuresFileName = featuresFolder + "/"
						+ files[i].split("\\." + imageFileExtension)[0] + "." + featureType;
				FeatureIO.writeText(featuresFileName, features);
			}
			totalWritingTime += System.currentTimeMillis() - startWring;
			System.out.println("completed in " + (System.currentTimeMillis() - start) + " ms");
			extractedCount++;
		}
		System.out.println("Average reading time in ms: " + totalReadingTime / (double) extractedCount);
		System.out.println("Average scaling time in ms: " + totalScalingTime / (double) extractedCount);
		System.out.println("Average extraction time in ms: " + featureExtractor.getTotalExtractionTime()
				/ (double) extractedCount);
		System.out.println("Average writing time in ms: " + totalWritingTime / (double) extractedCount);
		System.out.println("Average number of interest points per image: "
				+ featureExtractor.getTotalNumberInterestPoints() / (double) extractedCount);

	}
}


text:
drop procedure if exists pridoli_do_maintenance;

delimiter $$

create procedure pridoli_do_maintenance()
  modifies sql data
  begin
    declare exit handler for sqlexception
      begin
        rollback;
        select pridoli_admin_log('Maintenance error.', @pridoli_log_category_error);
      end;

    start transaction;
    call pridoli_check_truncate_logs();
    commit;

    call pridoli_admin_log('Hourly maintenance is done.', @pridoli_log_category_info);
  end$$

delimiter ;


text:
export const DEFAULT_HEIGHT = '100%';
export const DEFAULT_WIDTH = '100%';


text:
package com.ivstuart.tmud.utils;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.StringTokenizer;

/**
 * Point of this is that it is making use of new File NIO Java 1.4 code!!
 * update this to use a JDK7 mechanism to read files.
 */
public class FileHandle {

	private static final Logger LOGGER = LogManager.getLogger();

	private static Charset charset = Charset.forName("ISO-8859-1");

	private static CharsetEncoder encoder = charset.newEncoder();

	private static CharsetDecoder decoder = charset.newDecoder();

	private File file = null;

	private FileChannel wChannel = null;

	private StringTokenizer st = null;

	private String NL = null;

	public FileHandle(String filename) {

		file = new File(filename);
		NL = System.getProperty("line.separator");
	}

	public void close() throws IOException {
		// Close the file
		if (wChannel != null) {
			wChannel.close();
			wChannel = null;
		}

		file = null;
		wChannel = null;
		st = null;

	}

	public String getLine() {
		if (st.hasMoreTokens()) {
			return st.nextToken();
		}
		return null;
	}

	public boolean hasMoreLines() {
		if (st == null) {
			return false;
		}
		return st.hasMoreTokens();
	}

	public String read() throws FileNotFoundException {

		// Allocate buffers
		ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
		CharBuffer charBuffer = CharBuffer.allocate(1024);

		// Create a readable file channel
		FileInputStream fio = new FileInputStream(file);

		FileChannel rChannel = fio.getChannel();

		StringBuilder sb = new StringBuilder();

		// Read response
		try {
			try {
				while ((rChannel.read(buffer)) != -1) {
					buffer.flip();

					// Decode buffer
					decoder.decode(buffer, charBuffer, false);

					// Display
					charBuffer.flip();
					sb.append(charBuffer.toString());
					buffer.clear();
					charBuffer.clear();
				}
			} finally {
				fio.close();
				rChannel.close();
			}
		} catch (IOException e) {
			LOGGER.error("Problem reading file",e);
		}

		st = new StringTokenizer(sb.toString(), NL);

		return sb.toString();

	}

	public void write(String content) throws IOException {
		this.write(content, true);
	}

	public void write(String content, boolean append) throws IOException {

		CharBuffer cbuf = CharBuffer.wrap(content);

		// Create a writable file channel
		if (wChannel == null) {
			wChannel = new FileOutputStream(file, append).getChannel();
		}

		// Write the ByteBuffer contents; the bytes between the ByteBuffer's
		// position and the limit is written to the file
		wChannel.write(encoder.encode(cbuf));
	}

	public void writeln(String content) throws IOException {
		this.write(content + "\n", true);
	}

	public String getName() {
		return file.getName();
	}
}