text:
/*******************************************************************************
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 ******************************************************************************/
package lbms.plugins.mldht.kad;

import static the8472.utils.Functional.unchecked;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.util.Objects;
import java.util.stream.IntStream;
import java.util.stream.Stream;

import lbms.plugins.mldht.kad.DHT.DHTtype;
import lbms.plugins.mldht.kad.utils.AddressUtils;

import the8472.bencode.BEncoder.StringWriter;

public interface NodeList {

	enum AddressType {
		V4, V6;
	}

	AddressType type();

	Stream<KBucketEntry> entries();

	int packedSize();

	default StringWriter writer() {
		return new StringWriter() {

			@Override
			public void writeTo(ByteBuffer buf) {
				entries().forEach(e -> {

					InetSocketAddress sockAddr = e.getAddress();
					InetAddress addr = sockAddr.getAddress();
					buf.put(e.getID().hash);
					buf.put(addr.getAddress());
					buf.putShort((short) sockAddr.getPort());
				});
			}

			@Override
			public int length() {
				return packedSize();
			}
		};
	}

	static NodeList fromBuffer(ByteBuffer src, AddressType type) {
		Objects.requireNonNull(src);
		Objects.requireNonNull(type);

		return new NodeList() {

			@Override
			public int packedSize() {
				return src.remaining();
			}

			@Override
			public Stream<KBucketEntry> entries() {
				ByteBuffer buf = src.slice();

				byte[] rawId = new byte[20];
				byte[] rawAddr = new byte[type == AddressType.V4 ? 4 : 16];

				return IntStream.range(0, packedSize()/(type == AddressType.V4 ? DHTtype.IPV4_DHT.NODES_ENTRY_LENGTH : DHTtype.IPV6_DHT.NODES_ENTRY_LENGTH)).mapToObj(i -> {

					buf.get(rawId);
					buf.get(rawAddr);
					int port = Short.toUnsignedInt(buf.getShort());

					InetAddress addr = unchecked(() -> AddressUtils.fromBytesVerbatim(rawAddr));
					Key id = new Key(rawId);

					return new KBucketEntry(unchecked(() -> new InetSocketAddress(addr, port)), id);
				});
			}

			@Override
			public StringWriter writer() {
				return new StringWriter() {

					@Override
					public void writeTo(ByteBuffer buf) {
						buf.put(src.slice());
					}

					@Override
					public int length() {
						return src.remaining();
					}
				};
			}

			@Override
			public AddressType type() {
				return type;
			}
		};
	}

}


text:
=begin
Copyright 2014 Michal Papis <mpapis@gmail.com>

See the file LICENSE for copying permission.
=end

require 'minitest_helper'
require 'plugins/pre_commit/checks/gpg'

describe PreCommit::Checks::Gpg do
  let(:check){ PreCommit::Checks::Gpg.new(nil, nil, []) }

  describe "private methods" do

    it "finds binaries" do
      check.send(:find_binary, "rake").must_match(/rake$/)
    end

    it "finds GPG" do
      check.send(:gpg_program).must_match(/gpg(2)?$/)
    end

    it "ignores non signed files" do
      Dir.chdir(project_dir) do
        check.send(:get_signature, "file").must_equal(nil)
      end
    end

    it "detects signatures" do
      Dir.chdir(project_dir) do
        check.send(:get_signature, "file.good.asc").must_equal("file.good.asc")
      end
    end

    it "detects signatures by files" do
      Dir.chdir(project_dir) do
        check.send(:get_signature, "file.wrong").must_equal("file.wrong.asc")
      end
    end

    it "errors when no GPG found" do
      check.stubs(:gpg_program).returns(nil)
      check.send(:run_check, "file.asc").to_s.must_equal("No GPG program found to run verification\nfile.asc\n\n")
    end

    it "verifies good signature" do
      Dir.chdir(project_dir) do
        check.send(:run_check, "file.good.asc").must_equal(nil)
      end
    end

    it "errors on wrong signature" do
      Dir.chdir(project_dir) do
        errors =
        check.send(
          :run_check,
          "file.wrong.asc"
        ).errors
        errors.size.must_equal(2)
        errors.map(&:file).must_equal(["file.wrong.asc", "file.wrong.asc"])
        errors[0].message.must_match(/\Agpg: Signature made .* using RSA key ID BF04FF17\Z/)
        errors[1].message.must_match(/\Agpg: BAD signature from "Michal Papis \(RVM signing\) <mpapis@gmail.com>".*\Z/)
      end
    end

  end # private methods

  describe "plugin methods" do

    it "has text description" do
      check.class.description.must_be_kind_of String
    end

    it "succeeds if nothing changed" do
      check.call([]).must_equal nil
    end

    it "succeeds if non signed file changed" do
      Dir.chdir(project_dir) do
        check.call(['file']).must_equal nil
      end
    end

    it "succeeds if matching file changed" do
      Dir.chdir(project_dir) do
        check.call(['file.good']).must_equal nil
      end
    end

    it "succeeds if matching signature file" do
      Dir.chdir(project_dir) do
        check.call(['file.good.asc']).must_equal nil
      end
    end

    it "fails if not matching file changed" do
      Dir.chdir(project_dir) do
        errors = check.call(['file.wrong'])
        errors.size.must_equal(1)
        errors[0].must_be_kind_of(PreCommit::ErrorList)
      end
    end

    it "fails if not matching signature file" do
      Dir.chdir(project_dir) do
        errors = check.call(['file.wrong.asc'])
        errors.size.must_equal(1)
        errors[0].must_be_kind_of(PreCommit::ErrorList)
      end
    end

  end # plugin methods

end

redpajama_set_name: RedPajamaGithub


text:
ActionController::Base.session = {
  :key         => '_dawanda_session',
  :secret      => 'a8185bf2c2ab2571f00e6bf553383faf5c4bf95ad5ae1bc01627a7c65772ec7e589880954a54e01c4e9dfcd970125fe34d4a6b0a4c86bd368b56925116cb9bb9'
}

# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# ActionController::Base.session_store = :active_record_store


text:
CGroupHierarchyHolder::~CGroupHierarchyHolder			()
{
	VERIFY						(m_members.empty());
	VERIFY						(!m_visible_objects);
	VERIFY						(!m_sound_objects);
	VERIFY						(!m_hit_objects);
	VERIFY						(!m_agent_manager);
}

#ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER
void CGroupHierarchyHolder::update_leader				()
{
	m_leader					= 0;
	MEMBER_REGISTRY::iterator	I = m_members.begin();
	MEMBER_REGISTRY::iterator	E = m_members.end();
	for ( ; I != E; ++I)
		if ((*I)->g_Alive()) {
			m_leader			= *I;
			break;
		}
}
#endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER

void CGroupHierarchyHolder::register_in_group			(CEntity *member)
{
	VERIFY						(member);
	MEMBER_REGISTRY::iterator	I = std::find(m_members.begin(),m_members.end(),member);
	VERIFY3						(I == m_members.end(),"Specified group member has already been found",*member->cName());

	if (m_members.empty()) {
		m_visible_objects		= xr_new<VISIBLE_OBJECTS>();
		m_sound_objects			= xr_new<SOUND_OBJECTS>();
		m_hit_objects			= xr_new<HIT_OBJECTS>();

//		m_visible_objects->reserve	(128);
//		m_sound_objects->reserve	(128);
//		m_hit_objects->reserve		(128);
	}

	m_members.push_back			(member);
}

void CGroupHierarchyHolder::register_in_squad			(CEntity *member)
{
#ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER
	if (!leader() && member->g_Alive()) {
		m_leader				= member;
		if (!squad().leader())
			squad().leader		(member);
	}
#endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER
}

void CGroupHierarchyHolder::register_in_agent_manager	(CEntity *member)
{
	if (!get_agent_manager() && smart_cast<CAI_Stalker*>(member)) {
		m_agent_manager								= xr_new<CAgentManager>();
		agent_manager().memory().set_squad_objects	(&visible_objects());
		agent_manager().memory().set_squad_objects	(&sound_objects());
		agent_manager().memory().set_squad_objects	(&hit_objects());
	}

	if (get_agent_manager())
		agent_manager().member().add				(member);
}

void CGroupHierarchyHolder::register_in_group_senses	(CEntity *member)
{
	CCustomMonster			*monster = smart_cast<CCustomMonster*>(member);
	if (monster) {
		monster->memory().visual().set_squad_objects(&visible_objects());
		monster->memory().sound().set_squad_objects	(&sound_objects());
		monster->memory().hit().set_squad_objects	(&hit_objects());
	}
}

void CGroupHierarchyHolder::unregister_in_group			(CEntity *member)
{
	VERIFY						(member);
	MEMBER_REGISTRY::iterator	I = std::find(m_members.begin(),m_members.end(),member);
	VERIFY3						(I != m_members.end(),"Specified group member cannot be found",*member->cName());
	Msg("DEBUG: m_members.erase, member = %p ", member);
	m_members.erase(I);
}

void CGroupHierarchyHolder::unregister_in_squad			(CEntity *member)
{
#ifdef SQUAD_HIERARCHY_HOLDER_USE_LEADER
	if (leader() && (leader()->ID() == member->ID())) {
		update_leader					();
		if (squad().leader()->ID() == member->ID())
			if (leader())
				squad().leader			(leader());
			else
				squad().update_leader	();
	}
#endif // SQUAD_HIERARCHY_HOLDER_USE_LEADER
}

void CGroupHierarchyHolder::unregister_in_agent_manager	(CEntity *member)
{
	if (get_agent_manager()) {
		agent_manager().member().remove	(member);
		if (agent_manager().member().members().empty())
			xr_delete					(m_agent_manager);
	}

	if (m_members.empty()) {
		xr_delete						(m_visible_objects);
		xr_delete						(m_sound_objects);
		xr_delete						(m_hit_objects);
	}
}

void CGroupHierarchyHolder::unregister_in_group_senses	(CEntity *member)
{
	CCustomMonster			*monster = smart_cast<CCustomMonster*>(member);
	if (monster) {
		monster->memory().visual().set_squad_objects(0);
		monster->memory().sound().set_squad_objects	(0);
		monster->memory().hit().set_squad_objects	(0);
	}
}

void CGroupHierarchyHolder::register_member				(CEntity *member)
{
	register_in_group			(member);
	register_in_squad			(member);
	register_in_agent_manager	(member);
	register_in_group_senses	(member);
}

void CGroupHierarchyHolder::unregister_member			(CEntity *member)
{
	unregister_in_group			(member);
	unregister_in_squad			(member);
	unregister_in_agent_manager	(member);
	unregister_in_group_senses	(member);
}


text:
package org.sagebionetworks.web.client.widget;

import java.util.Map;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.shared.WikiPageKey;
import com.google.gwt.user.client.ui.IsWidget;

public interface WidgetRendererPresenter extends SynapseWidgetPresenter, IsWidget {
	/**
	 * This will be called to give you the parent entity ID, and the widget descriptor containing the
	 * params that should guide your display
	 *
	 * @param wikiKey
	 * @param widgetDescriptor
	 * @param wikiVersionInView TODO
	 */
	public void configure(WikiPageKey wikiKey, Map<String, String> widgetDescriptor, Callback widgetRefreshRequired, Long wikiVersionInView);
}


