text:
<?php
class HeadwayDynamicStyle {

	static function design_editor() {

		$elements = HeadwayElementsData::get_all_elements();

		$return = "/* DESIGN EDITOR STYLING */\n";

		foreach ( $elements as $element_id => $element_options ) {

			$element = HeadwayElementAPI::get_element($element_id);
			$selector = $element['selector'];

			//Continue to next element if the element/selector does not exist
			if ( !isset($selector) || $selector == false )
				continue;

			/* Regular Element */
			if ( isset($element_options['properties']) )
				$return .= HeadwayElementProperties::output_css($selector, $element_options['properties']);

			/* Layout-specific elements */
			if ( isset($element_options['special-element-layout']) && is_array($element_options['special-element-layout']) ) {

				//Handle every layout
				foreach ( $element_options['special-element-layout'] as $layout => $layout_properties ) {

					//Get the selector for the layout
					$layout_element_selector = 'body.layout-using-' . $layout . ' ' . $selector;

					//Since the layout selectors are targeted by the body element, we can't do anything body to style the actual body element.  Let's fix that.
					if ( $selector == 'body' )
						$layout_element_selector = str_replace(' body', '', $layout_element_selector); //The space inside str_replace is completely intentional.

					$return .= HeadwayElementProperties::output_css($layout_element_selector, $layout_properties);

				}

			}

			/* Instances */
			if ( isset($element_options['special-element-instance']) && is_array($element_options['special-element-instance']) ) {

				//Handle every instance
				foreach ( $element_options['special-element-instance'] as $instance => $instance_properties ) {

					//Make sure the instance exists
					if ( !isset($element['instances'][$instance]) )
						continue;

					//Get the selector for the instance
					$instance_selector = $element['instances'][$instance]['selector'];

					$return .= HeadwayElementProperties::output_css($instance_selector, $instance_properties);

				}

			}

			/* States */
			if ( isset($element_options['special-element-state']) && is_array($element_options['special-element-state']) ) {

				//Handle every instance
				foreach ( $element_options['special-element-state'] as $state => $state_properties ) {

					//Make sure the state exists
					if ( !isset($element['states'][ucwords($state)]) )
						continue;

					//Get the selector for the layout
					$state_selector = $element['states'][ucwords($state)];

					$return .= HeadwayElementProperties::output_css($state_selector, $state_properties);

				}

			}

		} //End main $elements foreach

		return $return;

	}

	static function grid() {

		return !HeadwayResponsiveGrid::is_enabled() ? self::fixed_grid() : self::responsive_grid();

	}

		static function fixed_grid() {

			$grid_number = HeadwayGrid::$columns;
			$column_width = HeadwayGrid::$column_width;
			$gutter_width = HeadwayGrid::$gutter_width;

			$grid_wrapper_width = ($column_width * $grid_number) + ($grid_number * $gutter_width);

			/* Column left margins */
			$return = '.column { margin-left: ' . ($gutter_width) . 'px; }';

			/* Widths and Lefts */
			for ( $i = 1; $i <= $grid_number; $i++ ) {

				/* Vars */
				$grid_width = $column_width * $i + (($i - 1) * $gutter_width);
				$grid_left_margin = (($column_width + $gutter_width) * $i) + $gutter_width;

				$return .= '.grid-width-' . $i . ' { width:' . ($grid_width) . 'px; }';
				$return .= '.grid-left-' . $i . ' { margin-left: ' . ($grid_left_margin) . 'px; }';

				/**
				 * If it's the first column in a row and the column doesn't start on the far left,
				 * then the additional gutter doesn't have to be taken into consideration
				 **/
				$return .= '.column-1.grid-left-' . $i . ' { margin-left: ' . ($grid_left_margin - $gutter_width) . 'px; }';

			}

			return $return;

		}

		static function responsive_grid() {

			$round_precision = 9;

			$grid_number = HeadwayGrid::$columns;
			$column_width = HeadwayGrid::$column_width;
			$gutter_width = HeadwayGrid::$gutter_width;

			$grid_wrapper_width = ($column_width * $grid_number) + ($grid_number * $gutter_width);

			$resp_width_ratio = ($column_width * $grid_number) / $grid_wrapper_width;
			$resp_gutter_ratio = ($gutter_width * $grid_number) / $grid_wrapper_width;
			$resp_single_column_width = (100 / $grid_number) * $resp_width_ratio;
			$resp_single_column_margin = (100 / $grid_number) * $resp_gutter_ratio;

			$return = '.column { margin-left: ' . round($resp_single_column_margin, $round_precision) . '%; }';

			for ( $i = 1; $i <= $grid_number; $i++ ) {

				/* Vars */
				$resp_grid_width = ($resp_single_column_width * $i) + ($i * $resp_single_column_margin);
				$resp_grid_left_margin = (($resp_single_column_width + $resp_single_column_margin) * $i) + $resp_single_column_margin;

				$sub_column_single_width = ($resp_single_column_width / $resp_grid_width) * 100;
				$sub_column_single_margin = ($resp_single_column_margin / $resp_grid_width) * 100;

				/* Output */
				$return .= '.grid-width-' . $i . ' { width: ' . round($resp_grid_width - $resp_single_column_margin, $round_precision) . '%; }';
				$return .= '.grid-width-' . $i . '.column-1 { width: ' . round($resp_grid_width, $round_precision) . '%; }';

				if ( $i < 24 ) {

					$return .= '.grid-left-' . $i . ' { margin-left: ' . round($resp_grid_left_margin, $round_precision) . '%; }';
					$return .= '.grid-left-' . $i . '.column-1 { margin-left: ' . round($resp_grid_left_margin - $resp_single_column_margin, $round_precision) . '%; }';

				}

				/* Responsive Sub Columns */
				$return .= '.grid-width-' . $i . ' .sub-column { margin-left: ' . round($sub_column_single_margin, $round_precision) . '%; }';

				for ( $sub_column_i = 1; $sub_column_i < $i; $sub_column_i++ ) {

					$sub_column_width = ($sub_column_single_width * $sub_column_i) + ($sub_column_i * $sub_column_single_margin);
					$sub_column_margin = (($sub_column_single_width + $sub_column_single_margin) * $sub_column_i) + $sub_column_single_margin;

					$return .= '.grid-width-' . $i . ' .sub-column.grid-width-' . $sub_column_i . ' { width: ' . round($sub_column_width - $sub_column_single_margin, $round_precision) . '%; }';
					$return .= '.grid-width-' . $i . ' .sub-column.grid-width-' . $sub_column_i . '.column-1 { width: ' . round($sub_column_width, $round_precision) . '%; }';

					$return .= '.grid-width-' . $i . ' .sub-column.grid-left-' . $sub_column_i . ' { margin-left: ' . round($sub_column_margin, $round_precision) . '%; }';
					$return .= '.grid-width-' . $i . ' .sub-column.grid-left-' . $sub_column_i . '.column-1 { margin-left: ' . round($sub_column_margin - $sub_column_single_margin, $round_precision) . '%; }';

				}

			}

			return $return;

		}

		static function visual_editor_grid() {

			$grid_number = HeadwayGrid::$columns;
			$column_width = HeadwayGrid::$column_width;
			$gutter_width = HeadwayGrid::$gutter_width;

			$grid_height = HeadwayOption::get('grid-height', false, 1500);

			/* Little grid lines in VE ... Subtract two off for the border-right and border-left on the grid column */
			$left_margin = ceil(($gutter_width / 2) - 1);
			$right_margin = floor(($gutter_width / 2) - 1);

			$return = 'div.grid-container { height: ' . $grid_height . 'px; }';
			$return .= 'div#grid div.grid-column { height: ' . $grid_height . 'px; margin: 0 ' . $right_margin . 'px 0 ' . $left_margin . 'px; }';

			/* Widths and Lefts */
			for ( $i = 1; $i <= $grid_number; $i++ ) {

				/* Visual Editor Grid Mode */
				$return .= '.grid-width-' . $i . '  { width: ' . ($column_width * $i + (($i - 1) * $gutter_width)) . 'px; }';
				$return .= '.grid-left-' . $i . '  { left: ' . (($column_width + $gutter_width) * $i) . 'px; }';

			}

			/* Set width for container when in layout mode to make sure the draggable works properly. */
			$return .= 'div.grid-container { width: ' . (HeadwayGrid::get_grid_width() + 1) . 'px; }';

			return $return;

		}

		static function block_heights() {

			if ( !($blocks = HeadwayBlocksData::get_all_blocks()) )
				return false;

			$return = '';

			//Retrieve the blocks so we can check if the block type is fixed or fluid height
			$block_types = HeadwayBlocks::get_block_types();

			foreach ( $blocks as $block ) {

				$selector = '#block-' . $block['id'];

				/* If the block is mirrored then change the selector */
					if ( $mirrored_block_id = HeadwayBlocksData::is_block_mirrored($block, true) )
						$selector = '#block-' . $mirrored_block_id . '.block-original-' . $block['id'];

				//If it's a fluid block (which blocks ARE by default), then we need to use min-height.  Otherwise, if it's fixed, we use height.
				if ( headway_get('fixed-height', headway_get($block['type'], $block_types), false) !== true )
					$return .= $selector . ' { min-height: ' . $block['dimensions']['height'] . 'px; }';
				else
					$return .= $selector . ' { height: ' . $block['dimensions']['height'] . 'px; }';

			}

			return $return;

		}

	static function wrapper() {

		$grid_number = HeadwayGrid::$columns;
		$column_width = HeadwayGrid::$column_width;
		$gutter_width = HeadwayGrid::$gutter_width;
		$grid_width = HeadwayGrid::get_grid_width();

		/* Fixed */
		$return = 'div.wrapper {
			width: ' . $grid_width . 'px;
		}';

		/* Responsive */
		if ( HeadwayResponsiveGrid::is_enabled() )
			$return .= 'div.wrapper.responsive-grid {
				width: auto;
				max-width: ' . $grid_width . 'px;
			}';

		return $return;

	}

	static function live_css() {

		if ( headway_get('visual-editor-open') )
			return null;

		return HeadwayOption::get('live-css');

	}

}


text:
        Polymer('x-foo', {
          fooish: true,
          domReady: function() {
            chai.assert.isTrue(this.firstElementChild.isBar, 'child is not upgraded');
            chai.assert.isTrue(this.previousElementSibling.isBar, 'sibling is not upgraded');
            chai.assert.isTrue(this.nextElementSibling.isBar, 'sibling is not upgraded');
            done();
          }
        });

redpajama_set_name: RedPajamaGithub


text:
#include "Common.h"
#include "BOSSManager.h"
#include "UnitUtil.h"

using namespace UAlbertaBot;

// get an instance of this
BOSSManager & BOSSManager::Instance()
{
	static BOSSManager instance;
	return instance;
}

// constructor
BOSSManager::BOSSManager()
	: _previousSearchStartFrame(0)
    , _previousSearchFinishFrame(0)
    , _searchInProgress(false)
    , _previousStatus("No Searches")
{

}

void BOSSManager::reset()
{
    _previousSearchResults = BOSS::DFBB_BuildOrderSearchResults();
    _searchInProgress = false;
    _previousBuildOrder.clear();
}

