text:
<title>Zend Framework API Documentation</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta><link rel="stylesheet" href="css/black-tie/jquery-ui-1.8.2.custom.css" type="text/css"></link><link rel="stylesheet" href="css/jquery.treeview.css" type="text/css"></link><link rel="stylesheet" href="css/theme.css" type="text/css"></link>

API Documentation

Service/WindowsAzure/Storage/TableEntityQuery.php

Global

                      Classes

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

Zend Framework

LICENSE

This source file is subject to the new BSD license that is bundled
with this package in the file LICENSE.txt.
It is also available through the world-wide-web at this URL:
http://framework.zend.com/license/new-bsd
If you did not receive a copy of the license and are unable to
obtain it through the world-wide-web, please send an email
to license@zend.com so we can send you a copy immediately.

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service_WindowsAzure

subpackage

Storage

version

$Id: TableEntityQuery.php 23775 2011-03-01 17:25:24Z ralph $

\Zend_Service_WindowsAzure_Storage_TableEntityQuery
jump to top

category

Zend

copyright

Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)

license

New BSD License

package

Zend_Service_WindowsAzure

subpackage

Storage

Properties

string
                 $_from= ''

From

Details

Type

string

array
                 $_orderBy= 'array'

Order by

Default valuearrayDetails

Type

array

string
                 $_partitionKey= 'null'

Partition key

Default valuenullDetails

Type

string

string
                 $_rowKey= 'null'

Row key

Default valuenullDetails

Type

string

int
                 $_top= 'null'

Top

Default valuenullDetails

Type

int

array
                 $_where= 'array'

Where

Default valuearrayDetails

Type

array

Methods

__toString(

          )

        :
          string

__toString overload

Returns

Type
Description

string

_quoteInto(
          string $text, string|array $value
              =
              null
          )

        :
          string

Quotes a variable into a condition

Parameters

Name
Type
Description

$text
string

Condition, can contain question mark(s) (?) for parameter insertion.

$value
string|array

Value(s) to insert in question mark (?) parameters.

Returns

Type
Description

string

_replaceOperators(
          string $text
          )

        :
          string

Replace operators

Parameters

Name
Type
Description

$text
string

Returns

Type
Description

string

andWhere(
          string $condition, string|array $value
              =
              null
          )

        :
          \Zend_Service_WindowsAzure_Storage_TableEntityQuery

Add where clause with AND condition

Parameters

Name
Type
Description

$condition
string

Condition, can contain question mark(s) (?) for parameter insertion.

$value
string|array

Value(s) to insert in question mark (?) parameters.

Returns

Type
Description

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

assembleFrom(
          boolean $includeParentheses
              =
              true
          )

        :
          string

Assemble from

Parameters

Name
Type
Description

$includeParentheses
boolean

Include parentheses? ()

Returns

Type
Description

string

assembleQuery(

          )

        :
          string

Assemble full query

Returns

Type
Description

string

assembleQueryString(
          boolean $urlEncode
              =
              false
          )

        :
          string

Assembles the query string

Parameters

Name
Type
Description

$urlEncode
boolean
Apply URL encoding to the query string

Returns

Type
Description

string

encodeQuery(
          string $query
          )

        :
          string

static
urlencode a query

Parameters

Name
Type
Description

$query
string
Query to encode

Returns

Type
Description

string
Encoded query

from(
          string $name
          )

        :
          \Zend_Service_WindowsAzure_Storage_TableEntityQuery

From clause

Parameters

Name
Type
Description

$name
string
Table name to select entities from

Returns

Type
Description

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

orWhere(
          string $condition, string|array $value
              =
              null
          )

        :
          \Zend_Service_WindowsAzure_Storage_TableEntityQuery

Add where clause with OR condition

Parameters

Name
Type
Description

$condition
string

Condition, can contain question mark(s) (?) for parameter insertion.

$value
string|array

Value(s) to insert in question mark (?) parameters.

Returns

Type
Description

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

orderBy(
          string $column, string $direction
              =
              asc
          )

        :
          \Zend_Service_WindowsAzure_Storage_TableEntityQuery

OrderBy clause

Parameters

Name
Type
Description

$column
string
Column to sort by

$direction
string

Direction to sort (asc/desc)

Returns

Type
Description

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

select(

          )

        :
          \Zend_Service_WindowsAzure_Storage_TableEntityQuery

Select clause

Returns

Type
Description

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

top(
          int $top
              =
              null
          )

        :
          \Zend_Service_WindowsAzure_Storage_TableEntityQuery

Top clause

Parameters

Name
Type
Description

$top
int
Top to fetch

Returns

Type
Description

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

where(
          string $condition, string|array $value
              =
              null, string $cond
          )

        :
          \Zend_Service_WindowsAzure_Storage_TableEntityQuery

Add where clause

Parameters

Name
Type
Description

$condition
string

Condition, can contain question mark(s) (?) for parameter insertion.

$value
string|array

Value(s) to insert in question mark (?) parameters.

$cond
string

Condition for the clause (and/or/not)

Returns

Type
Description

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

wherePartitionKey(
          string $value
              =
              null
          )

        :
          \Zend_Service_WindowsAzure_Storage_TableEntityQuery

Specify partition key

Parameters

Name
Type
Description

$value
string
Partition key to query for

Returns

Type
Description

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

whereRowKey(
          string $value
              =
              null
          )

        :
          \Zend_Service_WindowsAzure_Storage_TableEntityQuery

Specify row key

Parameters

Name
Type
Description

$value
string
Row key to query for

Returns

Type
Description

\Zend_Service_WindowsAzure_Storage_TableEntityQuery

Documentation was generated by DocBlox 0.13.3.


text:
export default function triggerBrowserReflow(node) {
  node.offsetHeight; // eslint-disable-line no-unused-expressions
}

redpajama_set_name: RedPajamaGithub


text:
from schematics.exceptions import ModelValidationError

class UnknownTableException(Exception):
    pass

class TableAlreadyExistsException(Exception):
    def __init__(self, response):
        self.response = response

class UpdateTableException(Exception):
    pass

class ConfigurationError(Exception):
    pass

class NotFound(Exception):
    pass

class ValidationError(ModelValidationError):
    pass

class MissingTableNameException(Exception):
    pass

class PrimaryKeyUpdateException(Exception):
    pass


text:
/*global define, module, require, window, document */