text:
Single worker that processes cli jobs with a graphical user interface for feedback.

[![Build Status](https://travis-ci.org/genkgo/gworkerd.png?branch=master)](https://travis-ci.org/genkgo/gworkerd)

## Usage

### Start Message and Result Server

Server should accept the STOMP protocol. It has been tested with Rabbit MQ only. By using the
[Dockerfile](assets/docker/Dockerfile) in this repo you can start the tested server by the following commands.

```
$ docker build --rm -t grabbit .
$ docker run -d -p 61613:61613 -p 15672:15672 grabbit
```

At this moment only mysql is supported as a result backend. There are plans to support multiple databases. In order to
start with mysql, create a [table](assets/sql/mysql_worker_results.sql) where you can store the results.

### Build gworkerd

```
$ cargo build
```

### Create a configuration file

```json
{
    "threads": 10,
    "log": {
        "directory": "/var/log/gworkerd",
        "levels": "gworkerd=info,mysql=warn,stomp=warn"
    },
    "mysql": {
        "address": "127.0.0.1",
        "username": "root",
        "password": "",
        "database": "worker_results"
    },
    "stomp": {
        "address": "127.0.0.1",
        "port": 61613,
        "username": "guest",
        "password": "guest",
        "host": "/",
        "topic": "/queue/gworkerd",
        "prefetch_count": 1
    },
     "monitor": {
         "address": "localhost:3000",
         "webapp_path": "../webapp/dist",
         "websockets": false,
         "password": "random generated password"
     }
}
```

### Start gworkerd

The daemon requires one argument: the location of the configuration file.

```
$ ./gworkerd config.json
```

### Send messages to the queue

Send your to the message queue. The content type of a job should be  application/json and has the following signature.

```json
{
    "id": "d334e01e-14cf-4247-b39a-7c9f417ad64b",
    "command": "mysqldump --all-databases",
    "cwd": "/your/directory"
}
```

### Monitor what is going on in your browser

Move your browser to the address of the monitor and you can see exactly what is going on.

`http://localhost:3000/`

## Roadmap

* 0.1.0 ~~Design of api and graphical interface (webapp in Ember)~~
* 0.2.0 ~~Pull jobs from STOMP and process jobs concurrently~~
* 0.3.0 ~~Enable logging to file~~
* 0.4.0 ~~Add config file to application~~
* 0.5.0 ~~Connect daemon to webapp~~
* 0.6.0 Support websocket in daemon
* 0.7.0 Support multiple result backends and consumers
* 0.8.0 Retry jobs
* 0.9.0 Breaking backward compatibility changes
* 1.0.0 General Availabililty


text:
#ifndef FSDICT_PATTERNGRAPH_H
#define FSDICT_PATTERNGRAPH_H FSDICT_PATTERNGRAPH_H

#include<algorithm>
#include<fstream>
#include<iostream>
#include<map>
#include<queue>
#include<string>
#include<vector>
#include "../Global.h"
#include "../Getopt/Getopt.h"

#include "../Pattern/PatternSet.h"

namespace fsdict {

    /**
     * @brief A specialised variant of the Aho-Corasick trie to search
     * in the set of left or right sides of a PatternSet.
     *
     * For the sake of simplicity and efficiency, the implementation details of
     * class \c PatternSet are used here: Internally we use simple \c size_t variables
     * to refer to a \c Pattern instead of using the official and public \c PatternRef
     * interface.
     *
     * @author Ulrich Reffle, 2008
     */
    class PatternGraph : public PatternSet {
    public:
	class Alphabet {

	public:

	    void initConstruction() {
		custom2std_.push_back( 0 ); // let 0 map to 0
	    }

	    void addChar( wchar_t c ) {
		if( ( std2custom_.size() > (size_t)c ) && std2custom_.at( c ) ) {
		    //std::wcout<<c<<L" already in alphabet"<<std::endl;

		}
		else {
		    if( (size_t)c >= std2custom_.size()  ) {
			std2custom_.resize( c + 1, 0 );
		    }
		    std2custom_.at( c ) = custom2std_.size(); // that's the first free slot of custom2std_
		    custom2std_.push_back( c );
		    //std::wcout<<"add "<<c<<L" to the alphabet"<<std::endl;
		}
	    }

	    void finishConstruction() {
		// sort the custom alphabet
		std::sort( custom2std_.begin(), custom2std_.end() );
		// update std2custom_ accordingly
		size_t n = 0;
		for( std::vector< wchar_t >::iterator it = custom2std_.begin(); it != custom2std_.end(); ++it ) {
		    std2custom_.at( *it ) = n;
		    //std::wcout<<"custom2std_.at("<< n <<" ) = "<<*it<<std::endl;
		    ++n;
		}

		n = 0;
		for( std::vector< wchar_t >::iterator it = std2custom_.begin(); it != std2custom_.end(); ++it ) {
		    //std::wcout<<"std2custom_.at("<< n<<" ) = "<<(size_t)*it<<std::endl;
		    ++n;
		}
	    }

	    wchar_t encode( wchar_t c ) const {
//		return std2custom_.at( c );
		return ( std2custom_.size() > (size_t)c ) ? std2custom_.at( c ) : 0;
	    }

	    wchar_t decode( wchar_t c ) const {
		return custom2std_.at( c ); // here we take the risky road
		// return ( custom2std_.size() > (size_t)c ) ? custom2std_.at( c ) : 0;
	    }

	    size_t size() const {
		return custom2std_.size();
	    }

	private:
	    std::vector< wchar_t > std2custom_;
	    std::vector< wchar_t > custom2std_;
	};

	// a string and an index into the list of patterns (from PatternSet)
	typedef std::vector< std::pair< std::wstring, size_t > > Replacements_t;

	class InternalState {
	public:
	    InternalState( Alphabet const& alph ) :
		alph_( &alph ), errorLink_( 0 ), prefixLength_( 0 ), isFinal_( false ) {

		transitions_.resize( alph_->size(), 0 );
	    }

	    /**
	     * Returns the target stateIndex when walking with char c (Only in the trie, no errorlinks!).
	     *
	     * @return the stateIndex of the follow-up state when walking in the trie with char c. ( 0 for fail state)
	     */
	    inline size_t getTransTarget( wchar_t c ) const {
		//std::wcout<<"walk with "<<c<<"("<<(size_t)alph_->encode( c )<<")"<<std::endl;
		return transitions_.at( alph_->encode( c ) );
	    }

	    inline void setTransition( wchar_t c, size_t targetStateIndex ) {
		if( targetStateIndex == 0 ) {
		    throw std::runtime_error( "fsdict::PatternGraph::setTransition: Removing a transition (set target to 0 ) is not supported" );
		}
		if( transitions_.at( alph_->encode( c ) ) == 0 ) {
		    allLabels_ += c;
		}
		transitions_.at( alph_->encode( c ) ) = targetStateIndex;
	    }

	    class TransIterator {
	    public:
		TransIterator( InternalState const* myIntState, size_t labelIndex = 0 ) : myInternalState_( myIntState ),
							     labelIndex_( labelIndex ) {
		}

		TransIterator& operator++() {
		    ++labelIndex_;
		    return *this;
		}
		bool operator==( TransIterator const& other ) const {
		    return ( ( myInternalState_ == other.myInternalState_ ) && ( labelIndex_ == other.labelIndex_ ) );

		}
		bool operator!=( TransIterator const& other ) const {
		    return !( *this == other );
		}

		std::pair< wchar_t, size_t > operator*() {
		    return std::make_pair( myInternalState_->allLabels_.at( labelIndex_ ),
				      myInternalState_->getTransTarget( myInternalState_->allLabels_.at( labelIndex_ ) ) );
		}

	    private:
		InternalState const* myInternalState_;
		/**
		 * @brief current position in the string of all labels
		 */
		size_t labelIndex_;

	    }; // class TransIterator

	    Alphabet const* alph_; // it's a pointer because the object needs to work with the assignment-operator
	    std::vector< size_t > transitions_;
	    Replacements_t replacements_;
	    size_t errorLink_;
	    std::wstring allLabels_;
	    int prefixLength_;
	    bool isFinal_;
	}; // class InternalState

	class State {
	public:
	    typedef InternalState::TransIterator iterator;

	    inline State() :
		myGraph_( 0 ),
		stateIndex_( 0 ) {

	    }

	    inline State( const PatternGraph& myGraph, size_t stateIndex ) :
		myGraph_( &myGraph ),
		stateIndex_( stateIndex ) {
	    }

	    inline bool operator==( State const& other ) {
		return( ( myGraph_ == other.myGraph_  ) && // compare pointers
			( stateIndex_ == stateIndex_ ) );
	    }

	    inline State& operator=( State const& other ) {
		myGraph_ = other.myGraph_;
		stateIndex_ = other.stateIndex_;
		return *this;
		}

	    /**
	     * walk in the AC-Trie. Use error links when needed.
	     *
	     * @return the "distance" from the root to the target state
	     */
	    inline bool walk( wchar_t c );

	    inline bool walkErrorLink();

	    /**
	     * walk in the trie only - do not use error links
	     * if walk is not possible, stay where you are
	     *
	     * @return true if an appropriate transition was found
	     */
	    inline bool walkStrict( wchar_t c );

	    /**
	     * This is equivalent to a 'walk' call, only that the state itself
	     * remains unchanged (-->const), but a copy of the target state
	     */
	    inline State getTransTarget( wchar_t c ) const;

	    /**
	     * @return an iterator positioned at the first of the state's transitions
	     */
	    inline iterator transBegin() const;

	    /**
	     * @return a past-the-end iterator for the state's transitions
	     */
	    inline iterator transEnd() const;

	    /**
	     * @return the "distance" from the root to the target state
	     */
	    inline size_t getPrefixLength() const;

	    inline bool isFinal() const;

	    /**
	     * @return a reference to the list of replacements attached to the state (which must be final)
	     */
	    inline const Replacements_t& getReplacements() const;

	    /**
	     * @return true iff the current state is not the failstate
	     */
	    inline bool isValid() const;

	    inline void addTransition( wchar_t c, const State& target );
	    size_t getStateIndex() const;

	private:
	    friend class PatternGraph;
	    friend class InternalState;

	    const PatternGraph* myGraph_;
	    size_t stateIndex_;

	}; // class State

	enum Direction {FORWARD, BACKWARD};
	enum IndexSide {INDEX_LEFT, INDEX_RIGHT};

	inline PatternGraph( Direction dir = FORWARD, IndexSide indexSide = INDEX_LEFT );

	inline void loadPatterns( const char* patternFile );

	inline State getRoot() const;

	inline size_t getNrOfPatterns() const;

	inline void toDot() const;

	// *** PRIVATE of PATTERNGRAPH ***
    private:

	Direction direction_;

	/**
	 * @brief Specifies if the left or right side of the pattern shall be indexed
	 *        in the trie
	 */
	IndexSide indexSide_;

	inline void addErrorLinks();

	/**
	 * Add a new state and return its index in the vector
	 */
	inline State newState();

	Alphabet alph_;

	/**
	 * Don't forget the realloc-trouble here !!!
	 */
	std::vector< InternalState > states_;

	size_t nrOfPatterns_;

    };

    /********** IMPL   STATE  ********************/

    bool PatternGraph::State::walk( wchar_t c ) {
//	std::wcout<<"Reading "<<c<<", beginning at state "<<getStateIndex()<<std::endl; // DEBUG
	while( isValid() && ( ! walkStrict( c ) ) ) {
	    stateIndex_ = myGraph_->states_.at( getStateIndex() ).errorLink_;
	    // std::wcout<<"  Retreat to "<<getStateIndex()<<std::endl; // DEBUG
	}
	if( ! isValid() ) {
	    stateIndex_ = 1;
	}
	return isValid(); // btw, this should always be true
    }

    bool PatternGraph::State::walkStrict( wchar_t c ) {
	if( size_t newIndex =  myGraph_->states_.at( stateIndex_ ).getTransTarget( c ) ) {
	    stateIndex_ = newIndex;
	    return true;
	}
	else {
	    return false;
	}
    }

    bool PatternGraph::State::walkErrorLink() {
	stateIndex_ = myGraph_->states_.at( getStateIndex() ).errorLink_;
	return isValid();
    }

    inline PatternGraph::State PatternGraph::State::getTransTarget( wchar_t c ) const {
	State newState = *this;
	newState.walk( c);
	return newState;
    }

    inline size_t PatternGraph::State::getPrefixLength() const {
	return myGraph_->states_.at( stateIndex_ ).prefixLength_;
    }

    inline size_t PatternGraph::State::getStateIndex() const {
	return stateIndex_;
    }

    inline PatternGraph::State::iterator PatternGraph::State::transBegin() const {
	return InternalState::TransIterator( &( myGraph_->states_.at( stateIndex_ ) ), 0 );
    }

    inline PatternGraph::State::iterator PatternGraph::State::transEnd() const {
	return InternalState::TransIterator( &( myGraph_->states_.at( stateIndex_ ) ), myGraph_->states_.at( stateIndex_ ).allLabels_.size() );
    }

    inline bool PatternGraph::State::isFinal() const {
	return myGraph_->states_.at( stateIndex_ ).isFinal_;
    }

    inline bool PatternGraph::State::isValid() const {
	return ( stateIndex_ != 0 );
    }

    inline PatternGraph::Replacements_t const& PatternGraph::State::getReplacements() const {
	return myGraph_->states_.at( stateIndex_ ).replacements_;
    }

//     inline const std::wstring& PatternGraph::State::getWord() const {
// 	return myGraph_->states_.at( stateIndex_ ).word_;
//     }

    /********* IMPL  PATTERNGRAPH *****************/

    PatternGraph::PatternGraph( Direction dir, IndexSide indexSide ) :
	direction_( dir ),
	indexSide_( indexSide ),
	nrOfPatterns_( 0 ) {
    }

    inline PatternGraph::State PatternGraph::getRoot() const {
	return State( *this, 1 );
    }

    inline size_t PatternGraph::getNrOfPatterns() const {
	return nrOfPatterns_;
    }

    inline void PatternGraph::loadPatterns( const char* patternFile ) {

	// Use the base class method to read the patterns from the file
	PatternSet::loadPatterns( patternFile );

	// 1st pass: build alphabet
	alph_.initConstruction();
	for( PatternList_t::const_iterator pattern = patternList().begin() + 1; // skip 1st pattern: it's the empty pattern!
	     pattern != patternList().end();
	     ++pattern ) {
	    std::wstring const& indexed = ( indexSide_ == INDEX_LEFT )? pattern->getLeft() : pattern->getRight();
	    for( std::wstring::const_iterator c = indexed.begin(); c != indexed.end(); ++c ) {
		alph_.addChar( *c );
	    }
	}
	alph_.finishConstruction();

	states_.push_back( InternalState( alph_ ) ); // failure state at position 0
	states_.push_back( InternalState( alph_ ) ); // root at position 1

	std::wstring indexed, replacement;
	for( PatternList_t::const_iterator pattern = patternList().begin() + 1; // skip 1st pattern: it's the empty pattern!
	     pattern != patternList().end();
	     ++pattern ) {

	    std::wstring const& indexedRef = ( indexSide_ == INDEX_LEFT )? pattern->getLeft() : pattern->getRight();
	    std::wstring const& replacementRef = ( indexSide_ == INDEX_LEFT )? pattern->getRight() : pattern->getLeft();

	    if( direction_ == BACKWARD ) {
		Global::reverse( indexedRef, &indexed );
		Global::reverse( replacementRef, &replacement );
	    }
	    else {
		indexed = indexedRef;
		replacement = replacementRef;
	    }

	    State state = getRoot();

	    // *** find common prefix ***
	    std::wstring::const_iterator c = indexed.begin(); // c must be visible outside the for-loop
	    for( ;
		 c != indexed.end() && state.walkStrict( *c );
		 ++c ) {
		// do nothing else
	    }

	    // *** add suffix ***
	    // prevent the vector from re-allocating during the process
	    states_.reserve( states_.size() + ( indexed.end() - c ) );

	    State lastState = state;
	    for( ;
		 c != indexed.end();
		 ++c ) {
		State newSt = newState();
		size_t newPrefixLength = lastState.getPrefixLength();
		if( (*c != Global::wordBeginMarker ) && (*c != Global::wordEndMarker ) ) ++newPrefixLength; // begin and end-markers do not contribute to prefixLength

		states_.at( newSt.getStateIndex() ).prefixLength_ = newPrefixLength;
		states_.at( lastState.getStateIndex() ).setTransition( *c, newSt.getStateIndex() );
		lastState = newSt;
	    }
	    states_.at( lastState.getStateIndex() ).isFinal_ = true;

	    states_.at( lastState.getStateIndex() ).replacements_.push_back( std::make_pair( replacement, pattern - patternList().begin() ) );
	}

	addErrorLinks();

	// toDot(); // DEBUG

    }

    inline void PatternGraph::addErrorLinks() {

	states_.at( 1 ).errorLink_ = 0;
	std::queue< size_t > queue;
	queue.push( getRoot().getStateIndex() );

	while( ! queue.empty() ) {
	    size_t parent = queue.front();
	    queue.pop();

	    for( std::wstring::const_iterator c = states_.at( parent ).allLabels_.begin();
		 c !=  states_.at( parent ).allLabels_.end();
		 ++c ) {
		queue.push( states_.at( parent ).getTransTarget( *c ) );

		size_t current = queue.back();
		size_t parentBack = parent;
		size_t back = 0;

		while( ( back == 0 ) && ( parentBack != 0 ) ) {
		    parentBack = states_.at( parentBack ).errorLink_;
		    back = states_.at( parentBack ).getTransTarget( *c );
		}
		if( parentBack == 0 ) back = 1;

		if( states_.at( back ).isFinal_ ) {
		    states_.at( current ).isFinal_ = true;
		    // copy all replacements of 'back' to 'current'
		    states_.at( current ).replacements_.insert( states_.at( current ).replacements_.end(),
								states_.at( back ).replacements_.begin(),
								states_.at( back ).replacements_.end() );
		}
		states_.at( current ).errorLink_ = back;
	    }
	}
    } // method PatternGraph::addErrorLinks

    inline PatternGraph::State PatternGraph::newState() {
	states_.resize( states_.size() + 1, InternalState( alph_ ) );
	return State( *this, states_.size() -1 );
    }

    inline void PatternGraph::toDot() const {
	std::wcout<< "Digraph PatternGraph { //DOTCODE"<<std::endl
		  <<"rankdir=LR; //DOTCODE"<<std::endl
		  <<"ordering=out; //DOTCODE"<<std::endl;

	size_t count = 0;
	for( std::vector< InternalState >::const_iterator st = states_.begin() ; st != states_.end(); ++st ) {
	    std::wcout<<count<<"[label=\""<<count<<"\",peripheries="<< ( (st->isFinal_)? "2" : "1" ) << "] // DOTCODE" << std::endl;

	    if( st->isFinal_ ) {
		std::wcout << count << "->" << count << "[color=\"#dddddd\", label=\"";
		for( Replacements_t::const_iterator r = st->replacements_.begin(); r != st->replacements_.end(); ++r ) {
		    std::wcout << "(" << this->at(r->second).toString() << ")";
		}
		std::wcout << "\"] // DOTCODE\n";
	    }

	    for( std::wstring::const_iterator c = st->allLabels_.begin();
		 c !=  st->allLabels_.end();
		 ++c ) {

		std::wcout << count << "->" << st->getTransTarget( *c ) << "[label=\"" << *c <<"\"] // DOTCODE" << std::endl;
	    }
	    std::wcout << count << "->" << st->errorLink_ << "[color=red, constraint=false] // DOTCODE" << std::endl;

	    ++count;
	}

	std::wcout << "} // DOTCODE" << std::endl;
    }

} // namespace fsdict

#endif


text:
Viewing your profile

{{ profile.name }}

	Age: {{ profile.age }}

	Favorite Food: {{ profile.favoriteFood }}

	Interests

			No interests are currently listed. Click to add one.

				{{ interest.name }}
				x

			<input type="text" *ngIf="interestsEdit[i]" [(ngModel)]="interestsEdit[i].name">
			<input type="submit" *ngIf="interestsEdit[i]" (click)="saveInterest(i)">
			<button *ngIf="interestsEdit[i]" (click)="cancelInterestEdit(i)">Cancel</button>

 0 && profile.interests.length <= 5) || interestsEdit.new">
			Add new

			<input type="text" *ngIf="interestsEdit.new" [(ngModel)]="newInterest.name">
			<input type="submit" *ngIf="interestsEdit.new" (click)="saveInterest('new')">
			<button *ngIf="interestsEdit.new" (click)="cancelInterestEdit('new')">Cancel</button>


text:
/**
 *
 */
package actorx.remote;

import co.paralleluniverse.fibers.SuspendExecution;
import actorx.Message;

/**
 * @author Xiong
 *
 */
public interface INetworkService {
	void start() throws SuspendExecution, Exception;
	void handleMessage(Message msg) throws SuspendExecution, Exception;
	void handleException(Throwable e) throws SuspendExecution;
	void stop() throws SuspendExecution;
}


text:
package com.github.nicholasren.moco.wrapper

import com.github.dreamhead.moco.{RequestMatcher, Moco, RequestExtractor}
import com.github.dreamhead.moco.resource.Resource

case class ExtractorMatcher(extractor: RequestExtractor[_ <: Any]) {
  def ===(expected: String): RequestMatcher = Moco.eq(extractor, expected)

  def ===(expected: Resource): RequestMatcher = Moco.eq(extractor, expected)

  def matched(expected: String): RequestMatcher = Moco.`match`(extractor, expected)

  def contain(expected: String): RequestMatcher = Moco.contain(extractor, expected)

  def startsWith(prefix: String): RequestMatcher = Moco.startsWith(extractor, prefix)

  def endsWith(suffix: String): RequestMatcher = Moco.endsWith(extractor, suffix)
}


text:
package v1alpha1

type MPIJobExpansion interface{}


text:
/*
 * Double-double precision (>= 106-bit significand) floating point
 * arithmetic package based on David Bailey's Fortran-90 double-double
 * package, with some changes. See
 *
 *   http://www.nersc.gov/~dhbailey/mpdist/mpdist.html
 *
 * for the original Fortran-90 version.
 *
 * Overall structure is similar to that of Keith Brigg's C++ double-double
 * package.  See
 *
 *   http://www-epidem.plansci.cam.ac.uk/~kbriggs/doubledouble.html
 *
 * for more details.  In particular, the fix for x86 computers is borrowed
 * from his code.
 *
 * Yozo Hida
 */

#ifndef _DD_REAL_H
#define _DD_REAL_H

#include <float.h>
#include <limits.h>
#include <math.h>

#include "_c99compat.h"

#ifdef __cplusplus
extern "C" {
#endif

/* Some configuration defines */

/* If fast fused multiply-add is available, define to the correct macro for
   using it.  It is invoked as DD_FMA(a, b, c) to compute fl(a * b + c).
   If correctly rounded multiply-add is not available (or if unsure),
   keep it undefined. */
#ifndef DD_FMA
#ifdef FP_FAST_FMA
#define DD_FMA(A, B, C) fma((A), (B), (C))
#endif
#endif

/* Same with fused multiply-subtract */
#ifndef DD_FMS
#ifdef FP_FAST_FMA
#define DD_FMS(A, B, C) fma((A), (B), (-C))
#endif
#endif

/* Define this macro to be the isfinite(x) function. */
#define DD_ISFINITE sc_isfinite

/* Define this macro to be the isinf(x) function. */
#define DD_ISINF sc_isinf

/* Define this macro to be the isnan(x) function. */
#define DD_ISNAN sc_isnan

#ifdef __cplusplus
#define DD_STATIC_CAST(T, X) (static_cast<T>(X))
#else
#define DD_STATIC_CAST(T, X) ((T)(X))
#endif

/* double2 struct definition, some external always-present double2 constants.
*/
typedef struct double2
{
    double x[2];
} double2;

extern const double DD_C_EPS;
extern const double DD_C_MIN_NORMALIZED;
extern const double2 DD_C_MAX;
extern const double2 DD_C_SAFE_MAX;
extern const int DD_C_NDIGITS;

extern const double2 DD_C_2PI;
extern const double2 DD_C_PI;
extern const double2 DD_C_3PI4;
extern const double2 DD_C_PI2;
extern const double2 DD_C_PI4;
extern const double2 DD_C_PI16;
extern const double2 DD_C_E;
extern const double2 DD_C_LOG2;
extern const double2 DD_C_LOG10;
extern const double2 DD_C_ZERO;
extern const double2 DD_C_ONE;

/* NAN definition in AIX's math.h doesn't make it qualify as constant literal. */
#if defined(__STDC__) && defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && defined(NAN) && !defined(_AIX)
#define DD_C_NAN_IS_CONST
extern const double2 DD_C_NAN;
extern const double2 DD_C_INF;
extern const double2 DD_C_NEGINF;
#else
#define DD_C_NAN (dd_create(NPY_NAN, NPY_NAN))
#define DD_C_INF (dd_create(NPY_INFINITY, NPY_INFINITY))
#define DD_C_NEGINF (dd_create(-NPY_INFINITY, -NPY_INFINITY))
#endif

/* Include the inline definitions of functions */
#include "dd_real_idefs.h"

/* Non-inline functions */

/********** Exponentiation **********/
double2 dd_npwr(const double2 a, int n);

/*********** Transcendental Functions ************/
double2 dd_exp(const double2 a);
double2 dd_log(const double2 a);
double2 dd_expm1(const double2 a);
double2 dd_log1p(const double2 a);
double2 dd_log10(const double2 a);
double2 dd_log_d(double a);

/* Returns the exponent of the double precision number.
   Returns INT_MIN is x is zero, and INT_MAX if x is INF or NaN. */
int get_double_expn(double x);

/*********** Random number generator ************/
extern double2 dd_rand(void);

#ifdef __cplusplus
}
#endif

#endif /* _DD_REAL_H */


text:
require 'spec_helper'

describe Project do
  it "generates the API token on creation" do
    @project = Project.create(:start => Date.today, :end => Date.today, :name => "Foo", :state => "ongoing")
    @project.api_token.should_not be_blank
  end

  it "can regenerate the API token" do
    @project = Project.create(:start => Date.today, :end => Date.today, :name => "Foo", :state => "ongoing")
    old_token = @project.api_token
    @project.regenerate_api_token
    @project.api_token.should_not == old_token
  end

  describe "#guest_access?" do
    subject { Project.new(:start => Date.today, :end => Date.today, :name => "Foo", :state => "ongoing") }

    it "returns true if guest token is set" do
      subject.enable_guest_access
      subject.guest_access?.should be_true
    end

    it "returns false if guest token is not set" do
      subject.guest_access?.should be_false
    end
  end

  describe "#authenticate_guest_access" do
    subject { Project.new(:start => Date.today, :end => Date.today, :name => "Foo", :state => "ongoing") }

    it "returns false if guest access is not on" do
      subject.authenticate_guest_access("abc").should be_false
    end

    it "returns false if guest token is incorrect" do
      subject.enable_guest_access
      subject.authenticate_guest_access("abc").should be_false
    end

    it "returns true if token is correct" do
      subject.enable_guest_access
      subject.authenticate_guest_access(subject.guest_token).should be_true
    end
  end

  describe "#enable_guest_access" do
    subject { Project.new(:start => Date.today, :end => Date.today, :name => "Foo", :state => "ongoing") }

    it "sets guest token" do
      subject.guest_token.should be_blank
      subject.enable_guest_access
      subject.guest_token.should_not be_blank
    end
  end

  describe "#disable_guest_access" do
    subject { Project.new(:start => Date.today, :end => Date.today, :name => "Foo", :state => "ongoing") }

    it "unsets guest token" do
      subject.enable_guest_access
      subject.guest_token.should_not be_blank
      subject.disable_guest_access
      subject.guest_token.should be_blank
    end
  end

  describe "#state" do
    it "always returns symbols" do
      @project = Project.new
      @project.state = "ongoing"
      @project.state.should be(:ongoing)
    end
  end

  describe "#state_name" do
    it "returns correct value for all 3 valid states" do
      @project = Project.new
      @project.state = "ongoing"
      @project.state_name.should == "Ongoing"
      @project.state = "on_hold"
      @project.state_name.should == "On Hold"
      @project.state = "completed"
      @project.state_name.should == "Completed"
    end
  end

  describe "#active?" do
    before do
      @project = Project.new
    end

    it "returns true if project is on going" do
      @project.state = "ongoing"
      @project.active?.should be_true
    end

    it "returns false if project is on hold" do
      @project.state = "on_hold"
      @project.active?.should be_false
    end

    it "returns false if project is completed" do
      @project.state = "completed"
      @project.active?.should be_false
    end
  end

  describe "#completed?" do
    before do
      @project = Project.new
    end

    it "returns true if project is completed" do
      @project.state = "completed"
      @project.completed?.should be_true
    end

    it "returns false if project is on hold" do
      @project.state = "on_hold"
      @project.completed?.should be_false
    end

    it "returns false if project is ongoing" do
      @project.state = "ongoing"
      @project.completed?.should be_false
    end
  end
end


text:
package spatial.codegen.cppgen

import argon.codegen.cppgen.CppCodegen
import argon.core._
import spatial.aliases._
import spatial.nodes._

trait CppGenStream extends CppCodegen {

  override protected def emitNode(lhs: Sym[_], rhs: Op[_]): Unit = rhs match {
//<<<<<<< HEAD
//    case StreamInNew(bus) => emit(s"$lhs = $bus // TODO: No idea what to connect this bus to, should expose periphal pins to something...")
//    case StreamOutNew(bus) =>
//      s"$bus" match {
//        case "BurstCmdBus" =>
//        case _ =>
//          emit(src"// New stream out $lhs")
//      }
//=======
    case BufferedOutNew(_, bus) => emit(s"// ${quote(lhs)} = $bus // TODO: No idea what to connect this bus to, should expose periphal pins to something...")
    case StreamInNew(bus) => emit(s"// ${quote(lhs)} = $bus // TODO: No idea what to connect this bus to, should expose periphal pins to something...")
    case StreamOutNew(bus) => emit(s"// ${quote(lhs)} = $bus // TODO: No idea what to connect this bus to, should expose periphal pins to something...")
    case _ => super.emitNode(lhs, rhs)
  }

  override protected def emitFileFooter() {
    super.emitFileFooter()
  }
}


text:
#ifndef __ASM_I386_I387_H
#define __ASM_I386_I387_H

#include <linux/sched.h>
#include <linux/init.h>
#include <linux/kernel_stat.h>
#include <asm/processor.h>
#include <asm/sigcontext.h>
#include <asm/user.h>

extern void mxcsr_feature_mask_init(void);
extern void init_fpu(struct task_struct *);

/*
 * FPU lazy state save handling...
 */

/*
 * The "nop" is needed to make the instructions the same
 * length.
 */
#define restore_fpu(tsk)			\
	alternative_input(			\
		"nop ; frstor %1",		\
		"fxrstor %1",			\
		X86_FEATURE_FXSR,		\
		"m" ((tsk)->thread.i387.fxsave))

extern void kernel_fpu_begin(void);
#define kernel_fpu_end() do { stts(); preempt_enable(); } while(0)

/* We need a safe address that is cheap to find and that is already
   in L1 during context switch. The best choices are unfortunately
   different for UP and SMP */
#ifdef CONFIG_SMP
#define safe_address (__per_cpu_offset[0])
#else
#define safe_address (kstat_cpu(0).cpustat.user)
#endif

/*
 * These must be called with preempt disabled
 */
static inline void __save_init_fpu( struct task_struct *tsk )
{
	/* Use more nops than strictly needed in case the compiler
	   varies code */
	alternative_input(
		"fnsave %[fx] ;fwait;" GENERIC_NOP8 GENERIC_NOP4,
		"fxsave %[fx]\n"
		"bt $7,%[fsw] ; jnc 1f ; fnclex\n1:",
		X86_FEATURE_FXSR,
		[fx] "m" (tsk->thread.i387.fxsave),
		[fsw] "m" (tsk->thread.i387.fxsave.swd) : "memory");
	/* AMD K7/K8 CPUs don't save/restore FDP/FIP/FOP unless an exception
	   is pending.  Clear the x87 state here by setting it to fixed
   	   values. safe_address is a random variable that should be in L1 */
	alternative_input(
		GENERIC_NOP8 GENERIC_NOP2,
		"emms\n\t"	  	/* clear stack tags */
		"fildl %[addr]", 	/* set F?P to defined value */
		X86_FEATURE_FXSAVE_LEAK,
		[addr] "m" (safe_address));
	task_thread_info(tsk)->status &= ~TS_USEDFPU;
}

#define __unlazy_fpu( tsk ) do { \
	if (task_thread_info(tsk)->status & TS_USEDFPU) \
		save_init_fpu( tsk ); 			\
	else						\
		tsk->fpu_counter = 0;			\
} while (0)