// start a new search for a new goal
void BOSSManager::startNewSearch(const std::vector<MetaPair> & goalUnits)
{
    size_t numWorkers   = UnitUtil::GetAllUnitCount(BWAPI::Broodwar->self()->getRace().getWorker());
    size_t numDepots    = UnitUtil::GetAllUnitCount(BWAPI::Broodwar->self()->getRace().getCenter())
                        + UnitUtil::GetAllUnitCount(BWAPI::UnitTypes::Zerg_Lair)
                        + UnitUtil::GetAllUnitCount(BWAPI::UnitTypes::Zerg_Hive);

    if (numWorkers == 0)
    {
        _previousStatus = "\x08No Workers :(";
        return;
    }

    if (numDepots == 0)
    {
        _previousStatus = "\x08No Depots :(";
        return;
    }

    // convert from UAlbertaBot's meta goal type to BOSS ActionType goal
    try
    {
        BOSS::BuildOrderSearchGoal goal = GetGoal(goalUnits);

        BOSS::GameState initialState(BWAPI::Broodwar, BWAPI::Broodwar->self(), BuildingManager::Instance().buildingsQueued());

        _smartSearch = SearchPtr(new BOSS::DFBB_BuildOrderSmartSearch(initialState.getRace()));
        _smartSearch->setGoal(GetGoal(goalUnits));
        _smartSearch->setState(initialState);

        _searchInProgress = true;
        _previousSearchStartFrame = BWAPI::Broodwar->getFrameCount();
        _totalPreviousSearchTime = 0;
        _previousGoalUnits = goalUnits;
    }
    catch (const BOSS::BOSSException)
    {
        BWAPI::BroodwarPtr->printf("Exception in BOSS::GameState constructor, will try again next frame");
    }
}

void BOSSManager::drawSearchInformation(int x, int y)
{
	if (!Config::Debug::DrawBuildOrderSearchInfo)
    {
        return;
    }

    // draw the background
    int width = 155;
    int height = 80;
    BWAPI::Broodwar->drawBoxScreen(BWAPI::Position(x-5,y), BWAPI::Position(x+width, y+height), BWAPI::Colors::Black, true);

    x += 5; y+=3;

    BWAPI::Broodwar->drawTextScreen(BWAPI::Position(x, y), "%cBuildOrderSearch:", '\x04');
    y += 10;
    BWAPI::Broodwar->drawTextScreen(BWAPI::Position(x, y), "%s", _previousStatus.c_str());

    for (size_t i(0); i < _previousGoalUnits.size(); ++i)
    {
        if (_previousGoalUnits[i].second > 0)
        {
            y += 10;
            BWAPI::Broodwar->drawTextScreen(BWAPI::Position(x,y), "%d %s", _previousGoalUnits[i].second, _previousGoalUnits[i].first.getName().c_str());
        }
    }

    BWAPI::Broodwar->drawTextScreen(BWAPI::Position(x, y+25), "Time (ms): %.3lf", _totalPreviousSearchTime);
    BWAPI::Broodwar->drawTextScreen(BWAPI::Position(x, y+35), "Nodes: %d", _savedSearchResults.nodesExpanded);
    BWAPI::Broodwar->drawTextScreen(BWAPI::Position(x, y+45), "BO Size: %d", (int)_savedSearchResults.buildOrder.size());
}

void BOSSManager::drawStateInformation(int x, int y)
{
	if (!Config::Debug::DrawBOSSStateInfo)
    {
        return;
    }

    BOSS::GameState currentState(BWAPI::Broodwar, BWAPI::Broodwar->self(), BuildingManager::Instance().buildingsQueued());
    BWAPI::Broodwar->drawTextScreen(BWAPI::Position(x-100, y+30), "\x04%s", currentState.getBuildingData().toString().c_str());
    BWAPI::Broodwar->drawTextScreen(BWAPI::Position(x+150, y), "\x04%s", currentState.toString().c_str());

}

// tell the search to keep going for however long we have this frame
void BOSSManager::update(double timeLimit)
{
    // if there's a search in progress, resume it
    if (isSearchInProgress())
    {
        _previousStatus.clear();

        // give the search at least 5ms to search this frame
        double realTimeLimit = timeLimit < 0 ? 5 : timeLimit;
        _smartSearch->setTimeLimit((int)realTimeLimit);
        bool caughtException = false;

		try
        {
            // call the search to continue searching
            // this will resume a search in progress or start a new search if not yet started
			_smartSearch->search();
		}
        // catch any errors that might happen in the search
		catch (const BOSS::BOSSException & exception)
        {
            UAB_ASSERT_WARNING(false, "BOSS SmartSearch Exception: %s", exception.what());
			BWAPI::Broodwar->drawTextScreen(0, 0, "Previous search didn't find a solution, resorting to Naive Build Order");
            _previousStatus = "BOSSExeption";
            caughtException = true;
		}

        _totalPreviousSearchTime += _smartSearch->getResults().timeElapsed;

        // after the search finishes for this frame, check to see if we have a solution or if we hit the overall time limit
        bool searchTimeOut = (BWAPI::Broodwar->getFrameCount() > (_previousSearchStartFrame + Config::Macro::BOSSFrameLimit));
        bool previousSearchComplete = searchTimeOut || _smartSearch->getResults().solved || caughtException;
        if (previousSearchComplete)
        {
            bool solved = _smartSearch->getResults().solved && _smartSearch->getResults().solutionFound;

            // if we've found a solution, let us know
            if (_smartSearch->getResults().solved && Config::Debug::DrawBuildOrderSearchInfo)
            {
                //BWAPI::Broodwar->printf("Build order SOLVED in %d nodes", (int)_smartSearch->getResults().nodesExpanded);
            }

            if (_smartSearch->getResults().solved)
            {
                if (_smartSearch->getResults().solutionFound)
                {
                    _previousStatus = std::string("\x07") + "BOSS Solve Solution\n";
                }
                else
                {
                    _previousStatus = std::string("\x03") + "BOSS Solve NoSolution\n";
                }
            }

            // re-set all the search information to get read for the next search
            _searchInProgress = false;
            _previousSearchFinishFrame = BWAPI::Broodwar->getFrameCount();
            _previousSearchResults = _smartSearch->getResults();
            _savedSearchResults = _previousSearchResults;
            _previousBuildOrder = _previousSearchResults.buildOrder;

            if (solved && _previousBuildOrder.size() == 0)
            {
                _previousStatus = std::string("\x07") + "BOSS Trivial Solve\n";
            }

            // if our search resulted in a build order of size 0 then something failed
            if (!solved && _previousBuildOrder.size() == 0)
            {
                // log the debug information since this shouldn't happen if everything goes to plan
                /*std::stringstream ss;
                ss << _smartSearch->getParameters().toString() << "\n";
                ss << "searchTimeOut: " << (searchTimeOut ? "true" : "false") << "\n";
                ss << "caughtException: " << (caughtException ? "true" : "false") << "\n";
                ss << "getResults().solved: " << (_smartSearch->getResults().solved ? "true" : "false") << "\n";
                ss << "getResults().solutionFound: " << (_smartSearch->getResults().solutionFound ? "true" : "false") << "\n";
                ss << "nodes: " << _savedSearchResults.nodesExpanded << "\n";
                ss << "time: " << _savedSearchResults.timeElapsed << "\n";
                Logger::LogOverwriteToFile("bwapi-data/AI/LastBadBuildOrder.txt", ss.str());*/

                // so try another naive build order search as a last resort
                BOSS::NaiveBuildOrderSearch nbos(_smartSearch->getParameters().initialState, _smartSearch->getParameters().goal);

				try
                {
                    if (searchTimeOut)
                    {
                        _previousStatus = std::string("\x02") + "BOSS Timeout\n";
                    }

                    if (caughtException)
                    {
                        _previousStatus = std::string("\x02") + "BOSS Exception\n";
                    }

					_previousBuildOrder = nbos.solve();
                    _previousStatus += "\x03NBOS Solution";

					return;
				}
                // and if that search doesn't work then we're out of luck, no build orders forus
				catch (const BOSS::BOSSException & exception)
                {
                    UAB_ASSERT_WARNING(false, "BOSS Timeout Naive Search Exception: %s", exception.what());
                    _previousStatus += "\x08Naive Exception";
                    if (Config::Debug::DrawBuildOrderSearchInfo)
                    {
					    BWAPI::Broodwar->drawTextScreen(0, 20, "No legal BuildOrder found, returning empty Build Order");
                    }
					_previousBuildOrder = BOSS::BuildOrder();
					return;
				}
            }
        }
    }
}

void BOSSManager::logBadSearch()
{
    std::string s = _smartSearch->getParameters().toString();

    Logger::LogOverwriteToFile("c:/uaberror.txt", s);
}

BOSS::BuildOrderSearchGoal BOSSManager::GetGoal(const std::vector<MetaPair> & goalUnits)
{
	BOSS::BuildOrderSearchGoal goal(BOSS::Races::GetRaceID(BWAPI::Broodwar->self()->getRace()));

	for (size_t i=0; i<goalUnits.size(); ++i)
	{
		goal.setGoal(GetActionType(goalUnits[i].first), goalUnits[i].second);
	}

	return goal;
}

// gets the StarcraftState corresponding to the beginning of a Melee game
BOSS::GameState BOSSManager::getStartState()
{
    BOSS::GameState state(getRace());
    state.setStartingState();

	return state;
}

const BOSS::RaceID BOSSManager::getRace() const
{
    BWAPI::Race r = BWAPI::Broodwar->self()->getRace();
    if (r == BWAPI::Races::Protoss)
    {
        return BOSS::Races::Protoss;
    }
    else if (r == BWAPI::Races::Terran)
    {
        return BOSS::Races::Terran;
    }
    else if (r == BWAPI::Races::Zerg)
    {
        return BOSS::Races::Zerg;
    }
    else
    {
        BOSS_ASSERT(false, "We should have had a valid race from BWAPI");
        return BOSS::Races::None;
    }
}

bool BOSSManager::isSearchInProgress()
{
    return _searchInProgress;
}

// converts SearchResults.buildOrder vector into vector of MetaType
std::vector<MetaType> BOSSManager::GetMetaVector(const BOSS::BuildOrder & buildOrder)
{
	std::vector<MetaType> metaVector;

	for (size_t i(0); i<buildOrder.size(); ++i)
	{
		metaVector.push_back(GetMetaType(buildOrder[i]));
	}

	return metaVector;
}

BuildOrder BOSSManager::getBuildOrder()
{
    return BuildOrder(BWAPI::Broodwar->self()->getRace(), GetMetaVector(_previousBuildOrder));
}

BOSS::ActionType BOSSManager::GetActionType(const MetaType & t)
{
	// set the appropriate type
	if (t.isUnit())
	{
		return BOSS::ActionType(t.getUnitType());
	}
	else if (t.isUpgrade())
	{
		return BOSS::ActionType(t.getUpgradeType());
	}
	else if (t.isTech())
	{
		return BOSS::ActionType(t.getTechType());
	}
	else
	{
		UAB_ASSERT(false, "Should have found a valid type here");
	}

	return BOSS::ActionType();
}

MetaType BOSSManager::GetMetaType(const BOSS::ActionType & a)
{
	// set the appropriate type
	if (a.isUnit())
	{
		return MetaType(a.getUnitType());
	}
	else if (a.isUpgrade())
	{
		return MetaType(a.getUpgradeType());
	}
	else if (a.isTech())
	{
		return MetaType(a.getTechType());
	}
	else
	{
		UAB_ASSERT(false, "Should have found a valid type here");
	}

	return MetaType();
}


text:
import os

import babel

from flask_babelex import Domain, get_locale
from flask_plugins import get_plugins_list

from flaskbb._compat import PY2

class FlaskBBDomain(Domain):
    def __init__(self, app):
        self.app = app
        super(FlaskBBDomain, self).__init__()

        self.plugins_folder = os.path.join(
            os.path.join(self.app.root_path, "plugins")
        )

        # FlaskBB's translations
        self.flaskbb_translations = os.path.join(
            self.app.root_path, "translations"
        )

        # Plugin translations
        with self.app.app_context():
            self.plugin_translations = [
                os.path.join(plugin.path, "translations")
                for plugin in get_plugins_list()
            ]

    def get_translations(self):
        """Returns the correct gettext translations that should be used for
        this request.  This will never fail and return a dummy translation
        object if used outside of the request or if a translation cannot be
        found.
        """
        locale = get_locale()
        cache = self.get_translations_cache()

        translations = cache.get(str(locale))
        if translations is None:
            # load flaskbb translations
            translations = babel.support.Translations.load(
                dirname=self.flaskbb_translations,
                locales=locale,
                domain="messages"
            )

            # If no compiled translations are found, return the
            # NullTranslations object.
            if not isinstance(translations, babel.support.Translations):
                return translations

            # Plugin translations are at the moment not supported under
            # Python 3. There is currently a bug in Babel where it is
            # not possible to merge two message catalogs.
            # https://github.com/mitsuhiko/babel/pull/92
            # So instead of adding/merging them, we are just skipping them
            # Better then no python3 support though..
            if not PY2:
                return translations

            # now load and add the plugin translations
            for plugin in self.plugin_translations:
                plugin_translation = babel.support.Translations.load(
                    dirname=plugin,
                    locales=locale,
                    domain="messages"
                )
                translations.add(plugin_translation)

            cache[str(locale)] = translations

        return translations