;(function (factory) {
  'use strict'
  if (typeof define === 'function' && define.amd) {
    // Register as an anonymous AMD module:
    define(['load-image'], factory)
  } else if (typeof module === 'object' && module.exports) {
    factory(require('./load-image'))
  } else {
    // Browser globals:
    factory(window.loadImage)
  }
}(function (loadImage) {
  'use strict'

  // Only apply fixes on the iOS platform:
  if (!window.navigator || !window.navigator.platform ||
    !(/iP(hone|od|ad)/).test(window.navigator.platform)) {
    return
  }

  var originalRenderMethod = loadImage.renderImageToCanvas

  // Detects subsampling in JPEG images:
  loadImage.detectSubsampling = function (img) {
    var canvas,
      context
    if (img.width * img.height > 1024 * 1024) { // only consider mexapixel images
      canvas = document.createElement('canvas')
      canvas.width = canvas.height = 1
      context = canvas.getContext('2d')
      context.drawImage(img, -img.width + 1, 0)
      // subsampled image becomes half smaller in rendering size.
      // check alpha channel value to confirm image is covering edge pixel or not.
      // if alpha value is 0 image is not covering, hence subsampled.
      return context.getImageData(0, 0, 1, 1).data[3] === 0
    }
    return false
  }

  // Detects vertical squash in JPEG images:
  loadImage.detectVerticalSquash = function (img, subsampled) {
    var naturalHeight = img.naturalHeight || img.height
    var canvas = document.createElement('canvas')
    var context = canvas.getContext('2d')
    var data
    var sy
    var ey
    var py
    var alpha
    if (subsampled) {
      naturalHeight /= 2
    }
    canvas.width = 1
    canvas.height = naturalHeight
    context.drawImage(img, 0, 0)
    data = context.getImageData(0, 0, 1, naturalHeight).data
    // search image edge pixel position in case it is squashed vertically:
    sy = 0
    ey = naturalHeight
    py = naturalHeight
    while (py > sy) {
      alpha = data[(py - 1) * 4 + 3]
      if (alpha === 0) {
        ey = py
      } else {
        sy = py
      }
      py = (ey + sy) >> 1
    }
    return (py / naturalHeight) || 1
  }

  // Renders image to canvas while working around iOS image scaling bugs:
  // https://github.com/blueimp/JavaScript-Load-Image/issues/13
  loadImage.renderImageToCanvas = function (
    canvas,
    img,
    sourceX,
    sourceY,
    sourceWidth,
    sourceHeight,
    destX,
    destY,
    destWidth,
    destHeight
  ) {
    if (img._type === 'image/jpeg') {
      var context = canvas.getContext('2d')
      var tmpCanvas = document.createElement('canvas')
      var tileSize = 1024
      var tmpContext = tmpCanvas.getContext('2d')
      var subsampled
      var vertSquashRatio
      var tileX
      var tileY
      tmpCanvas.width = tileSize
      tmpCanvas.height = tileSize
      context.save()
      subsampled = loadImage.detectSubsampling(img)
      if (subsampled) {
        sourceX /= 2
        sourceY /= 2
        sourceWidth /= 2
        sourceHeight /= 2
      }
      vertSquashRatio = loadImage.detectVerticalSquash(img, subsampled)
      if (subsampled || vertSquashRatio !== 1) {
        sourceY *= vertSquashRatio
        destWidth = Math.ceil(tileSize * destWidth / sourceWidth)
        destHeight = Math.ceil(
          tileSize * destHeight / sourceHeight / vertSquashRatio
        )
        destY = 0
        tileY = 0
        while (tileY < sourceHeight) {
          destX = 0
          tileX = 0
          while (tileX < sourceWidth) {
            tmpContext.clearRect(0, 0, tileSize, tileSize)
            tmpContext.drawImage(
              img,
              sourceX,
              sourceY,
              sourceWidth,
              sourceHeight,
              -tileX,
              -tileY,
              sourceWidth,
              sourceHeight
            )
            context.drawImage(
              tmpCanvas,
              0,
              0,
              tileSize,
              tileSize,
              destX,
              destY,
              destWidth,
              destHeight
            )
            tileX += tileSize
            destX += destWidth
          }
          tileY += tileSize
          destY += destHeight
        }
        context.restore()
        return canvas
      }
    }
    return originalRenderMethod(
      canvas,
      img,
      sourceX,
      sourceY,
      sourceWidth,
      sourceHeight,
      destX,
      destY,
      destWidth,
      destHeight
    )
  }
}))


text:
using CodeSanook.Core.Models;
using FluentNHibernate.Mapping;

namespace CodeSanook.Infrastructure.Data.Mappings
{
    public class TbMasCancellationInfoMap : ClassMap<TbMasCancellationInfo>
    {
        public TbMasCancellationInfoMap()
        {
            CompositeId(x => x.Key)
                .KeyProperty(x => x.CancelId, "CancellationId")
                .KeyProperty(x => x.CultureId, "CultureId");

            References(x => x.Cancellation, "CancellationId")
                .ForeignKey("none")
                .Not.Insert();
            Map(x => x.CancellationReason);
        }

    }
}


text:
module OneDBFsck
    # Sets:
    #
    #   @data_marketplaceapp: used also by marketplace check
    #   @fixes_marketplaceapp: used by do_check_marketplaceapp

    def check_marketplaceapp
        @data_marketplaceapp = {
            marketplace: {}
        }

        marketplace = @data_marketplaceapp[:marketplace]

        # DATA: create marketplace hash with its name and empty apps array
        @db.fetch("SELECT oid, name FROM marketplace_pool") do |row|
            marketplace[row[:oid]] = {:name => row[:name], :apps => []}
        end

        @fixes_marketplaceapp = {}
        apps_fix = @fixes_marketplaceapp

        # DATA: go through all apps
        @db.fetch("SELECT oid,body FROM marketplaceapp_pool") do |row|
            doc = Document.new(row[:body])

            market_id   = doc.root.get_text('MARKETPLACE_ID').to_s.to_i
            market_name = doc.root.get_text('MARKETPLACE')

            ####################################################################
            # DATA: TODO, BUG: this code will only work for a standalone oned.
            # In a federation, the image ID will refer to a different image
            # in each zone
            ####################################################################

            # DATA: get image origin id. Does it work?
            origin_id = doc.root.get_text('ORIGIN_ID').to_s.to_i
            if origin_id >= 0 && doc.root.get_text('STATE').to_s.to_i == 2 # LOCKED
                counters[:image][origin_id][:app_clones].add(row[:oid])
            end

            ####################################################################
            #####################################################################

            if market_id != -1
                market_entry = marketplace[market_id]

                # DATA: CHECK: does marketplace for this app exist?
                if market_entry.nil?
                    log_error("Marketplace App #{row[:oid]} has marketplace #{market_id}, but it does not exist. The app is probably unusable, and needs to be deleted manually:\n"<<
                        "  * The DB entry can be deleted with the command:\n"<<
                        "    DELETE FROM marketplaceapp_pool WHERE oid=#{row[:oid]};\n"<<
                        "  * Run fsck again.\n", false)
                else
                    # DATA: CHECK: marketplace name is correct
                    if market_name != market_entry[:name]
                        log_error("Marketplace App #{row[:oid]} has a wrong name for marketplace #{market_id}, #{market_name}. It will be changed to #{market_entry[:name]}")

                        doc.root.each_element('MARKETPLACE') do |e|
                            e.text = market_entry[:name]
                        end

                        apps_fix[row[:oid]] = doc.root.to_s
                    end

                    # DATA: Add app to marketplace list. Used in marketplace check
                    market_entry[:apps] << row[:oid]
                end
            end
        end
    end

    def fix_marketplaceapp
        # DATA: FIX: fix marketplace app data
        if !db_version[:is_slave]
            @db.transaction do
                @fixes_marketplaceapp.each do |id, body|
                    @db[:marketplaceapp_pool].where(:oid => id).update(:body => body)
                end
            end
        elsif !@fixes_marketplaceapp.empty?
            log_msg("^ Marketplace App errors need to be fixed in the master OpenNebula")
        end
    end
end


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.42000
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace ProAppCoordConversionModule.Properties {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class FileResources {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal FileResources() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ProAppCoordConversionModule.Properties.FileResources", typeof(FileResources).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to Geographic Coordinate Systems/Africa/Abidjan 1987|GCS_Abidjan_1987|4143|GEOGCS['GCS_Abidjan_1987',DATUM['D_Abidjan_1987',SPHEROID['Clarke_1880_RGS',6378249.145,293.465]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]Geographic Coordinate Systems/Africa/Accra|GCS_Accra|4168|GEOGCS['GCS_Accra',DATUM['D_Accra',SPHEROID['War_Office',6378300.0,296.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]Geographic Coordinate Systems/Africa/Adindan|GCS_Adindan|4201|GEOGCS['GCS_Adindan',DATUM['D_A [rest of string was truncated]";.
        /// </summary>
        public static string sr_out {
            get {
                return ResourceManager.GetString("sr_out", resourceCulture);
            }
        }
    }
}


text:
export default function callbackify(fn: () => Promise<any>) {
    return async (...args: any[]) => {
        const callback = args.pop();

        if ('function' !== typeof callback) {
            throw new TypeError('Callback is not a function');
        }

        try {
            const result = await fn(...args);

            callback(null, result);
            return result;
        } catch (error) {
            callback(error, null);
            throw error;
        }
    };
}


text:
package org.auraframework.util.type.converter;

import java.util.Date;

import org.auraframework.ds.serviceloader.AuraServiceProvider;
import org.auraframework.util.date.DateService;
import org.auraframework.util.date.DateServiceImpl;
import org.auraframework.util.type.Converter;

import aQute.bnd.annotation.component.Component;

@Component (provide=AuraServiceProvider.class)
public class StringToDateConverter implements Converter<String, Date> {