#define __clear_fpu( tsk )					\
do {								\
	if (task_thread_info(tsk)->status & TS_USEDFPU) {		\
		asm volatile("fnclex ; fwait");				\
		task_thread_info(tsk)->status &= ~TS_USEDFPU;	\
		stts();						\
	}							\
} while (0)

/*
 * These disable preemption on their own and are safe
 */
static inline void save_init_fpu( struct task_struct *tsk )
{
	preempt_disable();
	__save_init_fpu(tsk);
	stts();
	preempt_enable();
}

#define unlazy_fpu( tsk ) do {	\
	preempt_disable();	\
	__unlazy_fpu(tsk);	\
	preempt_enable();	\
} while (0)

#define clear_fpu( tsk ) do {	\
	preempt_disable();	\
	__clear_fpu( tsk );	\
	preempt_enable();	\
} while (0)
					\
/*
 * FPU state interaction...
 */
extern unsigned short get_fpu_cwd( struct task_struct *tsk );
extern unsigned short get_fpu_swd( struct task_struct *tsk );
extern unsigned short get_fpu_mxcsr( struct task_struct *tsk );
extern asmlinkage void math_state_restore(void);

/*
 * Signal frame handlers...
 */
extern int save_i387( struct _fpstate __user *buf );
extern int restore_i387( struct _fpstate __user *buf );