text:
namespace abb {
namespace ll {

template<typename Range>
class range_generator : utils::noncopyable {
private:
    typedef decltype(utils::begin(std::declval<Range&>())) iterator;
    typedef decltype(*std::declval<iterator>()) value_type;

public:
    explicit range_generator(Range && range):
        range(std::forward<Range>(range)),
        it(utils::begin(this->range)),
        end(utils::end(this->range)) {}

    explicit range_generator(Range const& range):
        range(range),
        it(utils::begin(this->range)),
        end(utils::end(this->range)) {}

    explicit operator bool() const {
        return this->it != this->end;
    }

    value_type operator()() {
        value_type elem = *this->it;
        ++this->it;
        return std::forward<value_type>(elem);
    }

private:
    Range range;
    iterator it;
    iterator end;
};

template<typename Iterator>
class iterator_generator {
private:
    typedef decltype(*std::declval<Iterator>()) value_type;

public:
    iterator_generator(Iterator begin, Iterator end):
        it(begin),
        end(end) {}

    explicit operator bool() const {
        return this->it != this->end;
    }

    value_type operator()() {
        value_type elem = *this->it;
        ++this->it;
        return std::forward<value_type>(elem);
    }

private:
    Iterator it;
    Iterator end;
};

template<typename Generator, typename Func>
class map_generator {
private:
    box<Generator> wrapped;
    box<Func> func;

public:
    template<typename GeneratorArg, typename FuncArg>
    map_generator(GeneratorArg && wrapped, FuncArg && func):
        wrapped(box_arg, std::forward<GeneratorArg>(wrapped)),
        func(box_arg, std::forward<FuncArg>(func)) {}

    explicit operator bool() const {
        return bool(*this->wrapped);
    }

    auto operator()() -> decltype((*this->func)((*this->wrapped)())) {
        return (*this->func)((*this->wrapped)());
    }
};

namespace internal {

template<typename EachBrick>
class each_child : private successor, public utils::cord_node {
private:
    typedef get_brick_ptr_t<EachBrick> brick_ptr_type;

public:
    each_child(brick_ptr_type in_brick, EachBrick * parent):
        in_brick(std::move(in_brick)),
        parent(parent) {}

private:
    virtual void on_update();

    brick_ptr_type in_brick;
    EachBrick * parent;

    friend EachBrick;
};

template<typename EachBrick>
void each_child<EachBrick>::on_update() {
    EachBrick * parent = this->parent;
    status parent_status = parent->update_child(this);
    if (parent_status != status::running) {
        parent->succ->on_update();
    }
}

} // namespace internal

template<typename Generator>
class each_brick : public brick<void(), typename decltype(std::declval<Generator>()())::reason> {
public:
    typedef void result();
    typedef typename decltype(std::declval<Generator>()())::reason reason;

private:
    typedef internal::each_child<each_brick<Generator>> each_child_type;
    typedef brick_ptr<result, reason> brick_ptr_type;
public:
    template<typename GeneratorArg>
    each_brick(GeneratorArg && arg, std::size_t limit):
        generator(box_arg, std::forward<GeneratorArg>(arg)),
        limit(limit),
        target(nullptr),
        aborted(false),
        succ(nullptr) {}

    void start(island & target, bool aborted, successor & succ) {
        this->target = ⌖
        this->aborted = aborted;
        this->succ = ≻
        if (!*this->generator) {
            this->out_brick = make_brick<success_brick<void()>>();
            return;
        }

        for (std::size_t limit = this->limit; *this->generator && limit; --limit) {
            this->children.insert(new each_child_type((*this->generator)(), this));
        }

        for (each_child_type * child : utils::firewalk(this->children)) {
            this->update_child(child);
        }
    }

    void adopt(successor & succ) {
        this->succ = ≻
    }

    status get_status() const {
        if (this->out_brick && this->children.empty()) {
            return status::next;
        } else if (this->succ) {
            return status::running;
        } else {
            return status::startable;
        }
    }

    brick_ptr_type get_next() {
        return std::move(this->out_brick);
    }

    void abort() {
        // TODO implement
    }

private:
    status update_child(each_child_type * child);

    box<Generator> generator;
    std::size_t limit;
    utils::cord_list<each_child_type> children;
    island * target;
    bool aborted;
    successor * succ;
    brick_ptr_type out_brick;

    friend each_child_type;
};

template<typename Generator>
status each_brick<Generator>::update_child(each_child_type * child) {
    for (;;) {
        status in_status = child->in_brick.update(*this->target, this->aborted, *child);
        if (in_status == status::success && *this->generator) { // TODO stop if out_brick is set
            child->in_brick = (*this->generator)();
        } else {
            brick_ptr_type in_brick = std::move(child->in_brick);
            child->cord_detach();
            delete child;

            if (in_status == status::success) {
                if (this->children.empty()) {
                    if (!this->out_brick) {
                        this->out_brick = std::move(in_brick);
                    }
                    return status::next;
                }
            } else {
                if (!this->out_brick) {
                    this->out_brick = std::move(in_brick);
                    // TODO issue abort
                }
                if (this->children.empty()) {
                    return status::next;
                }
            }
            return status::running;
        }
    }
}

} // namespace ll
} // namespace abb

#endif // ABB_LL_EACH_BRICK_H


text:
package org.apereo.cas.config;

import org.apereo.cas.configuration.CasConfigurationProperties;
import org.apereo.cas.cosmosdb.CosmosDbObjectFactory;
import org.apereo.cas.services.CosmosDbServiceRegistry;
import org.apereo.cas.services.ServiceRegistry;
import org.apereo.cas.services.ServiceRegistryExecutionPlan;
import org.apereo.cas.services.ServiceRegistryExecutionPlanConfigurer;

import com.microsoft.azure.documentdb.ConsistencyLevel;
import com.microsoft.azure.documentdb.IndexingMode;
import com.microsoft.azure.documentdb.IndexingPolicy;
import com.microsoft.azure.documentdb.RequestOptions;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * This is {@link CosmosDbServiceRegistryConfiguration}.
 *
 * @author Misagh Moayyed
 * @since 5.2.0
 */
@Configuration("cosmosDbServiceRegistryConfiguration")
@EnableConfigurationProperties(CasConfigurationProperties.class)
@Slf4j
public class CosmosDbServiceRegistryConfiguration implements ServiceRegistryExecutionPlanConfigurer {
    /**
     * Partition key field name.
     */
    private static final String PARTITION_KEY_FIELD_NAME = "partitionKey";

    @Autowired
    private CasConfigurationProperties casProperties;

    @Autowired
    private ApplicationContext applicationContext;