    @Override
    public Date convert(String value) {
        if (value == null || value.isEmpty()) {
            return null;
        }
        DateService dateService = DateServiceImpl.get();
        return dateService.getGenericISO8601Converter().parse(value);
    }

    @Override
    public Class<String> getFrom() {
        return String.class;
    }

    @Override
    public Class<Date> getTo() {
        return Date.class;
    }

    @Override
    public Class<?>[] getToParameters() {
        return null;
    }
}


text:
var _ = require('underscore'),
transformations = require('../transformations');
module.exports = function(req, res){
  var transforms = [];
  _.each(transformations, function(value, key){
    if (key === '_set'){
      return;
    }
    transforms.push({name : key, type : value.type});
  });
  return res.json(transforms);
};


text:
namespace SnapMD.VirtualCare.ApiModels
{
    public static class AddressObjectExtensions
    {
        public static bool SafeIsEmpty(this AddressObject addressObject)
        {
            return addressObject == null || addressObject.IsEmpty();
        }
    }
}


text:
#ifndef WORKLOAD_SIMPLEMEM_MEMORYTERMINAL_H_
#define WORKLOAD_SIMPLEMEM_MEMORYTERMINAL_H_

#include <json/json.h>
#include <prim/prim.h>

#include <queue>
#include <string>
#include <vector>

#include "event/Component.h"
#include "workload/Terminal.h"

class Application;

namespace SimpleMem {

class MemoryTerminal : public Terminal {
 public:
  MemoryTerminal(const std::string& _name, const Component* _parent,
                 u32 _id, const std::vector<u32>& _address, u32 _memorySlice,
                 ::Application* _app, Json::Value _settings);
  ~MemoryTerminal();
  void processEvent(void* _event, s32 _type) override;

 protected:
  void handleDeliveredMessage(Message* _message) override;
  void handleReceivedMessage(Message* _message) override;

 private:
  enum class eState {kWaiting, kAccessing};

  void startMemoryAccess();
  void sendMemoryResponse();

  u32 protocolClass_;

  u32 memoryOffset_;
  u8* memory_;
  u32 latency_;

  std::queue<Message*> messages_;
  eState fsm_;
};

}  // namespace SimpleMem

#endif  // WORKLOAD_SIMPLEMEM_MEMORYTERMINAL_H_


text:
App.PasswordConfirmView = Ember.View.extend({
    templateName: 'components/password_confirm'
});
Ember.Handlebars.helper('passwordconfirm-view', App.PasswordConfirmView);


text:
import * as React from 'react';
import { Alert } from '../Alert';
import { Renderer } from '../Renderer';

export const WarningField = ({ warning }: { warning: string }) => {
	return (
		<Alert plaintext warning mb={2}>
			<Renderer
				value={warning}
				schema={{
					type: 'string',
					format: 'markdown',
				}}
			/>
		</Alert>
	);
};


text:
package action

import (
	"context"
	"os"

	"github.com/justwatchcom/gopass/utils/jsonapi"
	"github.com/urfave/cli"
)

// JSONAPI reads a json message on stdin and responds on stdout
func (s *Action) JSONAPI(ctx context.Context, c *cli.Context) error {
	api := jsonapi.API{Store: s.Store, CliContext: c, Reader: os.Stdin, Writer: os.Stdout}
	if err := api.ReadAndRespond(ctx); err != nil {
		return api.RespondError(err)
	}
	return nil
}


text:
<?php
class SystemAuditTrailModel extends ORMSQLDatabaseModel
{
    const AUDIT_TYPE_ADDED_DATA = 0;
    const AUDIT_TYPE_UPDATED_DATA = 1;
    const AUDIT_TYPE_DELETED_DATA = 2;
    const AUDIT_TYPE_ROUTING = 4;
    const AUDIT_TYPE_SYSTEM = 5;

    private static $instance = false;
    private static $dataModel;

    public $database = '.audit_trail';
    private $auditTrailData;

    public function update()
    {
        throw new Exception('Cannot update audit trail');
    }

    public function delete()
    {
        throw new Exception('Cannot delete audit trail');
    }

    private function getInstance()
    {
        if(self::$instance === false)
        {
            self::$instance = Model::load('system.audit_trail');
            self::$dataModel = Model::load('system.audit_trail_data');
        }
        return self::$instance;
    }

    public static function log($params)
    {
        $model = self::getInstance();
        $params['user_id'] = $_SESSION['user_id'];
        $params['audit_date'] = time();
        $model->setData($params);
        $model->save();
    }

    public function preAddHook()
    {
        $this->auditTrailData = /*gzcompress(*/$this->datastore->data['data']/*)*/;
        unset($this->datastore->data['data']);
    }

    public function postAddHook($id, $data)
    {
        self::$dataModel->setData(
            array(
                'audit_trail_id' => $id,
                'data' => $this->auditTrailData,
            )
        );
        self::$dataModel->save();
    }
}


text:
using ImageApp.Utils;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ImageApp.UnitTests.Utils
{
    [TestClass]
    public class TextUtils_FitTests
    {
        private const int Limit = 5;

        [TestMethod]
        public void IfTextIsShorterThanLimitThenIsNotChanged()
        {
            const string text = "abc";
            var result = TextUtils.Fit(text, Limit);
            Assert.AreEqual(text, result);
        }

        [TestMethod]
        public void IfTextIsLongerThanLimitThenResultIsEndedThreeDots()
        {
            const string text = "abcdefghijk";
            const string expected = "ab...";
            var result = TextUtils.Fit(text, Limit);
            Assert.AreEqual(expected, result);
        }
    }
}