/*
 * ptrace request handers...
 */
extern int get_fpregs( struct user_i387_struct __user *buf,
		       struct task_struct *tsk );
extern int set_fpregs( struct task_struct *tsk,
		       struct user_i387_struct __user *buf );

extern int get_fpxregs( struct user_fxsr_struct __user *buf,
			struct task_struct *tsk );
extern int set_fpxregs( struct task_struct *tsk,
			struct user_fxsr_struct __user *buf );

/*
 * FPU state for core dumps...
 */
extern int dump_fpu( struct pt_regs *regs,
		     struct user_i387_struct *fpu );

#endif /* __ASM_I386_I387_H */


text:
"""
Test for issue 824:
https://github.com/ydataai/pandas-profiling/issues/824

High correlation warning printed multiple times

Problem :
The alert is probably generated for each active correlation calculation

Solution :
Field will be marked once is labelled as highly correlated for any calculation
"""
import pandas as pd
import pytest

from pandas_profiling import ProfileReport
from pandas_profiling.model.alerts import AlertType

@pytest.mark.skip()
def test_issue824():

    # Minimal reproducible code

    df = pd.DataFrame.from_dict(
        {
            "integer1": pd.Series([3, 4, 5, 6], dtype="int"),
            "integer2": pd.Series([3, 4, 5, 6], dtype="int"),
            "integer3": pd.Series([3, 4, 5, 6], dtype="int"),
            "integer4": pd.Series([3, 4, 5, 6], dtype="int"),
            "integer5": pd.Series([3, 4, 5, 6], dtype="int"),
        }
    )

    report = ProfileReport(df)
    _ = report.description_set

    assert (
        len(
            [
                a
                for a in report.description_set["alerts"]
                if a.alert_type == AlertType.HIGH_CORRELATION
            ]
        )
        == 5
    )