    @Bean
    @RefreshScope
    public ServiceRegistry cosmosDbServiceRegistry() {
        val factory = new CosmosDbObjectFactory(this.applicationContext);
        val cosmosDb = casProperties.getServiceRegistry().getCosmosDb();
        val dbFactory = factory.createDocumentDbFactory(cosmosDb);
        val db = factory.createDocumentDbTemplate(dbFactory, cosmosDb);

        if (cosmosDb.isDropCollection()) {
            val collectionLink = CosmosDbObjectFactory.getCollectionLink(cosmosDb.getDatabase(), cosmosDb.getCollection());
            val options = new RequestOptions();
            options.setConsistencyLevel(ConsistencyLevel.valueOf(cosmosDb.getConsistencyLevel()));
            options.setOfferThroughput(cosmosDb.getThroughput());
            try {
                dbFactory.getDocumentClient().deleteCollection(collectionLink, options);
            } catch (final Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
        val indexingPolicy = new IndexingPolicy();
        indexingPolicy.setAutomatic(true);
        indexingPolicy.setIndexingMode(IndexingMode.valueOf(cosmosDb.getIndexingMode()));
        db.createCollectionIfNotExists(cosmosDb.getCollection(), PARTITION_KEY_FIELD_NAME,
            cosmosDb.getThroughput(), indexingPolicy);
        return new CosmosDbServiceRegistry(db, dbFactory, cosmosDb.getCollection(), cosmosDb.getDatabase());
    }

    @Override
    public void configureServiceRegistry(final ServiceRegistryExecutionPlan plan) {
        plan.registerServiceRegistry(cosmosDbServiceRegistry());
    }
}


text:
package oshi.software.os.mac;

import static oshi.software.os.OSService.State.RUNNING;
import static oshi.software.os.OSService.State.STOPPED;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sun.jna.platform.mac.SystemB;

import oshi.annotation.concurrent.ThreadSafe;
import oshi.driver.mac.Who;
import oshi.driver.mac.WindowInfo;
import oshi.jna.Struct.CloseableProcTaskInfo;
import oshi.jna.Struct.CloseableTimeval;
import oshi.software.common.AbstractOperatingSystem;
import oshi.software.os.FileSystem;
import oshi.software.os.InternetProtocolStats;
import oshi.software.os.NetworkParams;
import oshi.software.os.OSDesktopWindow;
import oshi.software.os.OSProcess;
import oshi.software.os.OSProcess.State;
import oshi.software.os.OSService;
import oshi.software.os.OSSession;
import oshi.util.ExecutingCommand;
import oshi.util.FileUtil;
import oshi.util.ParseUtil;
import oshi.util.Util;
import oshi.util.platform.mac.SysctlUtil;
import oshi.util.tuples.Pair;

/**
 * macOS, previously Mac OS X and later OS X) is a series of proprietary graphical operating systems developed and
 * marketed by Apple Inc. since 2001. It is the primary operating system for Apple's Mac computers.
 */
@ThreadSafe
public class MacOperatingSystem extends AbstractOperatingSystem {

    private static final Logger LOG = LoggerFactory.getLogger(MacOperatingSystem.class);

    public static final String MACOS_VERSIONS_PROPERTIES = "oshi.macos.versions.properties";

    private static final String SYSTEM_LIBRARY_LAUNCH_AGENTS = "/System/Library/LaunchAgents";
    private static final String SYSTEM_LIBRARY_LAUNCH_DAEMONS = "/System/Library/LaunchDaemons";

    private int maxProc = 1024;

    private final String osXVersion;
    private final int major;
    private final int minor;

    private static final long BOOTTIME;
    static {
        try (CloseableTimeval tv = new CloseableTimeval()) {
            if (!SysctlUtil.sysctl("kern.boottime", tv) || tv.tv_sec.longValue() == 0L) {
                // Usually this works. If it doesn't, fall back to text parsing.
                // Boot time will be the first consecutive string of digits.
                BOOTTIME = ParseUtil.parseLongOrDefault(
                        ExecutingCommand.getFirstAnswer("sysctl -n kern.boottime").split(",")[0].replaceAll("\\D", ""),
                        System.currentTimeMillis() / 1000);
            } else {
                // tv now points to a 64-bit timeval structure for boot time.
                // First 4 bytes are seconds, second 4 bytes are microseconds
                // (we ignore)
                BOOTTIME = tv.tv_sec.longValue();
            }
        }
    }

    public MacOperatingSystem() {
        String version = System.getProperty("os.version");
        int verMajor = ParseUtil.getFirstIntValue(version);
        int verMinor = ParseUtil.getNthIntValue(version, 2);
        // Big Sur (11.x) may return 10.16
        if (verMajor == 10 && verMinor > 15) {
            String swVers = ExecutingCommand.getFirstAnswer("sw_vers -productVersion");
            if (!swVers.isEmpty()) {
                version = swVers;
            }
            verMajor = ParseUtil.getFirstIntValue(version);
            verMinor = ParseUtil.getNthIntValue(version, 2);
        }
        this.osXVersion = version;
        this.major = verMajor;
        this.minor = verMinor;
        // Set max processes
        this.maxProc = SysctlUtil.sysctl("kern.maxproc", 0x1000);
    }

    @Override
    public String queryManufacturer() {
        return "Apple";
    }

    @Override
    public Pair<String, OSVersionInfo> queryFamilyVersionInfo() {
        String family = this.major > 10 || (this.major == 10 && this.minor >= 12) ? "macOS"
                : System.getProperty("os.name");
        String codeName = parseCodeName();
        String buildNumber = SysctlUtil.sysctl("kern.osversion", "");
        return new Pair<>(family, new OSVersionInfo(this.osXVersion, codeName, buildNumber));
    }

    private String parseCodeName() {
        Properties verProps = FileUtil.readPropertiesFromFilename(MACOS_VERSIONS_PROPERTIES);
        String codeName = null;
        if (this.major > 10) {
            codeName = verProps.getProperty(Integer.toString(this.major));
        } else if (this.major == 10) {
            codeName = verProps.getProperty(this.major + "." + this.minor);
        }
        if (Util.isBlank(codeName)) {
            LOG.warn("Unable to parse version {}.{} to a codename.", this.major, this.minor);
        }
        return codeName;
    }

    @Override
    protected int queryBitness(int jvmBitness) {
        if (jvmBitness == 64 || (this.major == 10 && this.minor > 6)) {
            return 64;
        }
        return ParseUtil.parseIntOrDefault(ExecutingCommand.getFirstAnswer("getconf LONG_BIT"), 32);
    }

    @Override
    public FileSystem getFileSystem() {
        return new MacFileSystem();
    }

    @Override
    public InternetProtocolStats getInternetProtocolStats() {
        return new MacInternetProtocolStats(isElevated());
    }

    @Override
    public List<OSSession> getSessions() {
        return USE_WHO_COMMAND ? super.getSessions() : Who.queryUtxent();
    }

    @Override
    public List<OSProcess> queryAllProcesses() {
        List<OSProcess> procs = new ArrayList<>();
        int[] pids = new int[this.maxProc];
        Arrays.fill(pids, -1);
        int numberOfProcesses = SystemB.INSTANCE.proc_listpids(SystemB.PROC_ALL_PIDS, 0, pids,
                pids.length * SystemB.INT_SIZE) / SystemB.INT_SIZE;
        for (int i = 0; i < numberOfProcesses; i++) {
            if (pids[i] >= 0) {
                OSProcess proc = getProcess(pids[i]);
                if (proc != null) {
                    procs.add(proc);
                }
            }
        }
        return procs;
    }

    @Override
    public OSProcess getProcess(int pid) {
        OSProcess proc = new MacOSProcess(pid, this.major, this.minor, this);
        return proc.getState().equals(State.INVALID) ? null : proc;
    }

    @Override
    public List<OSProcess> queryChildProcesses(int parentPid) {
        List<OSProcess> allProcs = queryAllProcesses();
        Set<Integer> descendantPids = getChildrenOrDescendants(allProcs, parentPid, false);
        return allProcs.stream().filter(p -> descendantPids.contains(p.getProcessID())).collect(Collectors.toList());
    }

    @Override
    public List<OSProcess> queryDescendantProcesses(int parentPid) {
        List<OSProcess> allProcs = queryAllProcesses();
        Set<Integer> descendantPids = getChildrenOrDescendants(allProcs, parentPid, true);
        return allProcs.stream().filter(p -> descendantPids.contains(p.getProcessID())).collect(Collectors.toList());
    }

    @Override
    public int getProcessId() {
        return SystemB.INSTANCE.getpid();
    }

    @Override
    public int getProcessCount() {
        return SystemB.INSTANCE.proc_listpids(SystemB.PROC_ALL_PIDS, 0, null, 0) / SystemB.INT_SIZE;
    }

    @Override
    public int getThreadCount() {
        // Get current pids, then slightly pad in case new process starts while
        // allocating array space
        int[] pids = new int[getProcessCount() + 10];
        int numberOfProcesses = SystemB.INSTANCE.proc_listpids(SystemB.PROC_ALL_PIDS, 0, pids, pids.length)
                / SystemB.INT_SIZE;
        int numberOfThreads = 0;
        try (CloseableProcTaskInfo taskInfo = new CloseableProcTaskInfo()) {
            for (int i = 0; i < numberOfProcesses; i++) {
                int exit = SystemB.INSTANCE.proc_pidinfo(pids[i], SystemB.PROC_PIDTASKINFO, 0, taskInfo,
                        taskInfo.size());
                if (exit != -1) {
                    numberOfThreads += taskInfo.pti_threadnum;
                }
            }
        }
        return numberOfThreads;
    }

    @Override
    public long getSystemUptime() {
        return System.currentTimeMillis() / 1000 - BOOTTIME;
    }

    @Override
    public long getSystemBootTime() {
        return BOOTTIME;
    }

    @Override
    public NetworkParams getNetworkParams() {
        return new MacNetworkParams();
    }

    @Override
    public List<OSService> getServices() {
        // Get running services
        List<OSService> services = new ArrayList<>();
        Set<String> running = new HashSet<>();
        for (OSProcess p : getChildProcesses(1, ProcessFiltering.ALL_PROCESSES, ProcessSorting.PID_ASC, 0)) {
            OSService s = new OSService(p.getName(), p.getProcessID(), RUNNING);
            services.add(s);
            running.add(p.getName());
        }
        // Get Directories for stopped services
        ArrayList<File> files = new ArrayList<>();
        File dir = new File(SYSTEM_LIBRARY_LAUNCH_AGENTS);
        if (dir.exists() && dir.isDirectory()) {
            files.addAll(Arrays.asList(dir.listFiles((f, name) -> name.toLowerCase().endsWith(".plist"))));
        } else {
            LOG.error("Directory: /System/Library/LaunchAgents does not exist");
        }
        dir = new File(SYSTEM_LIBRARY_LAUNCH_DAEMONS);
        if (dir.exists() && dir.isDirectory()) {
            files.addAll(Arrays.asList(dir.listFiles((f, name) -> name.toLowerCase().endsWith(".plist"))));
        } else {
            LOG.error("Directory: /System/Library/LaunchDaemons does not exist");
        }
        for (File f : files) {
            // remove .plist extension
            String name = f.getName().substring(0, f.getName().length() - 6);
            int index = name.lastIndexOf('.');
            String shortName = (index < 0 || index > name.length() - 2) ? name : name.substring(index + 1);
            if (!running.contains(name) && !running.contains(shortName)) {
                OSService s = new OSService(name, 0, STOPPED);
                services.add(s);
            }
        }
        return services;
    }

    @Override
    public List<OSDesktopWindow> getDesktopWindows(boolean visibleOnly) {
        return WindowInfo.queryDesktopWindows(visibleOnly);
    }
}


text:
package com.googlecode.gmail4j;

/**
 * A class that represents email address, i.e. "John Smith
 * <j.smith@example.com>"
 *

 * Example #1:
 *

 *     EmailAddress tomas = new EmailAddress("Tomas", "tomas.varaneckas@gmail.com");
 *
 *     //Tomas
 *     String name = tomas.getName();
 *
 *     //tomas.varaneckas@gmail.com
 *     String email = tomas.getEmail();
 *
 *     //Tomas <tomas.varaneckas@gmail.com>
 *     String full = tomas.toString();
 *

 * Example #2:
 *

 *     EmailAddress john = new EmailAddress("j.smith@example.com");
 *
 *     //j.smith
 *     String name = john.getName();
 *
 *     //j.smith@example.com
 *     String email = john.getEmail();
 *
 *     //j.smith@example.com
 *     String full = tomas.toString();
 *

 *
 * @author Tomas Varaneckas <tomas.varaneckas@gmail.com>
 * @since 0.1
 */
public class EmailAddress {

    /**
     * Email address
     */
    private final String email;

    /**
     * Email owner's name
     */
    private String name;

    /**
     * Constructor with Email address
     *
     * @param email Email address
     */
    public EmailAddress(final String email) {
        this(null, email);
    }

    /**
     * Constructor with Person name and email address
     *
     * @param name Person name
     * @param email Email address
     */
    public EmailAddress(final String name, final String email) {
        if (name != null && name.length() > 0) {
            this.name = name;
        }
        this.email = email;
    }

    /**
     * Tells if this email address has a defined person name
     *
     * @return true if name exists
     * @since 0.3
     */
    public boolean hasName() {
        return name != null && name.length() > 0;
    }

    /**
     * Gets person {@link #name} or first part of email address if name is not
     * set
     *
     * @return name or first part of email address
     */
    public String getName() {
        return name == null ? email.replaceFirst("@.*", "") : name;
    }

    /**
     * Gets Email address
     *
     * @return {@link #email}
     */
    public String getEmail() {
        return email;
    }

    @Override
    public String toString() {
        return name == null ? email : name.concat(" <").concat(email).concat(">");
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Owin.Hosting;

namespace WebApiService
{
	class Program
	{
		static void Main(string[] args)
		{
			var baseAddress = "http://localhost:8000";
			using (WebApp.Start<Startup>(url: baseAddress))
			{
				Console.WriteLine("Press Enter key to stop the server...");
				Console.ReadLine();
			}
		}
	}
}


text:
// DataGridView Column Types for Drop-Down Controls
// Bradley Smith - 2015/4/14

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Windows.Forms.VisualStyles;
using System.Globalization;
using System.ComponentModel;

namespace DropDownControls {

	/// <summary>
	/// Base class for custom <see cref="DataGridView"/> column types.
	/// </summary>
	[ToolboxBitmapAttribute(typeof(DataGridViewComboBoxColumn), "DataGridViewComboBoxColumn.bmp")]
	public abstract class DropDownColumnBase : DataGridViewColumn {

		/// <summary>
		/// Gets a value indicating whether buffered painting is supported.
		/// Used when rendering cells.
		/// </summary>
		internal bool BufferedPaintingSupported { get; private set; }

		/// <summary>
		/// Constructor.
		/// </summary>
		protected DropDownColumnBase() {
			BufferedPaintingSupported = BufferedPainting.BufferedPainter<ComboBoxState>.IsSupported();
		}
	}

	/// <summary>
	/// Base class for custom <see cref="DataGridView"/> cell types.
	/// </summary>
	public abstract class DropDownCellBase : DataGridViewCell {

		private bool _wasCurrentCell;

		/// <summary>
		/// Paints common elements behind the cell content.
		/// </summary>
		/// <param name="graphics"></param>
		/// <param name="cellBounds"></param>
		/// <param name="cellState"></param>
		/// <param name="cellStyle"></param>
		/// <param name="paintParts"></param>
		protected void BeforePaintContent(Graphics graphics, Rectangle cellBounds, DataGridViewElementStates cellState, DataGridViewCellStyle cellStyle, DataGridViewPaintParts paintParts) {
			if (paintParts.HasFlag(DataGridViewPaintParts.Background)) {
				using (Brush brush = new SolidBrush(cellStyle.BackColor)) {
					graphics.FillRectangle(brush, cellBounds);
				}
			}

			if (paintParts.HasFlag(DataGridViewPaintParts.SelectionBackground) && cellState.HasFlag(DataGridViewElementStates.Selected)) {
				using (Brush brush = new SolidBrush(cellStyle.SelectionBackColor)) {
					graphics.FillRectangle(brush, cellBounds);
				}
			}

			if (paintParts.HasFlag(DataGridViewPaintParts.ContentBackground)) {
				ComboBoxState state = ComboBoxState.Normal;
				ButtonState legacyState = ButtonState.Normal;

				if ((DataGridView.Site == null) || !DataGridView.Site.DesignMode) {
					if (cellState.HasFlag(DataGridViewElementStates.ReadOnly)) {
						state = ComboBoxState.Disabled;
						legacyState = ButtonState.Inactive;
					}
					else if (cellBounds.Contains(DataGridView.PointToClient(DataGridView.MousePosition))) {
						if (DataGridView.MouseButtons.HasFlag(MouseButtons.Left)) {
							state = ComboBoxState.Pressed;
							legacyState = ButtonState.Pushed;
						}
						else {
							state = ComboBoxState.Hot;
						}
					}
				}

				Rectangle comboBounds = cellBounds;
				comboBounds.Width--;

				if (((DropDownColumnBase)OwningColumn).BufferedPaintingSupported) {
					GroupedComboBox.DrawComboBox(graphics, comboBounds, state);
				}
				else {
					DropDownControlBase.DrawLegacyComboBox(graphics, comboBounds, DropDownControlBase.GetComboButtonBounds(comboBounds), cellStyle.BackColor, legacyState);
				}
			}
		}

		/// <summary>
		/// Paints common elements in front of the cell content.
		/// </summary>
		/// <param name="graphics"></param>
		/// <param name="clipBounds"></param>
		/// <param name="cellBounds"></param>
		/// <param name="rowIndex"></param>
		/// <param name="cellStyle"></param>
		/// <param name="advancedBorderStyle"></param>
		/// <param name="paintParts"></param>
		protected void AfterPaintContent(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) {
			if (paintParts.HasFlag(DataGridViewPaintParts.ErrorIcon)) {
				base.PaintErrorIcon(graphics, clipBounds, cellBounds, GetErrorText(rowIndex));
			}

			if (paintParts.HasFlag(DataGridViewPaintParts.Border)) {
				base.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle);
			}

			if (paintParts.HasFlag(DataGridViewPaintParts.Focus) && (DataGridView.CurrentCell == this)) {
				Rectangle focusBounds = cellBounds;
				focusBounds.Width--;
				focusBounds.Height--;
				ControlPaint.DrawFocusRectangle(graphics, focusBounds);
			}
		}

		protected override void OnMouseEnter(int rowIndex) {
			base.OnMouseEnter(rowIndex);
			DataGridView.InvalidateCell(OwningColumn.Index, rowIndex);
		}

		protected override void OnMouseLeave(int rowIndex) {
			base.OnMouseLeave(rowIndex);
			DataGridView.InvalidateCell(OwningColumn.Index, rowIndex);
		}

		protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) {
			_wasCurrentCell = (DataGridView.CurrentCellAddress == new Point(e.ColumnIndex, e.RowIndex));
			base.OnMouseDown(e);
			DataGridView.InvalidateCell(e.ColumnIndex, e.RowIndex);
		}

		protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) {
			base.OnMouseUp(e);
			DataGridView.InvalidateCell(e.ColumnIndex, e.RowIndex);
		}

		protected override void OnMouseClick(DataGridViewCellMouseEventArgs e) {
			if (!ReadOnly && _wasCurrentCell) DataGridView.BeginEdit(true);
			base.OnMouseClick(e);
		}
	}
}


text:
  Skip to main content
  Skip to toolbar

Dashboard

Dashboard

Home