text:
namespace Hangman.Tests
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using Microsoft.VisualStudio.TestTools.UnitTesting;
    using Hangman.Common.Interfaces;
    using Hangman.Data.Repositories.PlayersRepositories;
    using Hangman.Models;

    [TestClass]
    public class PlayerUnitTests
    {
        private int timestamp;
        private int timestampCountdown;
        private PlayersFromDbRepository playersFromDb;

        [TestInitialize]
        public void InitializeTimestamp()
        {
            timestamp = int.Parse(DateTime.Now.ToString("MMddHHmmss"));
            timestampCountdown = int.MaxValue - timestamp;
            playersFromDb = new PlayersFromDbRepository();
        }

        [TestMethod]
        public void TestInsertPlayerInDbRepository()
        {
            string NewTestPlayerName = "NewTestPlayer " + timestamp;
            var player = new KeyValuePair<string, int>(NewTestPlayerName, timestamp);
            playersFromDb.InsertPlayerInDb(player);

            var newPlayersFromDb = new PlayersFromDbRepository();

            var listOfPlayers = newPlayersFromDb.Players;
            var lastPlayer = listOfPlayers[listOfPlayers.Count - 1];

            Assert.AreEqual(NewTestPlayerName, lastPlayer.Key);
            Assert.AreEqual(timestamp, lastPlayer.Value);
        }

        [TestMethod]
        public void TestUpdatePlayerInDbRepository()
        {
            string updateTestPlayerName = "UpdateTestPlayer";
            var player = new KeyValuePair<string, int>(updateTestPlayerName, timestampCountdown);
            playersFromDb.InsertPlayerInDb(player);

            var newPlayersFromDb = new PlayersFromDbRepository();

            var listOfPlayers = newPlayersFromDb.Players;
            var updatedPlayer =
                from p in listOfPlayers
                where p.Key == updateTestPlayerName
                select p.Value;

            Assert.AreEqual(timestampCountdown, updatedPlayer.ToArray()[0]);
        }

        [TestMethod]
        public void TestClonePlayer()
        {
            var player = new Player() { Name = "Gosho", MistakesCount = 2 };
            var score = new Scoreboard();
            var samePlayerNewGame = player.Clone() as Player;
            samePlayerNewGame.MistakesCount = 0;
            score.AddPlayer(samePlayerNewGame);

            var players = new List<IPlayer>(score.Players);

            Assert.AreEqual(player.Name, players[0].Name, "Name of the cloned person is not the same");
            Assert.AreEqual(0, players[0].MistakesCount, "Player's score was not overwritten!");
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void TestForWrongInitializationOfPlayerName()
        {
            var player = new Player() { Name = string.Empty, MistakesCount = 2 };
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void TestForWrongInitializationOfPlayerMistakesCount()
        {
            var player = new Player() { Name = "Gosho", MistakesCount = -2 };
        }
    }
}


text:
require 'blankslate'

class Sentry_Sender < BlankSlate

  attr_reader :scope, :on_method_missing

  def initialize scope, missing_method, &blok
    @scope = scope
    @on_method_missing = missing_method
    instance_eval(&blok) if block_given?
  end

  def method_missing name, *args, &blok
    scope.respond_to?(name) ?
      scope.send( name, *args, &blok ) :
      scope.send( on_method_missing, name, *args, &blok )
  end

end # === Sentry_Sender


text:
import { Component, OnInit } from '@angular/core';
@Component({
	selector: 'effi-footer',
	templateUrl: 'app/components/footer/footer.component.html',
	styleUrls: ['./app/components/footer/footer.css']
})
export class FooterComponent implements OnInit {
	ngOnInit() {
	// Mock todo: get 10,000 rows of data from the server
	}
}


text:
module Spree
  OptionType.class_eval do
    # We need to redefine the default_scope to include the tenant_id
    default_scope lambda {
      if OptionType.column_names.include?(:tenant_id)
        where( tenant_id: Tenant.current_tenant_id ).order( :position )
      end
    }
  end
end


text:
package com.atsebak.kernel.project.builder;

import com.atsebak.kernel.utils.KernelIcons;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.projectRoots.impl.ProjectJdkImpl;
import com.intellij.openapi.util.Computable;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class CppSdkType extends SdkType implements ApplicationComponent {
    public CppSdkType() {
        super("CppSdk");
    }

    public static CppSdkType getInstance() {
        return ApplicationManager.getApplication().getComponent(CppSdkType.class);
    }

    private static SdkModificator addSdkVersion(Sdk jdk) {
        SdkModificator sdkModificator = jdk.getSdkModificator();
        sdkModificator.setVersionString("xxx");
        return sdkModificator;
    }

    @Nullable
    public String suggestHomePath() {
        return null;
    }

    public boolean isValidSdkHome(String path) {
//    VirtualFile file = LocalFileSystem.getInstance().findFileByPath(path);
        return true; //TODO: file != null && (CppSupportSettings.isGccPath(file) || CppSupportSettings.isMsVcDirectory(file));
    }

    @Nullable
    public String getVersionString(String sdkHome) {
        return null;
    }

    public String suggestSdkName(String currentSdkName, String sdkHome) {
        return sdkHome.substring(sdkHome.lastIndexOf('/') + 1);
    }

    public void setupSdkPaths(Sdk sdk) {
    }

    public AdditionalDataConfigurable createAdditionalDataConfigurable(SdkModel sdkModel, SdkModificator sdkModificator) {
        return null;
    }

    public void saveAdditionalData(SdkAdditionalData additionalData, Element additional) {
    }

    public SdkAdditionalData loadAdditionalData(Element additional) {
        return null;
    }

    public String getPresentableName() {
        return "Cpp Sdk";
    }

    @NonNls
    @NotNull
    public String getComponentName() {
        return "CppTools.CppSdk";
    }

    public void initComponent() {
    }

    public void disposeComponent() {
    }

    @NotNull
    List<Sdk> getCppSdks() {
        List<Sdk> sdks = null;
        for (Sdk jdk : ProjectJdkTable.getInstance().getAllJdks()) {
            if (jdk.getSdkType() == this) {
                if (sdks == null) sdks = new ArrayList<Sdk>(1);
                sdks.add(jdk);
            }
        }
        return sdks != null ? sdks : Collections.<Sdk>emptyList();
    }

    public Sdk createOrGetSdkByPath(final String s) {
        for (Sdk jdk : getCppSdks()) {
            if (s.equals(jdk.getHomePath())) return jdk;
        }
        return ApplicationManager.getApplication().runWriteAction(new Computable<Sdk>() {
            public Sdk compute() {
                try {
                    Sdk jdk = new ProjectJdkImpl("Cpp SDK", getInstance());
                    SdkModificator sdkModificator = addSdkVersion(jdk);
                    sdkModificator.setHomePath(s);
                    sdkModificator.commitChanges();
                    ProjectJdkTable.getInstance().addJdk(jdk);
                    return jdk;
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    @Override
    public Icon getIcon() {
        return KernelIcons.Linux;
    }

    @Override
    public Icon getIconForAddAction() {
        return KernelIcons.Linux;
    }

    public boolean setupSdkPaths(Sdk sdk, SdkModel sdkModel) {
        SdkModificator sdkModificator = addSdkVersion(sdk);
        sdkModificator.commitChanges();
        return true;
    }
}


text:
package com.cloudera.whirr.cm.handler;

import static com.google.common.base.Predicates.and;
import static com.google.common.base.Predicates.containsPattern;

import java.util.Collections;
import java.util.Set;
import java.util.TreeSet;

import org.apache.commons.configuration.Configuration;
import org.apache.whirr.Cluster;
import org.apache.whirr.ClusterController;
import org.apache.whirr.ClusterSpec;
import org.junit.Assert;
import org.junit.Test;

import com.cloudera.whirr.cm.CmServerClusterInstance;
import com.cloudera.whirr.cm.cmd.BaseCommandCmServer;
import com.cloudera.whirr.cm.handler.cdh.CmCdhFlumeAgentHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHBaseMasterHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHBaseRegionServerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHdfsDataNodeHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHdfsHttpFsHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHdfsNameNodeHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHdfsSecondaryNameNodeHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHiveHCatalogHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHiveMetaStoreHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHiveServer2Handler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHueBeeswaxServerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhHueServerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhImpalaCatalogServerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhImpalaDaemonHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhImpalaStateStoreHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhMapReduceJobTrackerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhMapReduceTaskTrackerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhOozieServerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhSolrIndexerHBaseHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhSolrServerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhSparkMasterHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhSparkWorkerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhSqoopServerHandler;
import com.cloudera.whirr.cm.handler.cdh.CmCdhZookeeperServerHandler;
import com.cloudera.whirr.cm.server.CmServerServiceType;
import com.cloudera.whirr.cm.server.CmServerServiceTypeCms;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSortedSet;

public class CmServerHandlerTest extends BaseTestHandler {

  private static final int WHIRR_INSTANCE_TEMPLATE_NUM_SLAVES = 3;
  private static final String[] WHIRR_INSTANCE_TEMPLATE_ROLES_MASTER = { CmBalancerHandler.ROLE,
      CmCdhHdfsNameNodeHandler.ROLE, CmCdhHdfsSecondaryNameNodeHandler.ROLE, CmCdhHueServerHandler.ROLE,
      CmCdhHueBeeswaxServerHandler.ROLE, CmCdhMapReduceJobTrackerHandler.ROLE, CmCdhSparkMasterHandler.ROLE,
      CmCdhHBaseMasterHandler.ROLE, CmCdhHiveMetaStoreHandler.ROLE, CmCdhImpalaStateStoreHandler.ROLE,
      CmCdhImpalaCatalogServerHandler.ROLE, CmCdhOozieServerHandler.ROLE, CmCdhHiveServer2Handler.ROLE,
      CmCdhHiveHCatalogHandler.ROLE, CmCdhSqoopServerHandler.ROLE, CmCdhSolrServerHandler.ROLE,
      CmCdhHdfsHttpFsHandler.ROLE };
  private static final String[] WHIRR_INSTANCE_TEMPLATE_ROLES_SLAVES = { CmCdhHdfsDataNodeHandler.ROLE,
      CmCdhMapReduceTaskTrackerHandler.ROLE, CmCdhSparkWorkerHandler.ROLE, CmCdhZookeeperServerHandler.ROLE,
      CmCdhHBaseRegionServerHandler.ROLE, CmCdhImpalaDaemonHandler.ROLE, CmCdhFlumeAgentHandler.ROLE,
      CmCdhSolrIndexerHBaseHandler.ROLE, CmCdhHdfsHttpFsHandler.ROLE };
  private static final int WHIRR_INSTANCE_TEMPLATE_NUM_ROLES = WHIRR_INSTANCE_TEMPLATE_ROLES_MASTER.length
      + WHIRR_INSTANCE_TEMPLATE_NUM_SLAVES * WHIRR_INSTANCE_TEMPLATE_ROLES_SLAVES.length - 1;
  private static String WHIRR_INSTANCE_TEMPLATE_ALL = "1 " + CmServerHandler.ROLE + "+" + CmAgentHandler.ROLE + ",1 "
      + CmAgentHandler.ROLE;
  static {
    for (String role : WHIRR_INSTANCE_TEMPLATE_ROLES_MASTER) {
      WHIRR_INSTANCE_TEMPLATE_ALL += "+" + role;
    }
    WHIRR_INSTANCE_TEMPLATE_ALL += "," + WHIRR_INSTANCE_TEMPLATE_NUM_SLAVES + " " + CmAgentHandler.ROLE;
    for (String role : WHIRR_INSTANCE_TEMPLATE_ROLES_SLAVES) {
      WHIRR_INSTANCE_TEMPLATE_ALL += "+" + role;
    }
  }

  @Override
  protected Set<String> getInstanceRoles() {
    return ImmutableSortedSet.of(CmServerHandler.ROLE);
  }

  @Override
  protected Predicate<CharSequence> bootstrapPredicate() {
    return and(
        containsPattern("configure_hostnames"),
        and(containsPattern("install_database"),
            and(containsPattern("install_cm"),
                and(containsPattern("install_cm_java"), containsPattern("install_cm_server")))));
  }

  @Override
  protected Predicate<CharSequence> configurePredicate() {
    return containsPattern("configure_cm_server");
  }

  @Test
  public void testConfiguration() throws Exception {

    Configuration configuration = CmServerClusterInstance.getConfiguration(newClusterSpecForProperties(ImmutableMap.of(
        "whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",2 " + CmNodeHandler.ROLE)));
    Assert.assertEquals(
        "impala",
        configuration.getString(CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HDFS.getId().toLowerCase()
            + ".dfs_block_local_path_access_user"));
    Assert.assertEquals("/manager/agent/log/agent.log",
        CmServerClusterInstance.getConfiguration(newClusterSpecForProperties(Collections.<String, String> emptyMap()))
            .getString(CONFIG_WHIRR_INTERNAL_AGENT_LOG_FILE));
    Assert.assertEquals(
        "500000",
        configuration.getString(CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceTypeCms.CM.getId().toLowerCase()
            + ".parcel_distribute_rate_limit_kbs_per_second"));

    configuration = CmServerClusterInstance.getConfiguration(newClusterSpecForProperties(ImmutableMap
        .of("whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",2 " + CmNodeHandler.ROLE,
            CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HDFS.getId().toLowerCase()
                + ".dfs_block_local_path_access_user", "some_user", CONFIG_WHIRR_CM_CONFIG_PREFIX
                + CmServerServiceType.HDFS.getId().toLowerCase() + ".some_setting", "some_value",
            CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase()
                + ".some_other_setting", "some_other_value")));
    Assert.assertEquals(
        "some_user",
        configuration.getString(CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HDFS.getId().toLowerCase()
            + ".dfs_block_local_path_access_user"));
    Assert.assertEquals(
        "some_value",
        configuration.getString(CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HDFS.getId().toLowerCase()
            + ".some_setting"));
    Assert.assertEquals(
        "some_value",
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>(),
            CmServerServiceType.HDFS.getId(), null, "some_setting"));
    Assert.assertEquals("some_value", CmServerClusterInstance.getClusterConfiguration(configuration,
        new TreeSet<String>(), CmServerServiceType.HDFS_NAMENODE.getId(), CmServerServiceType.HDFS.getId(),
        "some_setting"));
    Assert.assertEquals("some_other_value", CmServerClusterInstance.getClusterConfiguration(configuration,
        new TreeSet<String>(), CmServerServiceType.HDFS_NAMENODE.getId(), CmServerServiceType.HDFS.getId(),
        "some_other_setting"));
    Assert.assertEquals(
        "mysql",
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>(),
            CmServerServiceTypeCms.CM.getId(), null, CONFIG_CM_DB_SUFFIX_TYPE));
    Assert.assertEquals("mysql", CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>(),
        CmServerServiceTypeCms.HOSTMONITOR.getId(), null, CONFIG_CM_DB_SUFFIX_TYPE));
    Assert.assertEquals("localhost:3306", CmServerClusterInstance.getClusterConfiguration(configuration,
        new TreeSet<String>(), CmServerServiceTypeCms.HOSTMONITOR.getId(), null, CONFIG_CM_DB_SUFFIX_HOST));
    Assert.assertEquals(
        "mysql",
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>(),
            CmServerServiceType.HIVE.getId(), null, CONFIG_CM_DB_SUFFIX_TYPE));
    Assert.assertEquals(
        "3306",
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>(),
            CmServerServiceType.HIVE.getId(), null, CONFIG_CM_DB_SUFFIX_PORT));
    boolean caught = false;
    try {
      Assert.assertEquals("some_other_value", CmServerClusterInstance.getClusterConfiguration(configuration,
          new TreeSet<String>(), CmServerServiceType.HDFS_NAMENODE.getId(), CmServerServiceType.HDFS.getId(),
          "some_unknown_setting"));
    } catch (Exception e) {
      caught = true;
    }
    Assert.assertTrue(caught);
    Assert.assertEquals(
        configuration.getString(CONFIG_WHIRR_INTERNAL_DATA_DIRS_DEFAULT)
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceTypeCms.NAVIGATOR.getId().toLowerCase() + ".mgmt_log_dir"),
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>())
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceTypeCms.NAVIGATOR.getId())
            .get("mgmt_log_dir"));
    Assert.assertEquals(
        configuration.getString(CONFIG_WHIRR_INTERNAL_DATA_DIRS_DEFAULT)
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list"),
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>())
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals(
        "/mnt/1"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/mnt/1"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals(
        "/mnt/1"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list")
            + ","
            + "/mnt/2"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/mnt/1", "/mnt/2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertNull(CmServerClusterInstance
        .getClusterConfiguration(configuration, ImmutableSortedSet.of("/mnt/1", "/mnt/2"))
        .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.MAPREDUCE_TASK_TRACKER.getId())
        .get(CONFIG_CM_TASKTRACKER_INSTRUMENTATION));

    configuration = CmServerClusterInstance.getConfiguration(newClusterSpecForProperties(ImmutableMap.of(
        "whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",2 " + CmNodeHandler.ROLE,
        CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceTypeCms.CM.getId().toLowerCase() + "."
            + CONFIG_CM_DB_SUFFIX_NAME, "cman", CONFIG_WHIRR_CM_CONFIG_PREFIX
            + CmServerServiceTypeCms.CM.getId().toLowerCase() + "." + CONFIG_CM_DB_SUFFIX_TYPE, "postgres",
        CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HIVE.getId().toLowerCase() + ".hive_metastore_"
            + CONFIG_CM_DB_SUFFIX_PORT, "9999", CONFIG_WHIRR_CM_CONFIG_PREFIX
            + CmServerServiceType.CLUSTER.getId().toLowerCase() + "." + CONFIG_CM_LICENSE_PROVIDED, "true")));
    Assert.assertEquals(
        "/data1"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceTypeCms.NAVIGATOR.getId().toLowerCase() + ".mgmt_log_dir"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/data1", "/data2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceTypeCms.NAVIGATOR.getId())
            .get("mgmt_log_dir"));
    Assert.assertEquals(
        "/data1"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list")
            + ",/data2"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/data1", "/data2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals(
        "org.apache.hadoop.mapred.TaskTrackerCmonInst",
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/mnt/1", "/mnt/2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.MAPREDUCE_TASK_TRACKER.getId())
            .get(CONFIG_CM_TASKTRACKER_INSTRUMENTATION));

    configuration = CmServerClusterInstance.getConfiguration(newClusterSpecForProperties(ImmutableMap.of(
        "whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",2 " + CmNodeHandler.ROLE,
        CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceTypeCms.CM.getId().toLowerCase() + "."
            + CONFIG_CM_DB_SUFFIX_NAME, "cman", CONFIG_WHIRR_CM_CONFIG_PREFIX
            + CmServerServiceTypeCms.CM.getId().toLowerCase() + "." + CONFIG_CM_DB_SUFFIX_TYPE, "postgres",
        CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HIVE.getId().toLowerCase() + ".hive_metastore_"
            + CONFIG_CM_DB_SUFFIX_PORT, "9999", CONFIG_WHIRR_CM_LICENSE_URI, "classpath:///"
            + CONFIG_WHIRR_DEFAULT_FILE)));
    Assert.assertEquals(
        "/data1"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceTypeCms.NAVIGATOR.getId().toLowerCase() + ".mgmt_log_dir"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/data1", "/data2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceTypeCms.NAVIGATOR.getId())
            .get("mgmt_log_dir"));
    Assert.assertEquals(
        "/data1"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list")
            + ",/data2"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/data1", "/data2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals(
        "org.apache.hadoop.mapred.TaskTrackerCmonInst",
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/mnt/1", "/mnt/2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.MAPREDUCE_TASK_TRACKER.getId())
            .get(CONFIG_CM_TASKTRACKER_INSTRUMENTATION));
    Assert.assertEquals("classpath:///" + CONFIG_WHIRR_DEFAULT_FILE,
        configuration.getString(CONFIG_WHIRR_CM_LICENSE_URI));

    configuration = CmServerClusterInstance.getConfiguration(newClusterSpecForProperties(ImmutableMap.of(
        "whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",2 " + CmNodeHandler.ROLE,
        CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceTypeCms.CM.getId().toLowerCase() + "."
            + CONFIG_CM_DB_SUFFIX_NAME, "cman", CONFIG_WHIRR_CM_CONFIG_PREFIX
            + CmServerServiceTypeCms.CM.getId().toLowerCase() + "." + CONFIG_CM_DB_SUFFIX_TYPE, "postgres",
        CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HIVE.getId().toLowerCase() + ".hive_metastore_"
            + CONFIG_CM_DB_SUFFIX_PORT, "9999")));
    Assert.assertEquals(
        "/tmp"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceTypeCms.NAVIGATOR.getId().toLowerCase() + ".mgmt_log_dir"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/tmp"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceTypeCms.NAVIGATOR.getId())
            .get("mgmt_log_dir"));
    Assert.assertEquals(
        "/tmp"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/tmp"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals(
        "/mnt/1"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list")
            + ",/mnt/2"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/mnt/1", "/mnt/2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals("postgres", CmServerClusterInstance.getClusterConfiguration(configuration,
        ImmutableSortedSet.of("/tmp"), CmServerServiceTypeCms.CM.getId(), null, CONFIG_CM_DB_SUFFIX_TYPE));
    Assert.assertEquals("mysql", CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>(),
        CmServerServiceTypeCms.HOSTMONITOR.getId(), null, CONFIG_CM_DB_SUFFIX_TYPE));
    Assert.assertEquals("localhost:3306", CmServerClusterInstance.getClusterConfiguration(configuration,
        new TreeSet<String>(), CmServerServiceTypeCms.HOSTMONITOR.getId(), null, CONFIG_CM_DB_SUFFIX_HOST));
    Assert.assertEquals(
        "mysql",
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>(),
            CmServerServiceType.HIVE.getId(), null, CONFIG_CM_DB_SUFFIX_TYPE));
    Assert.assertEquals(
        "9999",
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>(),
            CmServerServiceType.HIVE.getId(), null, CONFIG_CM_DB_SUFFIX_PORT));

    configuration = CmServerClusterInstance.getConfiguration(newClusterSpecForProperties(ImmutableMap.of(
        "whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",2 " + CmNodeHandler.ROLE,
        CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list",
        "/mynn")));
    Assert.assertEquals(
        "/mnt/1"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceTypeCms.NAVIGATOR.getId().toLowerCase() + ".mgmt_log_dir"),
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/mnt/1", "/mnt/2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceTypeCms.NAVIGATOR.getId())
            .get("mgmt_log_dir"));
    Assert.assertEquals(
        "/mynn",
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>())
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals(
        "/mynn",
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/mnt/1", "/mnt/2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals(
        configuration.getString(CONFIG_WHIRR_INTERNAL_DATA_DIRS_DEFAULT)
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_SECONDARY_NAMENODE.getId().toLowerCase() + ".fs_checkpoint_dir_list"),
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>())
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_SECONDARY_NAMENODE.getId())
            .get("fs_checkpoint_dir_list"));

    configuration = CmServerClusterInstance.getConfiguration(newClusterSpecForProperties(ImmutableMap.of(
        "whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",2 " + CmNodeHandler.ROLE,
        CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HDFS_NAMENODE.getId().toLowerCase() + ".dfs_name_dir_list",
        "/mynn", CONFIG_WHIRR_DATA_DIRS_ROOT, "/tmp")));
    Assert.assertEquals(
        "/mynn",
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>())
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals(
        "/mynn",
        CmServerClusterInstance.getClusterConfiguration(configuration, ImmutableSortedSet.of("/mnt/1", "/mnt/2"))
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_NAMENODE.getId())
            .get("dfs_name_dir_list"));
    Assert.assertEquals(
        "/data"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX
                + CmServerServiceType.HDFS_SECONDARY_NAMENODE.getId().toLowerCase() + ".fs_checkpoint_dir_list"),
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>())
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.HDFS_SECONDARY_NAMENODE.getId())
            .get("fs_checkpoint_dir_list"));

    Assert.assertEquals(
        null,
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>())
            .get(CmServerClusterInstance.CM_API_BASE_VERSION).get(CmServerServiceType.IMPALA_DAEMON.getId())
            .get("audit_event_log_dir"));
    Assert.assertEquals(
        "/data"
            + configuration.getString(CONFIG_WHIRR_INTERNAL_CM_CONFIG_DEFAULT_PREFIX + "5."
                + CmServerServiceType.IMPALA_DAEMON.getId().toLowerCase() + ".audit_event_log_dir"),
        CmServerClusterInstance.getClusterConfiguration(configuration, new TreeSet<String>()).get("5")
            .get(CmServerServiceType.IMPALA_DAEMON.getId()).get("audit_event_log_dir"));

  }

  @Test
  public void testNodes() throws Exception {
    Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        "1 " + CmServerHandler.ROLE + ",2 " + CmNodeHandler.ROLE))));
  }

  @Test
  public void testAgents() throws Exception {
    Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        "1 " + CmServerHandler.ROLE + ",2 " + CmAgentHandler.ROLE))));
  }

  @Test
  public void testNodesAndAgents() throws Exception {
    Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        "1 " + CmServerHandler.ROLE + ",2 " + CmNodeHandler.ROLE + ",2 " + CmAgentHandler.ROLE))));
  }

  @Test
  public void testNodesAndAgentsAndCluster() throws Exception {
    Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        WHIRR_INSTANCE_TEMPLATE_ALL))));
    Assert.assertTrue(countersAssertAndReset(WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, WHIRR_INSTANCE_TEMPLATE_NUM_ROLES,
        WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, 0));
  }

  @Test
  public void testNodesAndAgentsAndClusterLifecycle() throws Exception {
    ClusterSpec clusterSpec = newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        WHIRR_INSTANCE_TEMPLATE_ALL));
    ClusterController controller = getController(clusterSpec);
    Cluster cluster = launchWithClusterSpecAndWithController(clusterSpec, controller);
    Assert.assertNotNull(cluster);
    Assert.assertTrue(countersAssertAndReset(WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, WHIRR_INSTANCE_TEMPLATE_NUM_ROLES,
        WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, 0));
    Assert.assertNotNull(controller.startServices(clusterSpec, cluster));
    Assert.assertTrue(countersAssertAndReset(0, 0, WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, 0));
    Assert.assertNotNull(controller.stopServices(clusterSpec, cluster));
    Assert.assertTrue(countersAssertAndReset(0, 0, 0, WHIRR_INSTANCE_TEMPLATE_NUM_ROLES));
    Assert.assertNotNull(controller.stopServices(clusterSpec, cluster));
    Assert.assertTrue(countersAssertAndReset(0, 0, 0, WHIRR_INSTANCE_TEMPLATE_NUM_ROLES));
  }

  @Test
  public void testNodesAndAgentsAndClusterBootstrapMultiCluster() throws Exception {
    ClusterSpec clusterSpec = newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        WHIRR_INSTANCE_TEMPLATE_ALL));
    ClusterController controller = getController(clusterSpec);
    Cluster cluster = controller.bootstrapCluster(clusterSpec);

    ClusterSpec clusterSpecTwo = newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        WHIRR_INSTANCE_TEMPLATE_ALL));
    clusterSpecTwo.setVersion("different-version");
    ClusterController controllerTwo = getController(clusterSpecTwo);
    Cluster clusterTwo = controllerTwo.bootstrapCluster(clusterSpecTwo);

    Assert.assertNotNull(cluster);
    Assert.assertNotNull(clusterTwo);
  }

  @Test
  public void testNodesAndAgentsAndClusterLifecycleFilteredHdfs() throws Exception {
    ClusterSpec clusterSpec = newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        WHIRR_INSTANCE_TEMPLATE_ALL));
    Set<String> roles = BaseCommandCmServer.filterRoles(CmCdhHdfsNameNodeHandler.ROLE);
    ClusterController controller = getController(clusterSpec);
    Cluster cluster = launchWithClusterSpecAndWithController(clusterSpec, controller);
    Assert.assertNotNull(cluster);
    Assert.assertTrue(countersAssertAndReset(WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, WHIRR_INSTANCE_TEMPLATE_NUM_ROLES,
        WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, 0));
    Assert.assertNotNull(controller.startServices(clusterSpec, cluster, roles, new TreeSet<String>()));
    Assert.assertTrue(countersAssertAndReset(0, 0, 9, 0));
    Assert.assertNotNull(controller.stopServices(clusterSpec, cluster, roles, new TreeSet<String>()));
    Assert.assertTrue(countersAssertAndReset(0, 0, 0, 9));
    Assert.assertNotNull(controller.stopServices(clusterSpec, cluster, roles, new TreeSet<String>()));
    Assert.assertTrue(countersAssertAndReset(0, 0, 0, 9));
  }

  @Test
  public void testNodesAndAgentsAndClusterNotAuto() throws Exception {
    Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        WHIRR_INSTANCE_TEMPLATE_ALL, CONFIG_WHIRR_AUTO, Boolean.FALSE.toString()))));
  }

  @Test
  public void testNodesAndAgentsAndClusterFirewall() throws Exception {
    Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        WHIRR_INSTANCE_TEMPLATE_ALL, CONFIG_WHIRR_AUTO, Boolean.FALSE.toString()))));
  }

  @Test
  public void testNodesAndAgentsAndClusterConfiguration() throws Exception {
    Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        WHIRR_INSTANCE_TEMPLATE_ALL, CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HDFS.getId().toLowerCase()
            + ".some_setting", "some_value"))));
    Assert.assertTrue(countersAssertAndReset(WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, WHIRR_INSTANCE_TEMPLATE_NUM_ROLES,
        WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, 0));
  }

  @Test
  public void testNodesAndAgentsAndClusterConfigurationOverride() throws Exception {
    Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates",
        WHIRR_INSTANCE_TEMPLATE_ALL, CONFIG_WHIRR_CM_CONFIG_PREFIX + CmServerServiceType.HDFS.getId().toLowerCase()
            + ".dfs_block_local_path_access_user", "someuser"))));
    Assert.assertTrue(countersAssertAndReset(WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, WHIRR_INSTANCE_TEMPLATE_NUM_ROLES,
        WHIRR_INSTANCE_TEMPLATE_NUM_ROLES, 0));
  }

  @Test
  public void testNodesAndAgentsAndClusterConfigurationInvalid() throws Exception {
    boolean caught = false;
    try {
      Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of(
          "whirr.instance-templates", WHIRR_INSTANCE_TEMPLATE_ALL, CONFIG_WHIRR_CM_CONFIG_PREFIX
              + CmServerServiceType.HDFS.getId().toLowerCase(), "some_value"))));
    } catch (Exception e) {
      caught = true;
    }
    Assert.assertTrue(caught);
  }

  @Test
  public void testNoAgentsAndCluster() throws Exception {
    boolean caught = false;
    try {
      Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of(
          "whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",2 " + CmCdhHdfsNameNodeHandler.ROLE))));
    } catch (Exception e) {
      caught = true;
    }
    Assert.assertTrue(caught);
  }

  @Test
  public void testAgentsAndMultipleNameNodes() throws Exception {
    boolean caught = false;
    try {
      Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of(
          "whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",1 " + CmAgentHandler.ROLE + "+"
              + CmCdhHdfsNameNodeHandler.ROLE + ",1 " + CmAgentHandler.ROLE + "+" + CmCdhHdfsNameNodeHandler.ROLE))));
    } catch (Exception e) {
      caught = true;
    }
    Assert.assertTrue(caught);
  }

  @Test
  public void testMultipleCmServers() throws Exception {
    boolean caught = false;
    try {
      Assert.assertNotNull(launchWithClusterSpec(newClusterSpecForProperties(ImmutableMap.of(
          "whirr.instance-templates", "1 " + CmServerHandler.ROLE + ",1 " + CmServerHandler.ROLE))));
    } catch (Exception e) {
      caught = true;
    }
    Assert.assertTrue(caught);
  }

  @Test
  public void testInValidClusterName() throws Exception {
    boolean caught = false;
    try {
      ClusterSpec clusterSpec = newClusterSpecForProperties(ImmutableMap.of("whirr.instance-templates", "1 "
          + CmServerHandler.ROLE + ",1 " + CmAgentHandler.ROLE + ",1 " + CmAgentHandler.ROLE + "+"
          + CmCdhHdfsNameNodeHandler.ROLE));
      clusterSpec.getConfiguration()
          .setProperty(ClusterSpec.Property.CLUSTER_NAME.getConfigName(), "some_cluster_name");
      Assert.assertNotNull(launchWithClusterSpec(clusterSpec));
    } catch (Exception e) {
      caught = true;
    }
    Assert.assertTrue(caught);
  }

}


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using DotNetRuleEngine.Extensions;
using DotNetRuleEngine.Interface;