text:
********
Galleria
********
**A JavaScript image gallery for the fastidious.**

For more information and working demos visit: http://galleria.aino.se/.

For updates, follow us at Twitter: http://twitter.com/galleriajs.

Support
=======
Please don't post any support related issues on Github.

If you need help we have a small beta support community over at:
http://getsatisfaction.com/galleria.

General information
===================
Galleria is a image gallery framework that is very easy to use, yet loaded with
advanced customization options. Galleria and some of the themes provided here
are free to use under the MIT license. Premium themes, transitions and more
extras will soon be available for purchase at http://galleria.aino.se.

A good way to get started is to read the Getting Started section at
http://github.com/aino/galleria/blob/master/docs//tutorial/getting_started.rst

Good luck!

Documentation
=============
Documentation is currently available in `reST
<http://en.wikipedia.org/wiki/ReStructuredText>`_ format in the repository.

.. note:: We are currently re-organizing our docs for the 1.2 release.

The options documentation is ready, but the Reference API is still under construction.


text:
package com.navercorp.pinpoint.rpc.util;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jboss.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.navercorp.pinpoint.rpc.Future;
import com.navercorp.pinpoint.rpc.ResponseMessage;
import com.navercorp.pinpoint.rpc.client.MessageListener;
import com.navercorp.pinpoint.rpc.client.PinpointSocket;
import com.navercorp.pinpoint.rpc.client.PinpointSocketFactory;
import com.navercorp.pinpoint.rpc.packet.HandshakeResponseCode;
import com.navercorp.pinpoint.rpc.packet.HandshakeResponseType;
import com.navercorp.pinpoint.rpc.packet.PingPacket;
import com.navercorp.pinpoint.rpc.packet.RequestPacket;
import com.navercorp.pinpoint.rpc.packet.ResponsePacket;
import com.navercorp.pinpoint.rpc.packet.SendPacket;
import com.navercorp.pinpoint.rpc.server.AgentHandshakePropertyType;
import com.navercorp.pinpoint.rpc.server.PinpointServerAcceptor;
import com.navercorp.pinpoint.rpc.server.PinpointServer;
import com.navercorp.pinpoint.rpc.server.ServerMessageListener;

public final class PinpointRPCTestUtils {

    private static final Logger logger = LoggerFactory.getLogger(PinpointRPCTestUtils.class);

    private PinpointRPCTestUtils() {
    }

    public static int findAvailablePort() throws IOException {
        return findAvailablePort(21111);
    }

    public static int findAvailablePort(int defaultPort) throws IOException {
        int bindPort = defaultPort;

        ServerSocket serverSocket = null;
        while (0xFFFF >= bindPort && serverSocket == null) {
            try {
                serverSocket = new ServerSocket(bindPort);
            } catch (IOException ex) {
                bindPort++;
            }
        }

        if (serverSocket != null) {
            serverSocket.close();
            return bindPort;
        }

        throw new IOException("can't find available port.");
    }

    public static PinpointServerAcceptor createPinpointServerFactory(int bindPort) {
        return createPinpointServerFactory(bindPort, null);
    }

    public static PinpointServerAcceptor createPinpointServerFactory(int bindPort, ServerMessageListener messageListener) {
        PinpointServerAcceptor serverAcceptor = new PinpointServerAcceptor();
        serverAcceptor.bind("127.0.0.1", bindPort);

        if (messageListener != null) {
            serverAcceptor.setMessageListener(messageListener);
        }

        return serverAcceptor;
    }

    public static void close(PinpointServerAcceptor serverAcceptor, PinpointServerAcceptor... serverAcceptors) {
        if (serverAcceptor != null) {
            serverAcceptor.close();
        }

        if (serverAcceptors != null) {
            for (PinpointServerAcceptor eachServerAcceptor : serverAcceptors) {
                if (eachServerAcceptor != null) {
                    eachServerAcceptor.close();
                }
            }
        }
    }

    public static PinpointSocketFactory createSocketFactory(Map param) {
        return createSocketFactory(param, null);
    }

    public static PinpointSocketFactory createSocketFactory(Map param, MessageListener messageListener) {
        PinpointSocketFactory socketFactory = new PinpointSocketFactory();
        socketFactory.setProperties(param);

        if (messageListener != null) {
            socketFactory.setMessageListener(messageListener);
        }

        return socketFactory;
    }

    public static byte[] request(PinpointServer writableServer, byte[] message) {
        Future<ResponseMessage> future = writableServer.request(message);
        future.await();
        return future.getResult().getMessage();
    }

    public static byte[] request(PinpointSocket pinpointSocket, byte[] message) {
        Future<ResponseMessage> future = pinpointSocket.request(message);
        future.await();
        return future.getResult().getMessage();
    }

    public static void close(PinpointSocket socket, PinpointSocket... sockets) {
        if (socket != null) {
            socket.close();
        }

        if (sockets != null) {
            for (PinpointSocket eachSocket : sockets) {
                if (eachSocket != null) {
                    eachSocket.close();
                }
            }
        }
    }

    public static void close(Socket socket, Socket... sockets) throws IOException {
        if (socket != null) {
            socket.close();
        }

        if (sockets != null) {
            for (Socket eachSocket : sockets) {
                if (eachSocket != null) {
                    eachSocket.close();
                }
            }
        }
    }

    public static EchoServerListener createEchoServerListener() {
        return new EchoServerListener();
    }

    public static EchoClientListener createEchoClientListener() {
        return new EchoClientListener();
    }

    public static Map getParams() {
        Map properties = new HashMap();
        properties.put(AgentHandshakePropertyType.AGENT_ID.getName(), "agent");
        properties.put(AgentHandshakePropertyType.APPLICATION_NAME.getName(), "application");
        properties.put(AgentHandshakePropertyType.HOSTNAME.getName(), "hostname");
        properties.put(AgentHandshakePropertyType.IP.getName(), "ip");
        properties.put(AgentHandshakePropertyType.PID.getName(), 1111);
        properties.put(AgentHandshakePropertyType.SERVICE_TYPE.getName(), 10);
        properties.put(AgentHandshakePropertyType.START_TIMESTAMP.getName(), System.currentTimeMillis());
        properties.put(AgentHandshakePropertyType.VERSION.getName(), "1.0");

        return properties;
    }

    public static class EchoServerListener implements ServerMessageListener {
        private final List<SendPacket> sendPacketRepository = new ArrayList<SendPacket>();
        private final List<RequestPacket> requestPacketRepository = new ArrayList<RequestPacket>();

        @Override
        public void handleSend(SendPacket sendPacket, PinpointServer pinpointServer) {
            sendPacketRepository.add(sendPacket);
        }

        @Override
        public void handleRequest(RequestPacket requestPacket, PinpointServer pinpointServer) {
            requestPacketRepository.add(requestPacket);

            logger.info("handlerRequest {}", requestPacket);

            pinpointServer.response(requestPacket, requestPacket.getPayload());
        }

        @Override
        public HandshakeResponseCode handleHandshake(Map properties) {
            logger.info("handle Handshake {}", properties);
            return HandshakeResponseType.Success.DUPLEX_COMMUNICATION;
        }

        @Override
        public void handlePing(PingPacket pingPacket, PinpointServer pinpointServer) {

        }
    }

    public static class EchoClientListener implements MessageListener {
        private final List<SendPacket> sendPacketRepository = new ArrayList<SendPacket>();
        private final List<RequestPacket> requestPacketRepository = new ArrayList<RequestPacket>();

        @Override
        public void handleSend(SendPacket sendPacket, Channel channel) {
            sendPacketRepository.add(sendPacket);

            byte[] payload = sendPacket.getPayload();
            logger.debug(new String(payload));
        }

        @Override
        public void handleRequest(RequestPacket requestPacket, Channel channel) {
            requestPacketRepository.add(requestPacket);

            byte[] payload = requestPacket.getPayload();
            logger.debug(new String(payload));

            channel.write(new ResponsePacket(requestPacket.getRequestId(), requestPacket.getPayload()));
        }

        public List<SendPacket> getSendPacketRepository() {
            return sendPacketRepository;
        }

        public List<RequestPacket> getRequestPacketRepository() {
            return requestPacketRepository;
        }
    }

}


text:
package org.mousephenotype.cda.owl;

import org.semanticweb.owlapi.model.IRI;
import org.semanticweb.owlapi.model.OWLOntologyCreationException;
import org.semanticweb.owlapi.model.OWLOntologyStorageException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.manchester.cs.owl.owlapi.OWLObjectPropertyImpl;

import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;

public class OntologyParserFactory {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String owlpath;
    private DataSource komp2DataSource;

    public OntologyParserFactory(DataSource komp2DataSource, String owlpath){

        this.komp2DataSource = komp2DataSource;
        this.owlpath = owlpath;

    }