            Updates
              1

Posts

Posts

All Posts

Add New

Categories

Tags

Media

Media

Library

Add New

Pages

Pages

All Pages

Add New

Comments 0

Appearance

Appearance

Themes

Customize

Widgets

Menus

Header

Header

Editor

Plugins 1

Plugins 1

Installed Plugins

Add New

Editor

Users

Users

All Users

Add New

Your Profile

Tools

Tools

Available Tools

Import

Export

Settings

Settings

General

Writing

Reading

Discussion

Media

Permalinks

        <button type="button" id="collapse-button">Collapse menu</button>


text:
node-ffi
========
### Node.js Foreign Function Interface [![Build Status](https://secure.travis-ci.org/rbranson/node-ffi.png)](http://travis-ci.org/rbranson/node-ffi)

`node-ffi` is a Node.js addon for loading and calling dynamic libraries using
pure JavaScript. It can be used to create bindings to native libraries without
writing any C++ code.

It also simplifies the augmentation of node.js with C code as it takes care of
handling the translation of types across JavaScript and C, which can add reams
of boilerplate code to your otherwise simple C. See the `example/factorial`
for an example of this use case.

**WARNING**: node-ffi assumes you know what you're doing. You can pretty easily
create situations where you will segfault the interpreter and unless you've got
C debugger skills, you probably won't know what's going on.

Example
-------

``` js
var ffi = require('ffi');

var libm = ffi.Library('libm', {
  'ceil': [ 'double', [ 'double' ] ]
});
libm.ceil(1.5); // 2

// You can also access just functions in the current process by passing a null
var current = ffi.Library(null, {
  'atoi': [ 'int', [ 'string' ] ]
});
current.atoi('1234'); // 1234
```

For a more detailed introduction, see the [node-ffi tutorial page][tutorial].

Requirements
------------