namespace DotNetRuleEngine.Services
{
    internal sealed class AsyncRuleService<T> where T : class, new()
    {
        private readonly IEnumerable<IRuleAsync<T>> _rules;
        private readonly IRuleEngineConfiguration<T> _ruleEngineConfiguration;
        private readonly RxRuleService<IRuleAsync<T>, T> _rxRuleService;
        private readonly ConcurrentBag<IRuleResult> _asyncRuleResults = new ConcurrentBag<IRuleResult>();
        private readonly ConcurrentBag<Task<IRuleResult>> _parallelRuleResults = new ConcurrentBag<Task<IRuleResult>>();

        public AsyncRuleService(IEnumerable<IRuleAsync<T>> rules,
            IRuleEngineConfiguration<T> ruleEngineTerminated)
        {
            _rules = rules;
            _rxRuleService = new RxRuleService<IRuleAsync<T>, T>(_rules);
            _ruleEngineConfiguration = ruleEngineTerminated;
        }

        public async Task InvokeAsync()
        {
            await ExecuteAsyncRules(_rxRuleService.FilterRxRules(_rules));
        }

        public async Task<IEnumerable<IRuleResult>> GetAsyncRuleResultsAsync()
        {
            await Task.WhenAll(_parallelRuleResults);

            Parallel.ForEach(_parallelRuleResults, rule =>
            {
                rule.Result.AssignRuleName(rule.GetType().Name);
                AddToAsyncRuleResults(rule.Result);
            });

            return _asyncRuleResults;
        }