    // Properties we want to follow to get MA terms form MP
    public static final Set<OWLObjectPropertyImpl> VIA_PROPERTIES = new HashSet<>(Arrays.asList(new OWLObjectPropertyImpl(IRI.create("http://purl.obolibrary.org/obo/BFO_0000052")),
            new OWLObjectPropertyImpl(IRI.create("http://purl.obolibrary.org/obo/BFO_0000070")),
            new OWLObjectPropertyImpl(IRI.create("http://purl.obolibrary.org/obo/mp/mp-logical-definitions#inheres_in_part_of"))));

    public static final List<String> TOP_LEVEL_MP_TERMS = new ArrayList<>(Arrays.asList("MP:0010768", "MP:0002873", "MP:0001186", "MP:0003631",
            "MP:0005367",  "MP:0005369", "MP:0005370", "MP:0005371", "MP:0005377", "MP:0005378", "MP:0005375", "MP:0005376",
            "MP:0005379", "MP:0005380",  "MP:0005381", "MP:0005384", "MP:0005385", "MP:0005382", "MP:0005388", "MP:0005389", "MP:0005386",
            "MP:0005387", "MP:0005391",  "MP:0005390", "MP:0005394", "MP:0005397", "MP:0010771"));

    public static final Set<String> TOP_LEVEL_MA_TERMS = new HashSet<>(Arrays.asList("MA:0000004", "MA:0000007", "MA:0000009",
            "MA:0000010", "MA:0000012", "MA:0000014", "MA:0000016", "MA:0000017", "MA:0000325", "MA:0000326", "MA:0000327",
            "MA:0002411", "MA:0002418", "MA:0002431", "MA:0002711", "MA:0002887", "MA:0002405"));

    public static final Set<String> TOP_LEVEL_EMAPA_TERMS = new HashSet<>(Arrays.asList("EMAPA:16104", "EMAPA:16192", "EMAPA:16246",
            "EMAPA:16405", "EMAPA:16469", "EMAPA:16727", "EMAPA:16748", "EMAPA:16840", "EMAPA:17524", "EMAPA:31858"));

    public static final Set<String> TOP_LEVEL_HP_TERMS = new HashSet<>(Arrays.asList( "HP:0002086","HP:0045027","HP:0001871","HP:0001939","HP:0001574","HP:0001608",
            "HP:0001626","HP:0025354","HP:0001507","HP:0025142","HP:0001197","HP:0003549",
            "HP:0025031","HP:0003011","HP:0040064","HP:0000924","HP:0000769","HP:0000707",
            "HP:0000818","HP:0000478","HP:0000598","HP:0002664","HP:0002715","HP:0000119",
            "HP:0000152"));

    // These parsers are used by several indexers so it makes sense to initialize them in one place, so that they don't get out of synch.
    public OntologyParser getMpParser() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, SQLException {
        return  new OntologyParser(owlpath + "/mp.owl", "MP", TOP_LEVEL_MP_TERMS, getWantedMPIds());
    }

    public OntologyParser getMpMaParser() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException {
        return new OntologyParser(owlpath + "/mp-ext-merged.owl", "MP", null, null);
    }

    public OntologyParser getMpHpParser() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, SQLException {
        return new OntologyParser(owlpath + "/mp-hp.owl", "MP", null, null);
    }

    public OntologyParser getMaParser() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, SQLException {
        return new OntologyParser(owlpath + "/ma.owl", "MA", TOP_LEVEL_MA_TERMS, getMaWantedIds());
    }

    public OntologyParser getEmapaParser() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, SQLException {
        return new OntologyParser(owlpath + "/emapa.owl", "EMAPA", TOP_LEVEL_EMAPA_TERMS, getEmapaWantedIds());
    }

    public OntologyParser getUberonParser() throws OWLOntologyCreationException, OWLOntologyStorageException, IOException, SQLException {
        return new OntologyParser(owlpath + "/uberon.owl", "UBERON", null, null);
    }

    protected Set<String> getMaWantedIds() throws SQLException, OWLOntologyCreationException, OWLOntologyStorageException, IOException {

        Set<String> wantedIds = new HashSet<>();

        // Get MA terms from Sanger images
        PreparedStatement statement = komp2DataSource.getConnection().prepareStatement("SELECT DISTINCT (UPPER(TERM_ID)) AS TERM_ID FROM ANN_ANNOTATION");
        ResultSet res = statement.executeQuery();
        while (res.next()) {
            String r= res.getString("TERM_ID");
            if (r != null && r.startsWith("MA:")){
                wantedIds.add(r);
            }
        }
        // Add MA ids from IMPRESS
        wantedIds.addAll(getOntologyIds(8, komp2DataSource));

        // Get MA terms referenced by MP terms in the slim
        Set<String> wantedMp = getWantedMPIds();
        OntologyParser mpMaParser = getMpMaParser();

        for (String mpId: wantedMp){
            wantedIds.addAll( mpMaParser.getReferencedClasses(mpId, VIA_PROPERTIES, "MA"));
        }

        return wantedIds;

    }

    protected Set<String> getEmapaWantedIds() throws SQLException, IOException {

        Set<String> wantedIds = new HashSet<>();
        Set<String> emapIds = new HashSet<>();

        // In IMPRESS we have only EMAP ids
        emapIds.addAll(getOntologyIds(14, komp2DataSource));

        // Add EMAP terms from image annotations
        PreparedStatement statement = komp2DataSource.getConnection().prepareStatement("SELECT DISTINCT(UPPER(ontology_acc)) as TERM_ID FROM phenotype_parameter_ontology_annotation ppoa WHERE ppoa.ontology_db_id=?");
        statement.setInt(1, 14);
        ResultSet res = statement.executeQuery();
        while (res.next()) {
            String r = res.getString("TERM_ID");
            if (r.startsWith("EMAP:")){
                emapIds.add(r);
            }
        }
        emapIds.addAll(getOntologyIds(14, komp2DataSource));

        //Get EMAPA list by parsing EMAP list and check mapping txt ftp://ftp.hgu.mrc.ac.uk/pub/MouseAtlas/Anatomy/EMAP-EMAPA.txt
        Map<String,String> emapMap = getEmapToEmapaMap();
        for (String emapTerm: emapIds){
            wantedIds.add(emapMap.get(emapTerm));
        }

        // Get EMAPA terms from Sanger images
        statement = komp2DataSource.getConnection().prepareStatement("SELECT DISTINCT (UPPER(TERM_ID)) AS TERM_ID FROM ANN_ANNOTATION");
        res = statement.executeQuery();
        while (res.next()) {
            String r= res.getString("TERM_ID");
            if (r != null && r.startsWith("EMAPA:")){
                wantedIds.add(r);
            }
        }

        // We have no EMAPA terms referenced by MP terms in the slim

        return wantedIds;

    }

    /**
     *
     * @return all MP ids that we want in the slim
     * @throws SQLException
     */
    protected Set<String> getWantedMPIds() throws SQLException {

        // Select MP terms from images too
        Set<String> wantedIds = new HashSet<>();

        // Get mp terms from Sanger images
        PreparedStatement statement = komp2DataSource.getConnection().prepareStatement("SELECT DISTINCT (UPPER(TERM_ID)) AS TERM_ID, (UPPER(TERM_NAME)) as TERM_NAME FROM  IMA_IMAGE_TAG iit INNER JOIN ANN_ANNOTATION aa ON aa.FOREIGN_KEY_ID=iit.ID");
        ResultSet res = statement.executeQuery();
        while (res.next()) {
            String r = res.getString("TERM_ID");
            if (r.startsWith("MP:")) {
                wantedIds.add(r);
            }
        }

        //All MP terms we can have annotations to (from IMPRESS)
        wantedIds.addAll(getOntologyIds(5, komp2DataSource));

        return wantedIds;
    }

    /**
     * @author tudose
     * @param ontologyId database id. [14=emap, 5=mp, 8=ma]
     * @return
     * @throws SQLException
     */
    public List<String> getOntologyIds(Integer ontologyId, DataSource ds) throws SQLException{

        PreparedStatement statement = ds.getConnection().prepareStatement(
                "SELECT DISTINCT(ontology_acc) FROM phenotype_parameter_ontology_annotation ppoa WHERE ppoa.ontology_db_id=" + ontologyId);
        ResultSet res = statement.executeQuery();
        List<String> terms = new ArrayList<>();

        while (res.next()) {
            terms.add(res.getString("ontology_acc"));
        }

        return terms;
    }

    // EMAP to EMAPA mapping obtained by CK. Richard Baldock confirmed this is not maintained any more so we maintain it in our repo. Can add terms as needed.
    // Another way would be to use UBERON and get the EMAP and EMAPA cross refs from there.
    public Map<String,String> getEmapToEmapaMap()
            throws IOException {

        File emapEmapa = new File (owlpath + "/EMAP-EMAPA.txt") ;
        Scanner scan = new Scanner(emapEmapa);
        String line="";
        Map<String,String> emapMap = new HashMap<>();

        while (scan.hasNextLine())		{
            line = scan.nextLine();
            String[] split=line.split("\t");
            emapMap.put(split[0], split[2]);
        }

        return emapMap;
    }
}


text:
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.

using System;
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Allocation;
using osu.Framework.Extensions.TypeExtensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Input.Events;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Input.States;
using osu.Framework.Logging;
using osu.Framework.Platform;
using osu.Framework.Statistics;
using osuTK;
using osuTK.Input;
using JoystickState = osu.Framework.Input.States.JoystickState;
using KeyboardState = osu.Framework.Input.States.KeyboardState;
using MouseState = osu.Framework.Input.States.MouseState;

namespace osu.Framework.Input
{
    public abstract class InputManager : Container, IInputStateChangeHandler
    {
        /// <summary>
        /// The initial delay before key repeat begins.
        /// </summary>
        private const int repeat_initial_delay = 250;

        /// <summary>
        /// The delay between key repeats after the initial repeat.
        /// </summary>
        private const int repeat_tick_rate = 70;

        [Resolved(CanBeNull = true)]
        protected GameHost Host { get; private set; }

        /// <summary>
        /// The currently focused <see cref="Drawable"/>. Null if there is no current focus.
        /// </summary>
        public Drawable FocusedDrawable { get; internal set; }

        protected abstract IEnumerable<InputHandler> InputHandlers { get; }

        private double keyboardRepeatTime;
        private Key? keyboardRepeatKey;

        /// <summary>
        /// The initial input state. <see cref="CurrentState"/> is always equal (as a reference) to the value returned from this.
        /// <see cref="InputState.Mouse"/>, <see cref="InputState.Keyboard"/> and <see cref="InputState.Joystick"/> should be non-null.
        /// </summary>
        protected virtual InputState CreateInitialState() => new InputState(new MouseState { IsPositionValid = false }, new KeyboardState(), new JoystickState());

        /// <summary>
        /// The last processed state.
        /// </summary>
        public readonly InputState CurrentState;

        /// <summary>
        /// The <see cref="Drawable"/> which is currently being dragged. null if none is.
        /// </summary>
        public Drawable DraggedDrawable
        {
            get
            {
                mouseButtonEventManagers.TryGetValue(MouseButton.Left, out var manager);
                return manager?.DraggedDrawable;
            }
        }