 * Linux, OS X, Windows, or Solaris.
 * `libffi` comes bundled with node-ffi; it does *not* need to be installed on your system.
 * The current version is tested to run on node v0.6, v0.7, and v0.8.

Installation
------------

Make sure you've installed all the [necessary build
tools](https://github.com/TooTallNate/node-gyp#installation) for your platform,
then invoke:

``` bash
$ npm install ffi
```

Source Install / Manual Compilation
-----------------------------------

To compile from source it's easiest to use
[`node-gyp`](https://github.com/TooTallNate/node-gyp):

``` bash
$ npm install -g node-gyp
```

Now you can compile `node-ffi`:

``` bash
$ git clone git://github.com/rbranson/node-ffi.git
$ cd node-ffi
$ node-gyp rebuild
```

Types
-----

The types that you specify in function declarations correspond to ref's types
system. So [see its docs][ref-types] for
a reference if you are unfamiliar.

V8 and 64-bit Types
-------------------

Internally, V8 stores integers that will fit into a 32-bit space in a 32-bit
integer, and those that fall outside of this get put into double-precision
floating point numbers. This is problematic because FP numbers are imprecise.
To get around this, the methods in node-ffi that deal with 64-bit integers return
strings and can accept strings as parameters.

Call Overhead
-------------

There is non-trivial overhead associated with FFI calls. Comparing a hard-coded
binding version of `strtoul()` to an FFI version of `strtoul()` shows that the
native hard-coded binding is orders of magnitude faster. So don't just use the
C version of a function just because it's faster. There's a significant cost in
FFI calls, so make them worth it.

License
-------

MIT License. See the `LICENSE` file.

[v1apichanges]: https://github.com/rbranson/node-ffi/wiki/API-changes-from-v0.x-to-v1.x
[tutorial]: https://github.com/rbranson/node-ffi/wiki/Node-FFI-Tutorial
[ref-types]: https://github.com/TooTallNate/ref#built-in-types


text:
package org.limeprotocol.client;

import org.limeprotocol.*;
import org.limeprotocol.network.Channel;
import org.limeprotocol.security.Authentication;

import java.io.IOException;

/**
 * Defines the communication channel between a client node and a server.
 */
public interface ClientChannel extends Channel {

    /**
     * Sends a new session envelope to the server and listen for the response.
     * @param sessionListener
     */
    void startNewSession(SessionChannelListener sessionListener) throws IOException;

    /**
     * Sends a negotiate session envelope to accepts the session negotiation options
     * and listen for the server confirmation.
     * @param sessionCompression
     * @param sessionEncryption
     * @param sessionListener
     */
    void negotiateSession(SessionCompression sessionCompression, SessionEncryption sessionEncryption, SessionChannelListener sessionListener) throws IOException;

    /**
     * Sends a authenticate session envelope to the server to establish an authenticated session
     * and listen for the established session envelope.
     * @param identity
     * @param authentication
     * @param instance
     * @param sessionListener
     */
    void authenticateSession(Identity identity, Authentication authentication, String instance, SessionChannelListener sessionListener) throws IOException;

    /**
     *  Notify to the server that the specified message was received by the peer.
     * @param messageId
     * @param to
     */
    void sendReceivedNotification(String messageId, Node to) throws IOException;

    /**
     * Sends a finishing session envelope to the server.
     */
    void sendFinishingSession() throws IOException;

    /**
     * Performs the session negotiation and authentication
     * @param compression Chosen compression, or null for the first one supported by the server
     * @param encryption Chosen encryption, or null for the first one supported by the server
     * @param identity
     * @param authentication
     */
    void establishSession(SessionCompression compression, SessionEncryption encryption,
                                  Identity identity, Authentication authentication, String instance,
                                  EstablishSessionListener listener)
            throws IOException;

    /**
     * Defines listener for session establishment
     */
    public interface EstablishSessionListener extends SessionChannelListener {
        /**
         * Occurs if there is any unexpected failure during session establishment
         * @param exception
         */
        void onFailure(Exception exception);
    }
}


text:
<?php
/* @var $panel JavascriptPanel */

use bedezign\yii2\audit\models\AuditJavascript;
use bedezign\yii2\audit\panels\JavascriptPanel;
use dosamigos\chartjs\ChartJs;

//initialise defaults (0 entries) for each day
$defaults = [];
$startDate = strtotime('-6 days');
foreach (range(-6, 0) as $day) {
    $defaults[date('D: Y-m-d', strtotime($day . 'days'))] = 0;
}

$results = AuditJavascript::find()
    ->select(["COUNT(DISTINCT id) as count", "created AS day"])
    ->where(['between', 'created',
        date('Y-m-d 00:00:00', $startDate),
        date('Y-m-d 23:59:59')])
    ->groupBy("day")->indexBy('day')->column();

// format dates properly
$formattedData = [];
foreach ($results as $date => $count) {
    $date = date('D: Y-m-d', strtotime($date));
    $formattedData[$date] = $count;
}
$results = $formattedData;

// replace defaults with data from db where available
$results = array_merge($defaults, $results);

echo ChartJs::widget([
    'type' => 'bar',
    'clientOptions' => [
        'legend' => ['display' => false],
        'tooltips' => ['enabled' => false],
    ],
    'data' => [
        'labels' => array_keys($results),
        'datasets' => [
            [
                'fillColor' => 'rgba(151,187,205,0.5)',
                'strokeColor' => 'rgba(151,187,205,1)',
                'pointColor' => 'rgba(151,187,205,1)',
                'pointStrokeColor' => '#fff',
                'data' => array_keys($results),
            ],
        ],
    ]
]);


text:
<?php

namespace Doctrine\DBAL\Exception;

/**
 * Exception for a write operation attempt on a read-only database element detected in the driver.
 */
class ReadOnlyException extends ServerException
{
}


text:
znseaman.github.io
==================

A site for my thoughts and projects.

### Colophon

Uses [Tinkerer](http://tinkerer.me/), a blogging platform for Pythonistas.


text:
package http

import (
	"encoding/json"
	"net/http"
	_ "net/http/pprof"

	"github.com/Cepave/open-falcon-backend/modules/judge/g"
	log "github.com/sirupsen/logrus"
)

type Dto struct {
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func init() {
	configCommonRoutes()
	configInfoRoutes()
}

func RenderJson(w http.ResponseWriter, v interface{}) {
	bs, err := json.Marshal(v)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.Write(bs)
}

func RenderDataJson(w http.ResponseWriter, data interface{}) {
	RenderJson(w, Dto{Msg: "success", Data: data})
}

func RenderMsgJson(w http.ResponseWriter, msg string) {
	RenderJson(w, map[string]string{"msg": msg})
}

func AutoRender(w http.ResponseWriter, data interface{}, err error) {
	if err != nil {
		RenderMsgJson(w, err.Error())
		return
	}
	RenderDataJson(w, data)
}

func Start(pid chan string) {

	defer func() {
		if r := recover(); r != nil {
			log.Errorf("run time panic: %v", r)
			pid <- "http"
			return
		}
	}()

	if !g.Config().Http.Enabled {
		return
	}

	addr := g.Config().Http.Listen
	if addr == "" {
		return
	}
	s := &http.Server{
		Addr:           addr,
		MaxHeaderBytes: 1 << 30,
	}
	log.Println("http listening", addr)
	log.Fatalln(s.ListenAndServe())
}


text:
(function(){
  'use strict';

  var beerSearch = angular.module('getCrafty.beerSearch', []);

  beerSearch.config(function($stateProvider) {
      $stateProvider.state('beerSearch', {
        url: '/beer/',
        templateUrl: 'beer-search/beer-search.html',
        controller: 'beerSearchCtrl',
      });
  });

  beerSearch.controller('beerSearchCtrl', function($scope, $route, $routeParams, $http) {

  });
})();


text:
<!DOCTYPE html>
<!--
Copyright 2017 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/multi_dimensional_view.html">
<link rel="import" href="/tracing/extras/chrome/chrome_processes.html">
<link rel="import" href="/tracing/metrics/system_health/cpu_time_tree_data_reporter.html">
<link rel="import" href="/tracing/value/histogram_set.html">

<script>
'use strict';

tr.b.unittest.testSuite(function() {
  const reportToHistogramSet =
      tr.metrics.sh.CpuTimeTreeDataReporter.reportToHistogramSet;

  test('reportToHistogramSet_reportsLeafNodes', () => {
    const mdvBuilder = new tr.b.MultiDimensionalViewBuilder(
      3 /* dimensions (process, thread and rail stage / initiator) */,
      2 /* valueCount (cpuPercentage and cpuTime) */);
    mdvBuilder.addPath(
      [['browser_process'], ['CrBrowserMain'], ['Animation', 'CSS']],
      [42, 43], tr.b.MultiDimensionalViewBuilder.ValueKind.TOTAL);
    const rootNode = mdvBuilder.buildTopDownTreeView();

    const histograms = new tr.v.HistogramSet();
    reportToHistogramSet(rootNode, histograms);

    const cpuPercentageHistogram = histograms.getHistogramNamed(
        'cpuPercentage:browser_process:CrBrowserMain:Animation:CSS');
    const cpuTimeHistogram = histograms.getHistogramNamed(
        'cpuTime:browser_process:CrBrowserMain:Animation:CSS');

    // Histograms exist.
    assert.isDefined(cpuPercentageHistogram);
    assert.isDefined(cpuTimeHistogram);

    // Each histogram contains a single sample.
    assert.strictEqual(cpuPercentageHistogram.running.count, 1);
    assert.strictEqual(cpuTimeHistogram.running.count, 1);

    // Histogram sample value is correct.
    assert.closeTo(cpuPercentageHistogram.sum, 42, 1e-7);
    assert.closeTo(cpuTimeHistogram.sum, 43, 1e-7);
  });

  test('reportToHistogramSet_reportsAllProcesses', () => {
    const mdvBuilder = new tr.b.MultiDimensionalViewBuilder(
        3 /* dimensions (process, thread and rail stage / initiator) */,
        2 /* valueCount (cpuPercentage and cpuTime) */);
    mdvBuilder.addPath(
        [['browser_process'], ['CrBrowserMain'], ['Animation', 'CSS']],
        [42, 43], tr.b.MultiDimensionalViewBuilder.ValueKind.TOTAL);
    const rootNode = mdvBuilder.buildTopDownTreeView();

    const histograms = new tr.v.HistogramSet();
    reportToHistogramSet(rootNode, histograms);

    const cpuPercentageHistogram = histograms.getHistogramNamed(
        'cpuPercentage:all_processes:CrBrowserMain:Animation:CSS');
    const cpuTimeHistogram = histograms.getHistogramNamed(
        'cpuTime:all_processes:CrBrowserMain:Animation:CSS');

    // Histograms exist.
    assert.isDefined(cpuPercentageHistogram);
    assert.isDefined(cpuTimeHistogram);

    // Each histogram contains a single sample.
    assert.strictEqual(cpuPercentageHistogram.running.count, 1);
    assert.strictEqual(cpuTimeHistogram.running.count, 1);

    // Histogram sample value is correct.
    assert.closeTo(cpuPercentageHistogram.sum, 42, 1e-7);
    assert.closeTo(cpuTimeHistogram.sum, 43, 1e-7);
  });

  test('reportToHistogramSet_reportsAllThreads', () => {
    const mdvBuilder = new tr.b.MultiDimensionalViewBuilder(
      3 /* dimensions (process, thread and rail stage / initiator) */,
      2 /* valueCount (cpuPercentage and cpuTime) */);
    mdvBuilder.addPath(
      [['browser_process'], ['CrBrowserMain'], ['Animation', 'CSS']],
      [42, 43], tr.b.MultiDimensionalViewBuilder.ValueKind.TOTAL);
    const rootNode = mdvBuilder.buildTopDownTreeView();

    const histograms = new tr.v.HistogramSet();
    reportToHistogramSet(rootNode, histograms);

    const cpuPercentageHistogram = histograms.getHistogramNamed(
        'cpuPercentage:browser_process:all_threads:Animation:CSS');
    const cpuTimeHistogram = histograms.getHistogramNamed(
        'cpuTime:browser_process:all_threads:Animation:CSS');

    // Histograms exist.
    assert.isDefined(cpuPercentageHistogram);
    assert.isDefined(cpuTimeHistogram);

    // Each histogram contains a single sample.
    assert.strictEqual(cpuPercentageHistogram.running.count, 1);
    assert.strictEqual(cpuTimeHistogram.running.count, 1);

    // Histogram sample value is correct.
    assert.closeTo(cpuPercentageHistogram.sum, 42, 1e-7);
    assert.closeTo(cpuTimeHistogram.sum, 43, 1e-7);
  });

  test('reportToHistogramSet_doesNotAggregateStagesWithoutAllStagesNode',
      () => {
        const mdvBuilder = new tr.b.MultiDimensionalViewBuilder(
          3 /* dimensions (process, thread and rail stage / initiator) */,
          2 /* valueCount (cpuPercentage and cpuTime) */);
        mdvBuilder.addPath(
          [['browser_process'], ['CrBrowserMain'], ['Animation', 'CSS']],
          [42, 43], tr.b.MultiDimensionalViewBuilder.ValueKind.TOTAL);
        const rootNode = mdvBuilder.buildTopDownTreeView();

        const histograms = new tr.v.HistogramSet();
        reportToHistogramSet(rootNode, histograms);

        // all_stages:CSS does not make sense (e.g. we will never
        // aggregate Scroll Response and Scroll Animation, even if that's a
        // thing), so we use all_stages:all_initiators here.
        assert.isUndefined(histograms.getHistogramNamed(
            'cpuPercentage:' +
            'browser_process:CrBrowserMain:all_stages:all_initiators'));
        assert.isUndefined(histograms.getHistogramNamed(
            'cpuTime:' +
            'browser_process:CrBrowserMain:all_stages:all_initiators'));
      });

  test('reportToHistogramSet_' +
       'doesNotAggregateInitiatorsWithoutAllInitiatorsNode',
      () => {
        const mdvBuilder = new tr.b.MultiDimensionalViewBuilder(
          3 /* dimensions (process, thread and rail stage / initiator) */,
          2 /* valueCount (cpuPercentage and cpuTime) */);
        mdvBuilder.addPath(
          [['browser_process'], ['CrBrowserMain'], ['Animation', 'CSS']],
          [42, 43], tr.b.MultiDimensionalViewBuilder.ValueKind.TOTAL);
        const rootNode = mdvBuilder.buildTopDownTreeView();

        const histograms = new tr.v.HistogramSet();
        reportToHistogramSet(rootNode, histograms);

        assert.isUndefined(histograms.getHistogramNamed(
            'cpuPercentage:' +
            'browser_process:CrBrowserMain:Animation:all_initiators'));
        assert.isUndefined(histograms.getHistogramNamed(
            'cpuTime:browser_process:CrBrowserMain:Animation:all_initiators'));
      });
});
</script>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.bcvsolutions.idm.core.api.utils;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.time.LocalDate;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.Asserts;
import org.springframework.util.Assert;

import eu.bcvsolutions.idm.core.api.domain.Auditable;
import eu.bcvsolutions.idm.core.api.entity.ValidableEntity;

/**
 * Common entity helpers
 *
 * @author Radek Tomiška <tomiska@ders.cz>
 */
public class EntityUtils {

	private EntityUtils() {
	}

	/**
	 * Returns true, when given entity is valid, false otherwise
	 *
	 * @param entity
	 * @return
	 */
	public static boolean isValid(ValidableEntity entity) {
		return isValid(entity, LocalDate.now());
	}

	/**
	 * Returns if entity is valid for given date.
	 *
	 * @param entity
	 * @param targetDate
	 * @return
	 */
	public static boolean isValid(ValidableEntity entity, LocalDate targetDate) {
		Assert.notNull(targetDate, "Target date to compare validity is required.");
		//
		if (entity == null) {
			return false;
		}
		return (entity.getValidFrom() == null || entity.getValidFrom().compareTo(targetDate) <= 0)
				&& (entity.getValidTill() == null || entity.getValidTill().compareTo(targetDate) >= 0);
	}

	/**
	 * Returns true, when given dates are currently is valid, false otherwise
	 *
	 * @param validFrom
	 * @param validTill
	 * @return
	 */
	public static boolean isValid(ZonedDateTime validFrom, ZonedDateTime validTill) {
		return isValid(validFrom, validTill, ZonedDateTime.now());
	}

	/**
	 * Returns if dates are valid for given date.
	 *
	 * @param validFrom
	 * @param validTill
	 * @param targetDate
	 * @return
	 */
	public static boolean isValid(ZonedDateTime validFrom, ZonedDateTime validTill, ZonedDateTime targetDate) {
		Assert.notNull(targetDate, "Target date to compare validity is required.");
		//
		return (validFrom == null || validFrom.compareTo(targetDate) <= 0)
				&& (validTill == null || validTill.compareTo(targetDate) >= 0);
	}

	/**
	 * Returns true, if entity is valid in future, but not now.
	 *
	 * @param entity
	 * @return
	 */
	public static boolean isValidInFuture(ValidableEntity entity) {
		if (entity == null) {
			return false;
		}
		LocalDate now = LocalDate.now();
		return entity.getValidFrom() != null && entity.getValidFrom().compareTo(now) > 0
				&& (entity.getValidTill() == null || entity.getValidTill().compareTo(now) > 0);
	}

	/**
	 * Returns true, if entity is valid now or in future.
	 *
	 * @param entity
	 * @return
	 */
	public static boolean isValidNowOrInFuture(ValidableEntity entity) {
		if (entity == null) {
			return false;
		}
		LocalDate now = LocalDate.now();

		return entity.getValidTill() == null || entity.getValidTill().compareTo(now) >= 0;
	}

	/**
	 * Returns false, when validable information are the same
	 *
	 * @param previous
	 * @param current
	 * @return
	 */
	public static boolean validableChanged(ValidableEntity previous, ValidableEntity current) {
		return !Objects.equals(previous.getValidFrom(), current.getValidFrom()) || !Objects.equals(previous.getValidTill(), current.getValidTill());
	}

	/**
	 * Returns module name by entity package (by convention)
     * <p>
	 * TODO: Does not work for inline classes
	 *
	 * @param entityClass
	 * @return module identifier
	 */
	public static String getModule(Class<?> entityClass) {
		Assert.notNull(entityClass, "Entity class is requered to get IdM module.");
		//
		String name = entityClass.getCanonicalName();
		if (StringUtils.isEmpty(name)) {
			return null;
		}
		String packages[] = name.split("\\.");
		if (packages.length > 3) {
			return packages[3];
		}
		return null;
	}

	/**
	 * Returns {@link UUID} from given {@code string} or {@link UUID}.
	 *
	 * @param identifier {@code string} or {@link UUID}
	 * @return
     * @throws ClassCastException If identifier does not conform to the string representation as
     *          described in {@link #toString}
	 */
	public static UUID toUuid(Object identifier) {
        if(identifier == null) {
        	return null;
        }

        try {
            if(identifier instanceof UUID) {
                return (UUID) identifier;
            }
            return UUID.fromString((String) identifier);
        } catch (Exception ex) {
            throw new ClassCastException(String.format("Identified object [%s] is not an UUID.", identifier));
        }
    }

	/**
	 * Check if is string convertible to {@link UUID}
	 *
	 * @param uuid
	 * @return true if is given string convertible to {@link UUID}
	 */
	public static boolean isUuid(String uuid){
		if( uuid == null){
			return false;
		}
		try {
			UUID.fromString(uuid);
		} catch(IllegalArgumentException ex){
			// Simple is not UUID
			return false;
		}
		return true;
	}

    public static Field getFirstFieldInClassHierarchy(Class<?> sourceType, String field) throws NoSuchFieldException {
        Field result = getFirstFieldInClassHierarchyInternal(sourceType, field);
        if (result == null) {
            throw new NoSuchFieldException(String.format("No field %s found in class %s", field, sourceType));
        }
        return result;
    }

    private static Field getFirstFieldInClassHierarchyInternal(Class<?> sourceType, String field) {
        if (sourceType == null || field == null) {
            return null;
        }
        final Field[] fields = sourceType.getDeclaredFields();
        return Arrays.stream(fields)
                .filter(f -> field.equals(f.getName()))
                .findFirst()
                .orElseGet(() -> getFirstFieldInClassHierarchyInternal(sourceType.getSuperclass(), field));
    }

    /**
     * Find field property descriptor.
     *
     * @param entity dto / entity / object
     * @param propertyName field name
     * @return field property descriptor
     * @throws IntrospectionException
     * @throws IllegalAccessException
     * @throws IllegalArgumentException
     * @throws InvocationTargetException
     * @since 10.2.0
     */
    public static PropertyDescriptor getFieldDescriptor(Object entity, String propertyName)
    		throws IntrospectionException, IllegalAccessException {
    	Assert.notNull(entity, "Dto /  entity / ojec is required to find field property descriptor.");
    	Assert.hasLength(propertyName, "Property name is requred.");
    	Class<?> entityClass = entity.getClass();
    	//
		Optional<PropertyDescriptor> propertyDescriptionOptional = Arrays
				.asList(Introspector.getBeanInfo(entityClass).getPropertyDescriptors())
				.stream()
				.filter(propertyDescriptor -> {
					return propertyName.equals(propertyDescriptor.getName());
				})
				.findFirst();
		//
		if (!propertyDescriptionOptional.isPresent()) {
			throw new IllegalAccessException(String.format("Class [%s] field [%s] not found.", entityClass, propertyName));
		}
		return propertyDescriptionOptional.get();
	}

	/**
	 * Return object from entity for given property name
	 *
	 * @param entity
	 * @param propertyName
	 * @return
	 * @throws IntrospectionException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public static Object getEntityValue(Object entity, String propertyName)
			throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		PropertyDescriptor propertyDescriptor = getFieldDescriptor(entity, propertyName);
		//
		return propertyDescriptor.getReadMethod().invoke(entity);
	}

	/**
	 * Get value from given entity field.
	 * If is first parameter in write method String and value is not String, then will be value converted to String.
	 *
	 * @param entity
	 * @param propertyName
	 * @param value
	 * @return
	 * @throws IntrospectionException
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 */
	public static Object setEntityValue(Object entity, String propertyName, Object value)
			throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		Optional<PropertyDescriptor> propertyDescriptionOptional = Arrays
				.asList(Introspector.getBeanInfo(entity.getClass()).getPropertyDescriptors()).stream()
				.filter(propertyDescriptor -> {
					return propertyName.equals(propertyDescriptor.getName());
				}).findFirst();
		if (!propertyDescriptionOptional.isPresent()) {
			throw new IllegalAccessException("Field " + propertyName + " not found!");
		}
		PropertyDescriptor propertyDescriptor = propertyDescriptionOptional.get();
		Class<?> parameterClass = propertyDescriptor.getWriteMethod().getParameterTypes()[0];
		if (value != null && String.class.equals(parameterClass) && !(value instanceof String)) {
			value = String.valueOf(value);
		}
		// When is target LocalDate and value not, then we try create instance of LocalDate first
		if (value != null && LocalDate.class.equals(parameterClass) && !(value instanceof LocalDate)) {
			value = LocalDate.parse(value.toString());
		}
		if (value != null && !parameterClass.isAssignableFrom(value.getClass()) && !(value.getClass().isPrimitive() || parameterClass.isPrimitive())) {
			throw new IllegalAccessException(
					MessageFormat.format("Wrong type of value [{0}]. Value must be instance of [{1}] type, but has type [{2}]!",
							value, parameterClass, value.getClass()));
		}
		return propertyDescriptor.getWriteMethod().invoke(entity, value);
	}

	/**
	 * Method clear audit fields in entity. Entity must not be null.
	 *
	 * @param entity or dto
	 */
	public static void clearAuditFields(Auditable auditable) {
		Asserts.notNull(auditable, "Entity must be not null!");
		//
		auditable.setCreated(null);
		auditable.setCreator(null);
		auditable.setCreatorId(null);
		auditable.setModified(null);
		auditable.setModifier(null);
		auditable.setModifierId(null);
		auditable.setOriginalCreator(null);
		auditable.setOriginalCreatorId(null);
		auditable.setOriginalModifier(null);
		auditable.setOriginalModifierId(null);
		auditable.setTransactionId(null);
	}

	/**
	 * Sets target audit fields by given source.
	 * Id and realm id is not copied.
	 *
	 * @param auditableSource entity or dto
	 * @param auditableTarget entity or dto
	 * @see #setAuditable(Auditable, Auditable)
	 */
	public static void copyAuditFields(Auditable source, Auditable target) {
		Asserts.notNull(target, "Entity must be not null!");
		Asserts.notNull(source, "Entity must be not null!");
		//
		target.setCreated(source.getCreated());
		target.setCreator(source.getCreator());
		target.setCreatorId(source.getCreatorId());
		target.setModified(source.getModified());
		target.setModifier(source.getModifier());
		target.setModifierId(source.getModifierId());
		target.setOriginalCreator(source.getOriginalCreator());
		target.setOriginalCreatorId(source.getOriginalCreatorId());
		target.setOriginalModifier(source.getModifier());
		target.setOriginalModifierId(source.getOriginalModifierId());
		target.setTransactionId(source.getTransactionId());
	}
}


text:
package live;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * Class that handles the input and output queue
 * @author Han
 *
 * @param <T>
 */
public class InputOutputQueue<T> implements InputQueue<T>, OutputQueue<T> {

	protected Queue<T> out;
	protected Queue<T> in;

	public InputOutputQueue(Queue<T> in) {
		this.in = in;
		this.out = new ConcurrentLinkedQueue<T>();
	}

	public Queue<T> getInputQueue() {
		return this.in;
	}

	@Override
	public Queue<T> getOutputQueue() {
		return this.out;
	}

	@Override
	public void setInputQueue(Queue<T> q) {
		this.in = q;
	}

}


text:
namespace cryo {
namespace opencl {

enum OpenclMemFlag {
	ReadWrite = CL_MEM_READ_WRITE,
	ReadOnly = CL_MEM_READ_ONLY,
	WriteOnly = CL_MEM_WRITE_ONLY,
	UseHostPointer = CL_MEM_USE_HOST_PTR,
	AllocHostPointer = CL_MEM_ALLOC_HOST_PTR,
	CopyHostPointer = CL_MEM_COPY_HOST_PTR
};

class OpenclContext {
	public:
		static std::unique_ptr<OpenclContext> create(const std::vector<OpenclDevice>& p_devices) throw (std::exception, OpenclError);
		static std::unique_ptr<OpenclContext> create(const OpenclDevice& p_device) throw (std::exception, OpenclError);

	private:
		cl_context m_handle;

	public:
		OpenclContext(const cl_context& p_handle);
		OpenclContext(const OpenclContext& p_other) = delete;
		virtual ~OpenclContext() throw ();

		OpenclContext& operator=(const OpenclContext& p_other) = delete;

		inline const cl_context& getHandle() const;

		std::unique_ptr<OpenclCommandQueue> createCommandQueue(const OpenclDevice& p_device) const throw (OpenclError);
		std::unique_ptr<OpenclBuffer> createBuffer(OpenclMemFlag p_flags, std::size_t p_size, void* p_hostPointer = 0) const throw (OpenclError);
		std::unique_ptr<OpenclProgram> createProgram(const OpenclDevice& p_device, const std::string& p_file, const std::string& p_includePath = "") const throw (std::exception, OpenclError);

	private:
		std::string loadSource(const std::string& p_file) const throw (std::exception);
};

}}

namespace cryo {
namespace opencl {

inline const cl_context& OpenclContext::getHandle() const {
	return m_handle;
}

}}

#endif


text:
export * from './mail-notification.reducers'
export * from './mail-notification.component'
export * from './mail-notification.module'


text:
package com.banadiga.http2;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Http2Application {
  public static void main(String[] args) {
    SpringApplication.run(Http2Application.class, args);
  }
}


text:
package org.hamcrest.generator;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Pattern;

import com.thoughtworks.qdox.model.DocletTag;
import com.thoughtworks.qdox.model.JavaAnnotation;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaMethod;
import com.thoughtworks.qdox.model.JavaParameter;
import com.thoughtworks.qdox.model.JavaType;
import com.thoughtworks.qdox.model.JavaTypeVariable;

/**
 * Wraps an existing sequence of FactoryMethods, and attempts to pull in
 * parameter names and JavaDoc (which aren't available using reflection) using
 * QDox.
 *
 * @see QDox
 * @author Joe Walnes
 */
public class QDoxFactoryReader implements Iterable<FactoryMethod> {

    private final JavaClass classSource;

    private JavaClass factoryAnnotation;

    private static final Pattern GENERIC_REGEX = Pattern.compile("^<(.*)>$");

    public QDoxFactoryReader(QDox qdox, String className) {
        this.classSource = qdox.getClassByName(className);
        this.factoryAnnotation = qdox.getClassByName("org.hamcrest.Factory");
    }

    @Override
    public Iterator<FactoryMethod> iterator() {
        List<FactoryMethod> methods = new ArrayList<FactoryMethod>();

        for (JavaMethod jm : classSource.getMethods()) {
            if (!isFactoryMethod(jm)) {
                continue;
            }

            FactoryMethod fm = new FactoryMethod(typeToString(classSource), jm.getName(), typeToString(jm.getReturnType()));

            for (JavaTypeVariable<?> tv : jm.getTypeParameters()) {
                String decl = tv.getGenericFullyQualifiedName();
                decl = GENERIC_REGEX.matcher(decl).replaceFirst("$1");
                fm.addGenericTypeParameter(decl);
            }

            for (JavaParameter p : jm.getParameters()) {
                String type = typeToString(p.getType());

                // Special case for var args methods.... String[] -> String...
                if (p.isVarArgs()) {
                    type += "...";
                }

                fm.addParameter(type, p.getName());
            }

            for (JavaType exception : jm.getExceptions()) {
                fm.addException(typeToString(exception));
            }

            fm.setJavaDoc(createJavaDocComment(jm));

            String generifiedType = GENERIC_REGEX.matcher(fm.getReturnType()).replaceFirst("$1");
            if (!generifiedType.equals(fm.getReturnType())) {
                fm.setGenerifiedType(generifiedType);
            }

            methods.add(fm);
        }

        Collections.sort(methods, new Comparator<FactoryMethod>() {
            @Override public int compare(FactoryMethod o1, FactoryMethod o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        return methods.iterator();
    }

    /**
     * Determine whether a particular method is classified as a matcher factory method.
     *

     *
The rules for determining this are:
     * 1. The method must be public static.
     * 2. It must have a return type of org.hamcrest.Matcher (or something that extends this).
     * 3. It must be marked with the org.hamcrest.Factory annotation.
     *

     *
To use another set of rules, override this method.
     */
    protected boolean isFactoryMethod(JavaMethod javaMethod) {
        return javaMethod.isStatic()
                && javaMethod.isPublic()
                && hasFactoryAnnotation(javaMethod)
                && !javaMethod.getReturnType().equals(JavaType.VOID);
    }

    private boolean hasFactoryAnnotation(JavaMethod javaMethod) {
        for (JavaAnnotation a : javaMethod.getAnnotations()) {
            if (a.getType().equals(factoryAnnotation)) {
                return true;
            }
        }
        return false;
    }

    private static String typeToString(JavaType type) {
        return type.getGenericFullyQualifiedName().replace('$', '.');
    }

    /**
     * Reconstructs the JavaDoc as a string for a particular method.
     */
    private static String createJavaDocComment(JavaMethod methodSource) {
        String comment = methodSource.getComment();
        List<DocletTag> tags = methodSource.getTags();
        if ((comment == null || comment.trim().length() == 0) && tags.isEmpty()) {
            return null;
        }
        StringBuilder result = new StringBuilder();
        result.append(comment);
        result.append("\n\n");
        for (DocletTag tag : tags) {
            result.append('@').append(tag.getName())
                    .append(' ').append(tag.getValue())
                    .append('\n');
        }
        return result.toString();
    }

}


text:
#include <wtf/HashSet.h>
#include <wtf/RefCounted.h>
#include <wtf/text/WTFString.h>

namespace WebCore {
class StorageNamespaceProvider;
class UserContentController;
}

class WebVisitedLinkStore;

OBJC_CLASS WebView;

class WebViewGroup : public RefCounted<WebViewGroup> {
public:
    static RefPtr<WebViewGroup> getOrCreate(const String& name, const String& localStorageDatabasePath);
    ~WebViewGroup();

    static WebViewGroup* get(const String& name);

    void addWebView(WebView *);
    void removeWebView(WebView *);

    WebCore::StorageNamespaceProvider& storageNamespaceProvider();
    WebCore::UserContentController& userContentController() { return m_userContentController.get(); }
    WebVisitedLinkStore& visitedLinkStore() { return m_visitedLinkStore.get(); }

private:
    WebViewGroup(const String& name, const String& localStorageDatabasePath);

    String m_name;
    HashSet<WebView *> m_webViews;

    String m_localStorageDatabasePath;
    RefPtr<WebCore::StorageNamespaceProvider> m_storageNamespaceProvider;

    Ref<WebCore::UserContentController> m_userContentController;
    Ref<WebVisitedLinkStore> m_visitedLinkStore;
};


text:
  Vouhenans est
       un village
       localisé dans le département de Haute-Saône en Franche-Comté. Elle totalisait 405 habitants en 2008.

À coté de Vouhenans sont localisées les communes de
La Vergenne située à 6 km, 108 habitants,
Gouhenans localisée à 5 km, 435 habitants,
Les Aynans à 4 km, 297 habitants,
Bouhans-lès-Lure située à 6 km, 268 habitants,
Froideterre située à 6 km, 366 habitants,
Magny-Vernois à 1 km, 1 200 habitants,
 entre autres. De plus, Vouhenans est située à seulement 28 km de Belfort.

Si vous envisagez de emmenager à Vouhenans, vous pourrez facilement trouver une maison à acheter.

Le parc de logements, à Vouhenans, était réparti en 2011 en 20 appartements et 168 maisons soit
 un marché plutôt équilibré.


text:
class VERGEClient
  class RPCError < StandardError

    attr_accessor :message

    def initialize(message)
      @message = message
    end

  end
end


text:
/*
 NAME
    OMCredentialStoreService.h - Oracle Mobile Credential Store Service

 DESCRIPTION
    Credential Store service that takes care of returning cred store

 RELATED DOCUMENTS
    None

 PROTOCOLS
    None

 EXAMPLES
    None

 NOTES
    None

 MODIFIED   (MM/DD/YY)
 msadasiv    11/20/12 - Bug 14836655 - set ksecattraccessible to a secure
                                       by default value
 sativenk    01/03/12 - Added header
 kerajago    10/02/11 - Creation
 */

#import <Foundation/Foundation.h>
#import "OMCredentialStore.h"

/**
 * OMCredentialStoreService is used to get OMCredentialStore object.
 */
@interface OMCredentialStoreService : NSObject
{
@private
    OMCredentialStore *_credStore;
}

@property (nonatomic, retain) OMCredentialStore *credStore;

/**
 * @brief Default protection level for keychain data entries
 *
 * Any keychain entry gets this protection level if not overrided by protection
 * parameter.
 * @param keychainDataProtection   String value of protection level.
 * @return                         Returns nil if keychainDataProtection provided
 *                                 is not valid.
 */
- (id)initWithDefaultKeychainDataProtection:(NSString *)keychainDataProtection;

@end


text:
module Superbolt
  class App
    attr_reader :config, :env, :runner_type, :error_notifier_type
    attr_accessor :logger

    def initialize(name, options={})
      @name                = name
      @env                 = options[:env] || Superbolt.env
      @logger              = options[:logger] || LogStashLogger.new(type: :stdout)
      @config              = options[:config] || Superbolt.config
      @runner_type         = options[:runner] || config.runner || :default
      @error_notifier_type = options[:error_notifier] || Superbolt.error_notifier
    end

    def name
      env ? "#{@name}_#{env}" : @name
    end

    def connection
      @connection ||= Connection::Queue.new(name, config)
    end

    delegate :close, :closing, :exclusive?, :durable?, :auto_delete?,
      :writer, :channel, :q,
        to: :connection

    def queue
      connection.q
    end

    def run(&block)
      runner_class.new(queue, error_notifier, logger, block).run
    end

    def runner_class
      runner_map[runner_type] || default_runner
    end

    def runner_map
      {
        pop:      Runner::Pop,
        ack_one:  Runner::AckOne,
        ack:      Runner::Ack,
        greedy:   Runner::Greedy,
        pg:       Runner::Pg
      }
    end

    def default_runner
      runner_map[:ack_one]
    end

    def error_notifier
      @error_notifier ||= error_notifier_class.new(logger)
    end

    def error_notifier_class
      error_notifier_map[error_notifier_type] || default_error_notifier
    end

    def error_notifier_map
      {
        airbrake: ErrorNotifier::Airbrake,
        rollbar: ErrorNotifier::Rollbar,
        none: ErrorNotifier::None
      }
    end

    def default_error_notifier
      error_notifier_map[:none]
    end

    def quit(message='no message given')
      logger.info "EXITING Superbolt App listening on queue #{name}: #{message}"
      q.channel.basic_cancel q.channel.consumers.first[0]
      close
    end
  end
end


text:
package de.plushnikov.intellij.plugin.extension;

import com.intellij.openapi.application.QueryExecutorBase;
import com.intellij.openapi.project.DumbService;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiReference;
import com.intellij.psi.search.SearchRequestCollector;
import com.intellij.psi.search.UsageSearchContext;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.util.Processor;
import de.plushnikov.intellij.plugin.psi.LombokLightFieldBuilder;
import de.plushnikov.intellij.plugin.psi.LombokLightMethodBuilder;
import org.jetbrains.annotations.NotNull;

import java.util.Arrays;
import java.util.Objects;

/**
 * Annas example: org.jetbrains.plugins.javaFX.fxml.refs.JavaFxControllerFieldSearcher
 * Alternative Implementation for LombokFieldFindUsagesHandlerFactory
 */
public class LombokReferenceSearcher extends QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters> {

  public LombokReferenceSearcher() {
    super(true);
  }

  @Override
  public void processQuery(@NotNull ReferencesSearch.SearchParameters queryParameters, @NotNull Processor consumer) {
    PsiElement refElement = queryParameters.getElementToSearch();

    if (refElement instanceof PsiField) {
      DumbService.getInstance(queryParameters.getProject()).runReadActionInSmartMode(() ->
        processPsiField((PsiField) refElement, queryParameters.getOptimizer()));
    }
  }

  private void processPsiField(final PsiField refPsiField, final SearchRequestCollector collector) {
    final PsiClass containingClass = refPsiField.getContainingClass();
    if (null != containingClass) {
      processClassMethods(refPsiField, collector, containingClass);

      final PsiClass[] innerClasses = containingClass.getInnerClasses();
      Arrays.stream(innerClasses)
        .forEach(psiClass -> processClassMethods(refPsiField, collector, psiClass));

      Arrays.stream(innerClasses)
        .forEach(psiClass -> processClassFields(refPsiField, collector, psiClass));
    }
  }

  private void processClassMethods(PsiField refPsiField, SearchRequestCollector collector, PsiClass containingClass) {
    Arrays.stream(containingClass.getMethods())
      .filter(LombokLightMethodBuilder.class::isInstance)
      .filter(psiMethod -> psiMethod.getNavigationElement() == refPsiField)
      .forEach(psiMethod -> {
        collector.searchWord(psiMethod.getName(), psiMethod.getUseScope(), UsageSearchContext.IN_CODE, true, psiMethod);
      });
  }

  private void processClassFields(PsiField refPsiField, SearchRequestCollector collector, PsiClass containingClass) {
    Arrays.stream(containingClass.getFields())
      .filter(LombokLightFieldBuilder.class::isInstance)
      .filter(psiField -> psiField.getNavigationElement() == refPsiField)
      .filter(psiField -> Objects.nonNull(psiField.getName()))
      .forEach(psiField -> {
        collector.searchWord(psiField.getName(), psiField.getUseScope(), UsageSearchContext.IN_CODE, true, psiField);
      });
  }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="shortcut icon" href="favicon.ico">

    <title>End Game: Collegiate Esports Summit</title>

    <link href="assets/css/bootstrap.css" rel="stylesheet">

    <link href="assets/css/style.css" rel="stylesheet">
    <link href="assets/css/font-awesome.min.css" rel="stylesheet">

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
            Toggle navigation

          </button>
          End Game Summit

HOME

              ABOUT

ABOUT US

CONTACT

JOBS

              UPCOMING SUMMITS

TEXAS: 2019

FLORIDA: 2019

              PAST SUMMITS

TEXAS: 2018

TEXAS: 2017

TEXAS: 2016

Texas: 2016

<! --/Carousel -->

About the Summit

The first summit's goal was to bring together a group of Texas Esports
		 		leaders, and create a dedicated network of collegiate leaders within the
		 		state. With one month of planning, we were able to host the summit at the
		 		University of Texas at Austin, score donations from Sparkypants, HEB and
		 		Redbull as well as guest speakers from EFG, Nerd Bird and Ward eSports.

Event Schedule

		 		Day 1 - Saturday, August 6th
				11:00AM Getting Situated

				11:30AM Welcome Leaders!

				12:00PM A look at Esports

				12:30PM Establish a Structure

				01:00PM Lunch Break

				02:00PM Legitimizing Your Club

				02:30PM Growing Your Club

				03:00PM Quick Break

				03:15PM EG Federation

				03:45PM Technology

				04:00PM Quick Break

				04:15PM Running Events

				04:45PM Ward Esports

				05:15PM Ice Breaker

				Day 2 - Sunday, August 7th
				11:00AM Getting Situated

				11:30AM Leadership: Info

				01:00PM Lunch Break

				02:00PM Nerd Bird

				02:30PM Leadership: Tech.

				03:00PM Closing Discussion

Summit Details

Date: August 6th & 7th, 2016.

Venue: University of Texas at Austin.

Dress Code: Business Casual.

Organizers: Brennan Settles, Jimmy Chan, Kaitlin Teniente, Chris Canik,
		 		Ruben Garcia, Katelyn Wilcox, Justin Yoo, Komsan Sujaritpakdee, Aaron Mance.

		 		23 Attendees

		 		9 Schools

		 		3 Guest Speakers

Special thanks to our donors:

HEB, Redbull, Sparkypants.

<! --/row -->

<! --/container -->

Our Event Sponsors & Guest Speakers

<! --/row -->

<! --/container -->

<! --/cwrap -->

About

We strive to bring Esports leaders together and provide them with
		 			the tools to create better Esports clubs and organizations.

Social Links

Contact Us

General Questions: contact@endgamesummit.com

		 			Sponsor Questions: sponsor@endgamesummit.com

<! --/row -->

<! --/container -->

<! --/footerwrap -->