        private async Task ExecuteAsyncRules(IEnumerable<IRuleAsync<T>> rules)
        {
            await ExecuteParallelRules(rules);

            foreach (var rule in OrderByExecutionOrder(rules))
            {
                await InvokeNestedRulesAsync(rule.Configuration.InvokeNestedRulesFirst, rule);

                if (rule.CanInvoke() && !_ruleEngineConfiguration.IsRuleEngineTerminated())
                {
                    try
                    {
                        await InvokeProactiveRulesAsync(rule);

                        AddToAsyncRuleResults(await ExecuteRuleAsync(rule));
                        rule.UpdateRuleEngineConfiguration(_ruleEngineConfiguration);

                        await InvokeReactiveRulesAsync(rule);
                    }
                    catch (Exception exception)
                    {
                        rule.UnhandledException = exception;

                        if (_rxRuleService.GetExceptionRules().ContainsKey(rule.GetType()))
                        {
                            await InvokeExceptionRulesAsync(rule);
                        }
                        else
                        {
                            var globalExceptionHandler = _rules.GetGlobalExceptionHandler();

                            if (globalExceptionHandler is IRuleAsync<T> ruleAsync)
                            {
                                globalExceptionHandler.UnhandledException = exception;
                                await ExecuteAsyncRules(new List<IRuleAsync<T>> { ruleAsync });
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }

                }

                await InvokeNestedRulesAsync(!rule.Configuration.InvokeNestedRulesFirst, rule);
            }
        }

        private async Task ExecuteParallelRules(IEnumerable<IRuleAsync<T>> rules)
        {
            foreach (var rule in GetParallelRules(rules))
            {
                await InvokeNestedRulesAsync(rule.Configuration.InvokeNestedRulesFirst, rule);

                if (rule.CanInvoke() && !_ruleEngineConfiguration.IsRuleEngineTerminated())
                {
                    await InvokeProactiveRulesAsync(rule);

                    _parallelRuleResults.Add(await Task.Factory.StartNew(async () =>
                    {
                        IRuleResult ruleResult = null;

                        try
                        {
                            ruleResult = await ExecuteRuleAsync(rule);
                        }
                        catch (Exception exception)
                        {
                            rule.UnhandledException = exception;
                            if (_rxRuleService.GetExceptionRules().ContainsKey(rule.GetType()))
                            {
                                await InvokeExceptionRulesAsync(rule);
                            }
                            else
                            {
                                var globalExceptionHandler = _rules.GetGlobalExceptionHandler();

                                if (globalExceptionHandler is IRuleAsync<T> ruleAsync)
                                {
                                    globalExceptionHandler.UnhandledException = exception;
                                    await ExecuteAsyncRules(new List<IRuleAsync<T>> { ruleAsync });
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }

                        return ruleResult;

                    }, rule.ParallelConfiguration.CancellationTokenSource?.Token ?? CancellationToken.None,
                        rule.ParallelConfiguration.TaskCreationOptions,
                        rule.ParallelConfiguration.TaskScheduler));

                    await InvokeReactiveRulesAsync(rule);
                }

                await InvokeNestedRulesAsync(!rule.Configuration.InvokeNestedRulesFirst, rule);
            }
        }

        private static async Task<IRuleResult> ExecuteRuleAsync(IRuleAsync<T> rule)
        {
            await rule.BeforeInvokeAsync();

            if (rule.IsParallel && rule.ParallelConfiguration.CancellationTokenSource != null &&
                rule.ParallelConfiguration.CancellationTokenSource.Token.IsCancellationRequested)
            {
                return null;
            }

            var ruleResult = await rule.InvokeAsync();

            await rule.AfterInvokeAsync();

            ruleResult.AssignRuleName(rule.GetType().Name);

            return ruleResult;
        }

        private async Task InvokeReactiveRulesAsync(IRuleAsync<T> asyncRule)
        {
            if (_rxRuleService.GetReactiveRules().ContainsKey(asyncRule.GetType()))
            {
                await ExecuteAsyncRules(_rxRuleService.GetReactiveRules()[asyncRule.GetType()]);
            }
        }

        private async Task InvokeProactiveRulesAsync(IRuleAsync<T> asyncRule)
        {
            if (_rxRuleService.GetProactiveRules().ContainsKey(asyncRule.GetType()))
            {
                await ExecuteAsyncRules(_rxRuleService.GetProactiveRules()[asyncRule.GetType()]);
            }
        }

        private async Task InvokeExceptionRulesAsync(IRuleAsync<T> asyncRule)
        {
            var exceptionRules =
                _rxRuleService.GetExceptionRules()[asyncRule.GetType()]
                    .Select(rule =>
                    {
                        rule.UnhandledException = asyncRule.UnhandledException;
                        return rule;
                    }).ToList();

            await ExecuteAsyncRules(exceptionRules);
        }

        private async Task InvokeNestedRulesAsync(bool invokeNestedRules, IRuleAsync<T> rule)
        {
            if (invokeNestedRules && rule.IsNested)
            {
                await ExecuteAsyncRules(_rxRuleService.FilterRxRules(rule.GetRules().OfType<IRuleAsync<T>>().ToList()));
            }
        }

        private void AddToAsyncRuleResults(IRuleResult ruleResult)
        {
            if (ruleResult != null) _asyncRuleResults.Add(ruleResult);
        }

        private static IEnumerable<IRuleAsync<T>> OrderByExecutionOrder(IEnumerable<IRuleAsync<T>> rules)
        {
            return rules.GetRulesWithExecutionOrder().OfType<IRuleAsync<T>>()
                    .Concat(rules.GetRulesWithoutExecutionOrder(rule => !((IRuleAsync<T>)rule).IsParallel).OfType<IRuleAsync<T>>());
        }

        private static IEnumerable<IRuleAsync<T>> GetParallelRules(IEnumerable<IRuleAsync<T>> rules)
        {
            return rules.Where(r => r.IsParallel && !r.Configuration.ExecutionOrder.HasValue)
                .AsParallel();
        }
    }
}


text:
from google.protobuf import descriptor
from google.protobuf import message
from google.protobuf import reflection
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)

DESCRIPTOR = descriptor.FileDescriptor(
  name='slop.proto',
  package='voldemort',
  serialized_pb='\n\nslop.proto\x12\tvoldemort\"f\n\x04Slop\x12\r\n\x05store\x18\x01 \x01(\t\x12\x11\n\toperation\x18\x02 \x01(\t\x12\x0b\n\x03key\x18\x03 \x01(\x0c\x12\r\n\x05value\x18\x04 \x01(\x0c\x12\x0f\n\x07node_id\x18\x05 \x01(\x05\x12\x0f\n\x07\x61rrived\x18\x06 \x01(\x03\x42\'\n\x17voldemort.serializationB\nVSlopProtoH\x01')

_SLOP = descriptor.Descriptor(
  name='Slop',
  full_name='voldemort.Slop',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    descriptor.FieldDescriptor(
      name='store', full_name='voldemort.Slop.store', index=0,
      number=1, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=unicode("", "utf-8"),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    descriptor.FieldDescriptor(
      name='operation', full_name='voldemort.Slop.operation', index=1,
      number=2, type=9, cpp_type=9, label=1,
      has_default_value=False, default_value=unicode("", "utf-8"),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    descriptor.FieldDescriptor(
      name='key', full_name='voldemort.Slop.key', index=2,
      number=3, type=12, cpp_type=9, label=1,
      has_default_value=False, default_value="",
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    descriptor.FieldDescriptor(
      name='value', full_name='voldemort.Slop.value', index=3,
      number=4, type=12, cpp_type=9, label=1,
      has_default_value=False, default_value="",
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    descriptor.FieldDescriptor(
      name='node_id', full_name='voldemort.Slop.node_id', index=4,
      number=5, type=5, cpp_type=1, label=1,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    descriptor.FieldDescriptor(
      name='arrived', full_name='voldemort.Slop.arrived', index=5,
      number=6, type=3, cpp_type=2, label=1,
      has_default_value=False, default_value=0,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  extension_ranges=[],
  serialized_start=25,
  serialized_end=127,
)

class Slop(message.Message):
  __metaclass__ = reflection.GeneratedProtocolMessageType
  DESCRIPTOR = _SLOP

  # @@protoc_insertion_point(class_scope:voldemort.Slop)

# @@protoc_insertion_point(module_scope)