        /// <summary>
        /// Contains the previously hovered <see cref="Drawable"/>s prior to when
        /// <see cref="hoveredDrawables"/> got updated.
        /// </summary>
        private readonly List<Drawable> lastHoveredDrawables = new List<Drawable>();

        /// <summary>
        /// Contains all hovered <see cref="Drawable"/>s in top-down order up to the first
        /// which returned true in its <see cref="Drawable.OnHover"/> method.
        /// Top-down in this case means reverse draw order, i.e. the front-most visible
        /// <see cref="Drawable"/> first, and <see cref="Container"/>s after their children.
        /// </summary>
        private readonly List<Drawable> hoveredDrawables = new List<Drawable>();

        /// <summary>
        /// The <see cref="Drawable"/> which returned true in its
        /// <see cref="Drawable.OnHover"/> method, or null if none did so.
        /// </summary>
        private Drawable hoverHandledDrawable;

        /// <summary>
        /// Contains all hovered <see cref="Drawable"/>s in top-down order up to the first
        /// which returned true in its <see cref="Drawable.OnHover"/> method.
        /// Top-down in this case means reverse draw order, i.e. the front-most visible
        /// <see cref="Drawable"/> first, and <see cref="Container"/>s after their children.
        /// </summary>
        public IReadOnlyList<Drawable> HoveredDrawables => hoveredDrawables;

        /// <summary>
        /// Contains all <see cref="Drawable"/>s in top-down order which are considered
        /// for positional input. This list is the same as <see cref="HoveredDrawables"/>, only
        /// that the return value of <see cref="Drawable.OnHover"/> is not taken
        /// into account.
        /// </summary>
        public IEnumerable<Drawable> PositionalInputQueue => buildPositionalInputQueue(CurrentState);

        /// <summary>
        /// Contains all <see cref="Drawable"/>s in top-down order which are considered
        /// for non-positional input.
        /// </summary>
        public IEnumerable<Drawable> NonPositionalInputQueue => buildNonPositionalInputQueue();

        private readonly Dictionary<MouseButton, MouseButtonEventManager> mouseButtonEventManagers = new Dictionary<MouseButton, MouseButtonEventManager>();

        protected InputManager()
        {
            CurrentState = CreateInitialState();
            RelativeSizeAxes = Axes.Both;

            foreach (var button in Enum.GetValues(typeof(MouseButton)).Cast<MouseButton>())
            {
                var manager = CreateButtonManagerFor(button);
                manager.RequestFocus = ChangeFocusFromClick;
                manager.GetPositionalInputQueue = () => PositionalInputQueue;
                mouseButtonEventManagers.Add(button, manager);
            }
        }

        /// <summary>
        /// Create a <see cref="MouseButtonEventManager"/> for a specified mouse button.
        /// </summary>
        /// <param name="button">The button to be handled by the returned manager.</param>
        /// <returns>The <see cref="MouseButtonEventManager"/>.</returns>
        protected virtual MouseButtonEventManager CreateButtonManagerFor(MouseButton button)
        {
            switch (button)
            {
                case MouseButton.Left:
                    return new MouseLeftButtonEventManager(button);
                default:
                    return new MouseMinorButtonEventManager(button);
            }
        }

        /// <summary>
        /// Reset current focused drawable to the top-most drawable which is <see cref="Drawable.RequestsFocus"/>.
        /// </summary>
        /// <param name="triggerSource">The source which triggered this event.</param>
        public void TriggerFocusContention(Drawable triggerSource)
        {
            if (FocusedDrawable == null) return;

            Logger.Log($"Focus contention triggered by {triggerSource}.");
            ChangeFocus(null);
        }

        /// <summary>
        /// Changes the currently-focused drawable. First checks that <see cref="potentialFocusTarget"/> is in a valid state to receive focus,
        /// then unfocuses the current <see cref="FocusedDrawable"/> and focuses <see cref="potentialFocusTarget"/>.
        /// <see cref="potentialFocusTarget"/> can be null to reset focus.
        /// If the given drawable is already focused, nothing happens and no events are fired.
        /// </summary>
        /// <param name="potentialFocusTarget">The drawable to become focused.</param>
        /// <returns>True if the given drawable is now focused (or focus is dropped in the case of a null target).</returns>
        public bool ChangeFocus(Drawable potentialFocusTarget) => ChangeFocus(potentialFocusTarget, CurrentState);

        /// <summary>
        /// Changes the currently-focused drawable. First checks that <see cref="potentialFocusTarget"/> is in a valid state to receive focus,
        /// then unfocuses the current <see cref="FocusedDrawable"/> and focuses <see cref="potentialFocusTarget"/>.
        /// <see cref="potentialFocusTarget"/> can be null to reset focus.
        /// If the given drawable is already focused, nothing happens and no events are fired.
        /// </summary>
        /// <param name="potentialFocusTarget">The drawable to become focused.</param>
        /// <param name="state">The <see cref="InputState"/> associated with the focusing event.</param>
        /// <returns>True if the given drawable is now focused (or focus is dropped in the case of a null target).</returns>
        protected bool ChangeFocus(Drawable potentialFocusTarget, InputState state)
        {
            if (potentialFocusTarget == FocusedDrawable)
                return true;

            if (potentialFocusTarget != null && (!potentialFocusTarget.IsPresent || !potentialFocusTarget.AcceptsFocus))
                return false;

            var previousFocus = FocusedDrawable;

            FocusedDrawable = null;

            if (previousFocus != null)
            {
                previousFocus.HasFocus = false;
                previousFocus.TriggerEvent(new FocusLostEvent(state));

                if (FocusedDrawable != null) throw new InvalidOperationException($"Focus cannot be changed inside {nameof(OnFocusLost)}");
            }

            FocusedDrawable = potentialFocusTarget;

            Logger.Log($"Focus changed from {previousFocus?.ToString() ?? "nothing"} to {FocusedDrawable?.ToString() ?? "nothing"}.", LoggingTarget.Runtime, LogLevel.Debug);

            if (FocusedDrawable != null)
            {
                FocusedDrawable.HasFocus = true;
                FocusedDrawable.TriggerEvent(new FocusEvent(state));
            }

            return true;
        }

        internal override bool BuildNonPositionalInputQueue(List<Drawable> queue, bool allowBlocking = true)
        {
            if (!allowBlocking)
                base.BuildNonPositionalInputQueue(queue, false);

            return false;
        }

        internal override bool BuildPositionalInputQueue(Vector2 screenSpacePos, List<Drawable> queue) => false;

        private bool hoverEventsUpdated;

        protected override void Update()
        {
            unfocusIfNoLongerValid();

            // aggressively clear to avoid holding references.
            inputQueue.Clear();
            positionalInputQueue.Clear();

            hoverEventsUpdated = false;

            foreach (var result in GetPendingInputs())
            {
                result.Apply(CurrentState, this);
            }

            if (CurrentState.Mouse.IsPositionValid)
            {
                PropagateBlockableEvent(PositionalInputQueue.Where(d => d is IRequireHighFrequencyMousePosition), new MouseMoveEvent(CurrentState));
            }

            updateKeyRepeat(CurrentState);

            // Other inputs or drawable changes may affect hover even if
            // there were no mouse movements, so it must be updated every frame.
            if (!hoverEventsUpdated)
                updateHoverEvents(CurrentState);

            if (FocusedDrawable == null)
                focusTopMostRequestingDrawable();

            base.Update();
        }

        private void updateKeyRepeat(InputState state)
        {
            if (!(keyboardRepeatKey is Key key)) return;

            keyboardRepeatTime -= Time.Elapsed;
            while (keyboardRepeatTime < 0)
            {
                handleKeyDown(state, key, true);
                keyboardRepeatTime += repeat_tick_rate;
            }
        }

        protected virtual List<IInput> GetPendingInputs()
        {
            var inputs = new List<IInput>();

            foreach (var h in InputHandlers)
            {
                inputs.AddRange(h.GetPendingInputs());
            }

            return inputs;
        }

        private readonly List<Drawable> inputQueue = new List<Drawable>();

        private IEnumerable<Drawable> buildNonPositionalInputQueue()
        {
            inputQueue.Clear();

            if (this is UserInputManager)
                FrameStatistics.Increment(StatisticsCounterType.InputQueue);

            var children = AliveInternalChildren;
            for (int i = 0; i < children.Count; i++)
                children[i].BuildNonPositionalInputQueue(inputQueue);

            if (!unfocusIfNoLongerValid())
            {
                inputQueue.Remove(FocusedDrawable);
                inputQueue.Add(FocusedDrawable);
            }

            // queues were created in back-to-front order.
            // We want input to first reach front-most drawables, so the queues
            // need to be reversed.
            inputQueue.Reverse();

            return inputQueue;
        }

        private readonly List<Drawable> positionalInputQueue = new List<Drawable>();

        private IEnumerable<Drawable> buildPositionalInputQueue(InputState state)
        {
            positionalInputQueue.Clear();

            if (this is UserInputManager)
                FrameStatistics.Increment(StatisticsCounterType.PositionalIQ);

            var children = AliveInternalChildren;
            for (int i = 0; i < children.Count; i++)
                children[i].BuildPositionalInputQueue(state.Mouse.Position, positionalInputQueue);

            positionalInputQueue.Reverse();
            return positionalInputQueue;
        }

        protected virtual bool HandleHoverEvents => true;

        private void updateHoverEvents(InputState state)
        {
            Drawable lastHoverHandledDrawable = hoverHandledDrawable;
            hoverHandledDrawable = null;

            lastHoveredDrawables.Clear();
            lastHoveredDrawables.AddRange(hoveredDrawables);

            hoveredDrawables.Clear();

            // New drawables shouldn't be hovered if the cursor isn't in the window
            if (HandleHoverEvents)
            {
                // First, we need to construct hoveredDrawables for the current frame
                foreach (Drawable d in PositionalInputQueue)
                {
                    hoveredDrawables.Add(d);
                    lastHoveredDrawables.Remove(d);

                    // Don't need to re-hover those that are already hovered
                    if (d.IsHovered)
                    {
                        // Check if this drawable previously handled hover, and assume it would once more
                        if (d == lastHoverHandledDrawable)
                        {
                            hoverHandledDrawable = lastHoverHandledDrawable;
                            break;
                        }

                        continue;
                    }

                    d.IsHovered = true;
                    if (d.TriggerEvent(new HoverEvent(state)))
                    {
                        hoverHandledDrawable = d;
                        break;
                    }
                }
            }

            // Unhover all previously hovered drawables which are no longer hovered.
            foreach (Drawable d in lastHoveredDrawables)
            {
                d.IsHovered = false;
                d.TriggerEvent(new HoverLostEvent(state));
            }

            hoverEventsUpdated = true;
        }

        private bool isModifierKey(Key k)
        {
            return k == Key.LControl || k == Key.RControl
                                     || k == Key.LAlt || k == Key.RAlt
                                     || k == Key.LShift || k == Key.RShift
                                     || k == Key.LWin || k == Key.RWin;
        }

        protected virtual void HandleKeyboardKeyStateChange(ButtonStateChangeEvent<Key> keyboardKeyStateChange)
        {
            var state = keyboardKeyStateChange.State;
            var key = keyboardKeyStateChange.Button;
            var kind = keyboardKeyStateChange.Kind;

            if (kind == ButtonStateChangeKind.Pressed)
            {
                handleKeyDown(state, key, false);

                if (!isModifierKey(key))
                {
                    keyboardRepeatKey = key;
                    keyboardRepeatTime = repeat_initial_delay;
                }
            }
            else
            {
                handleKeyUp(state, key);

                keyboardRepeatKey = null;
                keyboardRepeatTime = 0;
            }
        }

        protected virtual void HandleJoystickButtonStateChange(ButtonStateChangeEvent<JoystickButton> joystickButtonStateChange)
        {
            var state = joystickButtonStateChange.State;
            var button = joystickButtonStateChange.Button;
            var kind = joystickButtonStateChange.Kind;

            if (kind == ButtonStateChangeKind.Pressed)
            {
                handleJoystickPress(state, button);
            }
            else
            {
                handleJoystickRelease(state, button);
            }
        }

        public virtual void HandleInputStateChange(InputStateChangeEvent inputStateChange)
        {
            switch (inputStateChange)
            {
                case MousePositionChangeEvent mousePositionChange:
                    HandleMousePositionChange(mousePositionChange);
                    return;
                case MouseScrollChangeEvent mouseScrollChange:
                    HandleMouseScrollChange(mouseScrollChange);
                    return;
                case ButtonStateChangeEvent<MouseButton> mouseButtonStateChange:
                    HandleMouseButtonStateChange(mouseButtonStateChange);
                    return;
                case ButtonStateChangeEvent<Key> keyboardKeyStateChange:
                    HandleKeyboardKeyStateChange(keyboardKeyStateChange);
                    return;
                case ButtonStateChangeEvent<JoystickButton> joystickButtonStateChange:
                    HandleJoystickButtonStateChange(joystickButtonStateChange);
                    return;
            }
        }

        protected virtual void HandleMousePositionChange(MousePositionChangeEvent e)
        {
            var state = e.State;
            var mouse = state.Mouse;

            foreach (var h in InputHandlers)
                if (h.Enabled.Value && h is INeedsMousePositionFeedback handler)
                    handler.FeedbackMousePositionChange(mouse.Position);

            handleMouseMove(state, e.LastPosition);

            foreach (var manager in mouseButtonEventManagers.Values)
                manager.HandlePositionChange(state, e.LastPosition);

            updateHoverEvents(state);
        }

        protected virtual void HandleMouseScrollChange(MouseScrollChangeEvent e)
        {
            handleScroll(e.State, e.LastScroll, e.IsPrecise);
        }

        protected virtual void HandleMouseButtonStateChange(ButtonStateChangeEvent<MouseButton> e)
        {
            if (mouseButtonEventManagers.TryGetValue(e.Button, out var manager))
                manager.HandleButtonStateChange(e.State, e.Kind, Time.Current);
        }

        private bool handleMouseMove(InputState state, Vector2 lastPosition)
        {
            return PropagateBlockableEvent(PositionalInputQueue, new MouseMoveEvent(state, lastPosition));
        }

        private bool handleScroll(InputState state, Vector2 lastScroll, bool isPrecise)
        {
            return PropagateBlockableEvent(PositionalInputQueue, new ScrollEvent(state, state.Mouse.Scroll - lastScroll, isPrecise));
        }

        private bool handleKeyDown(InputState state, Key key, bool repeat)
        {
            return PropagateBlockableEvent(NonPositionalInputQueue, new KeyDownEvent(state, key, repeat));
        }

        private bool handleKeyUp(InputState state, Key key)
        {
            return PropagateBlockableEvent(NonPositionalInputQueue, new KeyUpEvent(state, key));
        }

        private bool handleJoystickPress(InputState state, JoystickButton button)
        {
            return PropagateBlockableEvent(NonPositionalInputQueue, new JoystickPressEvent(state, button));
        }

        private bool handleJoystickRelease(InputState state, JoystickButton button)
        {
            return PropagateBlockableEvent(NonPositionalInputQueue, new JoystickReleaseEvent(state, button));
        }

        /// <summary>
        /// Triggers events on drawables in <paramref cref="drawables"/> until it is handled.
        /// </summary>
        /// <param name="drawables">The drawables in the queue.</param>
        /// <param name="e">The event.</param>
        /// <returns>Whether the event was handled.</returns>
        protected virtual bool PropagateBlockableEvent(IEnumerable<Drawable> drawables, UIEvent e)
        {
            var handledBy = drawables.FirstOrDefault(target => target.TriggerEvent(e));

            if (handledBy != null)
            {
                var detail = handledBy is ISuppressKeyEventLogging ? e.GetType().ReadableName() : e.ToString();
                Logger.Log($"{detail} handled by {handledBy}.", LoggingTarget.Runtime, LogLevel.Debug);
            }

            return handledBy != null;
        }

        /// <summary>
        /// Unfocus the current focused drawable if it is no longer in a valid state.
        /// </summary>
        /// <returns>true if there is no longer a focus.</returns>
        private bool unfocusIfNoLongerValid()
        {
            if (FocusedDrawable == null) return true;

            bool stillValid = FocusedDrawable.IsAlive && FocusedDrawable.IsPresent && FocusedDrawable.Parent != null;

            if (stillValid)
            {
                //ensure we are visible
                CompositeDrawable d = FocusedDrawable.Parent;
                while (d != null)
                {
                    if (!d.IsPresent || !d.IsAlive)
                    {
                        stillValid = false;
                        break;
                    }

                    d = d.Parent;
                }
            }

            if (stillValid)
                return false;

            Logger.Log($"Focus on \"{FocusedDrawable}\" no longer valid as a result of {nameof(unfocusIfNoLongerValid)}.", LoggingTarget.Runtime, LogLevel.Debug);
            ChangeFocus(null);
            return true;
        }

        protected virtual void ChangeFocusFromClick(Drawable clickedDrawable)
        {
            Drawable focusTarget = null;

            if (clickedDrawable != null)
            {
                focusTarget = clickedDrawable;

                if (!focusTarget.AcceptsFocus)
                {
                    // search upwards from the clicked drawable until we find something to handle focus.
                    Drawable previousFocused = FocusedDrawable;

                    while (focusTarget?.AcceptsFocus == false)
                        focusTarget = focusTarget.Parent;

                    if (focusTarget != null && previousFocused != null)
                    {
                        // we found a focusable target above us.
                        // now search upwards from previousFocused to check whether focusTarget is a common parent.
                        Drawable search = previousFocused;
                        while (search != null && search != focusTarget)
                            search = search.Parent;

                        if (focusTarget == search)
                            // we have a common parent, so let's keep focus on the previously focused target.
                            focusTarget = previousFocused;
                    }
                }
            }

            ChangeFocus(focusTarget);
        }

        private void focusTopMostRequestingDrawable()
        {
            // todo: don't rebuild input queue every frame
            ChangeFocus(NonPositionalInputQueue.FirstOrDefault(target => target.RequestsFocus));
        }

        private class MouseLeftButtonEventManager : MouseButtonEventManager
        {
            public MouseLeftButtonEventManager(MouseButton button)
                : base(button)
            {
            }

            public override bool EnableDrag => true;

            public override bool EnableClick => true;

            public override bool ChangeFocusOnClick => true;
        }

        private class MouseMinorButtonEventManager : MouseButtonEventManager
        {
            public MouseMinorButtonEventManager(MouseButton button)
                : base(button)
            {
            }

            public override bool EnableDrag => false;

            public override bool EnableClick => false;

            public override bool ChangeFocusOnClick => false;
        }
    }
}


text:
#include <csignal>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "../include/producer.hpp"
#include "../include/consumer.hpp"
#include "../include/blocking_queue.hpp"
#include "../include/data_entry.h"
#include "../include/conditional_var.hpp"

#define	DEFAULT_NUM_PRODUCERS 2
#define	DEFAULT_MAX_DATA_SIZE 15
#define	DEFAULT_NUM_CONSUMERS 3

// References defined in the global scope to enable access to them in the
// signal callback handler.
int num_producers, max_data_size, num_consumers;

mutex mtx;
conditional_var c(&mtx);
blocking_queue<data_entry> queue(&mtx);

producer * producers[DEFAULT_NUM_PRODUCERS];
consumer * consumers[DEFAULT_NUM_CONSUMERS];

/**
 * Callback handler registered to listen for the SIGINT signal and to then
 * shutdown all of the running threads.
 */
void signal_callback_handler(int signum)
{
	std::cout << "Caught signal " << signum << std::endl;

	// Tell all of our threads to shutdown
	for (int i = 0; i < num_producers; ++i)
	{
		producers[i]->shutdown();
	}

	for (int i = 0; i < num_consumers; ++i)
	{
		consumers[i]->shutdown();
	}
}

int main(int argc, char* argv[])
{
	// Register the SIGINT signal and the signal handler
	std::signal(SIGINT, signal_callback_handler);

	std::cout << "Starting cpp-unit-test-example..." << std::endl;

	// Parse our command line arguments.
	int  arg_ints[3] {0, 0, 0};
	if ( argc > 1)
	{
		for (int i = 1; i < argc; ++i)
		{
			std::cout << "argv[" << i << "] = " << argv[i] << std::endl;
			arg_ints[(i - 1)] = atoi(argv[i]);
		}
	}

	for (int i = 0; i < 3; ++i)
	{
		std::cout << "arg_ints[" << i << "] = " << arg_ints[i] << std::endl;
	}

	//
	// If we were passed a command line argument, override the default values
	// for the threads to instantiate.  Otherwise we use the constants.
	//
	if (arg_ints[0] != 0)
	{
		num_producers = arg_ints[0];
		producer * producers[num_producers];
	}
	else
	{
		num_producers = DEFAULT_NUM_PRODUCERS;
	}

	if (arg_ints[1] != 0)
	{
		max_data_size = arg_ints[1];
	}
	else
	{
		max_data_size = DEFAULT_MAX_DATA_SIZE;
	}

	if (arg_ints[2] != 0)
	{
		num_consumers = arg_ints[2];
		consumer * consumers[num_consumers];
	}
	else
	{
		num_consumers = DEFAULT_NUM_CONSUMERS;
	}

	//
	// Instantiate the producers and consumers
	//
	char buff [64];
	int n;

	for (int i = 0; i < num_producers; ++i)
	{
		// Concatenate the id for the producer
		n = sprintf(buff, "Producer %d", (i + 1));

		// Instantiate the producer and start the thread
		producers[i] = new producer(&queue, &mtx, &c, buff);
		producers[i]->produce(max_data_size);
	}

	for (int i = 0; i < num_consumers; ++i)
	{
		// Concatenate the id for the consumer
		n = sprintf(buff, "Consumer %d", (i + 1));

		// Instantiate the consumer and start the thread
		consumers[i] = new consumer(&queue, &mtx, &c, buff);
		consumers[i]->consume();
	}

	// Join the current thread on all of the new threads
	for (int i = 0; i < num_producers; ++i)
	{
		producers[i]->join();
	}

	for (int i = 0; i < num_consumers; ++i)
	{
		consumers[i]->join();
	}

	// Delete our instances and set the pointers to NULL
	for (int i = 0; i < num_producers; ++i)
	{
		delete producers[i];
		producers[i] = NULL;
	}

	for (int i = 0; i < num_consumers; ++i)
	{
		delete consumers[i];
		consumers[i] = NULL;
	}

	return (0);
}


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=type.U414.html">

Redirecting to type.U414.html...