text:
from decimal import Decimal

import graphene
import pytest
from mock import patch

from .....order import OrderEvents
from .....payment import TransactionAction
from .....payment.interface import TransactionActionData
from .....payment.models import TransactionItem
from ....core.enums import TransactionRequestActionErrorCode
from ....tests.utils import assert_no_permission, get_graphql_content
from ...enums import TransactionActionEnum

MUTATION_TRANSACTION_REQUEST_ACTION = """
mutation TransactionRequestAction(
    $id: ID!,
    $action_type: TransactionActionEnum!,
    $amount: PositiveDecimal
    ){
    transactionRequestAction(
            id: $id,
            actionType: $action_type,
            amount: $amount
        ){
        transaction{
                id
                actions
                reference
                type
                status
                modifiedAt
                createdAt
                authorizedAmount{
                    amount
                    currency
                }
                voidedAmount{
                    currency
                    amount
                }
                chargedAmount{
                    currency
                    amount
                }
                refundedAmount{
                    currency
                    amount
                }
        }
        errors{
            field
            message
            code
        }
    }
}
"""

@pytest.mark.parametrize(
    "charge_amount, expected_called_charge_amount",
    [
        (Decimal("8.00"), Decimal("8.00")),
        (None, Decimal("10.00")),
        (Decimal("100"), Decimal("10.00")),
    ],
)
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
def test_transaction_request_charge_action_for_order(
    mocked_payment_action_request,
    mocked_is_active,
    charge_amount,
    expected_called_charge_amount,
    order_with_lines,
    app_api_client,
    permission_manage_payments,
):
    # given
    mocked_is_active.return_value = True

    transaction = TransactionItem.objects.create(
        status="Authorized",
        type="Credit card",
        reference="PSP ref",
        available_actions=["charge", "void"],
        currency="USD",
        order_id=order_with_lines.pk,
        authorized_value=Decimal("10"),
    )

    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.CHARGE.name,
        "amount": charge_amount,
    }

    # when
    response = app_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION,
        variables,
        permissions=[permission_manage_payments],
    )

    # then
    get_graphql_content(response)

    assert mocked_is_active.called
    mocked_payment_action_request.assert_called_once_with(
        TransactionActionData(
            transaction=transaction,
            action_type=TransactionAction.CHARGE,
            action_value=expected_called_charge_amount,
        ),
        channel_slug=order_with_lines.channel.slug,
    )

    event = order_with_lines.events.first()
    assert event.type == OrderEvents.TRANSACTION_CAPTURE_REQUESTED
    assert Decimal(event.parameters["amount"]) == expected_called_charge_amount
    assert event.parameters["reference"] == transaction.reference

@pytest.mark.parametrize(
    "refund_amount, expected_called_refund_amount",
    [
        (Decimal("8.00"), Decimal("8.00")),
        (None, Decimal("10.00")),
        (Decimal("100"), Decimal("10.00")),
    ],
)
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
def test_transaction_request_refund_action_for_order(
    mocked_payment_action_request,
    mocked_is_active,
    refund_amount,
    expected_called_refund_amount,
    order_with_lines,
    app_api_client,
    permission_manage_payments,
):
    # given
    mocked_is_active.return_value = True

    transaction = TransactionItem.objects.create(
        status="Captured",
        type="Credit card",
        reference="PSP ref",
        available_actions=["refund"],
        currency="USD",
        order_id=order_with_lines.pk,
        charged_value=Decimal("10"),
    )

    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.REFUND.name,
        "amount": refund_amount,
    }

    # when
    response = app_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION,
        variables,
        permissions=[permission_manage_payments],
    )

    # then
    get_graphql_content(response)

    assert mocked_is_active.called
    mocked_payment_action_request.assert_called_once_with(
        TransactionActionData(
            transaction=transaction,
            action_type=TransactionAction.REFUND,
            action_value=expected_called_refund_amount,
        ),
        channel_slug=order_with_lines.channel.slug,
    )

    event = order_with_lines.events.first()
    assert event.type == OrderEvents.TRANSACTION_REFUND_REQUESTED
    assert Decimal(event.parameters["amount"]) == expected_called_refund_amount
    assert event.parameters["reference"] == transaction.reference

@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
def test_transaction_request_void_action_for_order(
    mocked_payment_action_request,
    mocked_is_active,
    order_with_lines,
    app_api_client,
    permission_manage_payments,
):
    # given
    mocked_is_active.return_value = True

    transaction = TransactionItem.objects.create(
        status="Authorized",
        type="Credit card",
        reference="PSP ref",
        available_actions=["charge", "void"],
        currency="USD",
        order_id=order_with_lines.pk,
        authorized_value=Decimal("10"),
    )
    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.VOID.name,
    }

    # when
    response = app_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION,
        variables,
        permissions=[permission_manage_payments],
    )

    # then
    get_graphql_content(response)

    assert mocked_is_active.called
    mocked_payment_action_request.assert_called_once_with(
        TransactionActionData(
            transaction=transaction,
            action_type=TransactionAction.VOID,
            action_value=None,
        ),
        channel_slug=order_with_lines.channel.slug,
    )

    event = order_with_lines.events.first()
    assert event.type == OrderEvents.TRANSACTION_VOID_REQUESTED
    assert event.parameters["reference"] == transaction.reference

@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
def test_transaction_request_void_action_for_checkout(
    mocked_payment_action_request,
    mocked_is_active,
    checkout,
    app_api_client,
    permission_manage_payments,
):
    # given
    mocked_is_active.return_value = True

    transaction = TransactionItem.objects.create(
        status="Authorized",
        type="Credit card",
        reference="PSP ref",
        available_actions=["charge", "void"],
        currency="USD",
        checkout_id=checkout.pk,
        authorized_value=Decimal("10"),
    )
    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.VOID.name,
    }

    # when
    response = app_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION,
        variables,
        permissions=[permission_manage_payments],
    )

    # then
    get_graphql_content(response)

    assert mocked_is_active.called
    mocked_payment_action_request.assert_called_once_with(
        TransactionActionData(
            transaction=transaction,
            action_type=TransactionAction.VOID,
            action_value=None,
        ),
        channel_slug=checkout.channel.slug,
    )

@pytest.mark.parametrize(
    "charge_amount, expected_called_charge_amount",
    [
        (Decimal("8.00"), Decimal("8.00")),
        (None, Decimal("10.00")),
        (Decimal("100"), Decimal("10.00")),
    ],
)
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
def test_transaction_request_charge_action_for_checkout(
    mocked_payment_action_request,
    mocked_is_active,
    charge_amount,
    expected_called_charge_amount,
    checkout,
    app_api_client,
    permission_manage_payments,
):
    # given
    mocked_is_active.return_value = True

    transaction = TransactionItem.objects.create(
        status="Authorized",
        type="Credit card",
        reference="PSP ref",
        available_actions=["charge", "void"],
        currency="USD",
        checkout_id=checkout.pk,
        authorized_value=Decimal("10"),
    )

    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.CHARGE.name,
        "amount": charge_amount,
    }

    # when
    response = app_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION,
        variables,
        permissions=[permission_manage_payments],
    )

    # then
    get_graphql_content(response)

    assert mocked_is_active.called
    mocked_payment_action_request.assert_called_once_with(
        TransactionActionData(
            transaction=transaction,
            action_type=TransactionAction.CHARGE,
            action_value=expected_called_charge_amount,
        ),
        channel_slug=checkout.channel.slug,
    )

@pytest.mark.parametrize(
    "refund_amount, expected_called_refund_amount",
    [
        (Decimal("8.00"), Decimal("8.00")),
        (None, Decimal("10.00")),
        (Decimal("100"), Decimal("10.00")),
    ],
)
@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
def test_transaction_request_refund_action_for_checkout(
    mocked_payment_action_request,
    mocked_is_active,
    refund_amount,
    expected_called_refund_amount,
    checkout,
    app_api_client,
    permission_manage_payments,
):
    # given
    mocked_is_active.return_value = True

    transaction = TransactionItem.objects.create(
        status="Captured",
        type="Credit card",
        reference="PSP ref",
        available_actions=["refund"],
        currency="USD",
        checkout_id=checkout.pk,
        charged_value=Decimal("10"),
    )

    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.REFUND.name,
        "amount": refund_amount,
    }

    # when
    response = app_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION,
        variables,
        permissions=[permission_manage_payments],
    )

    # then
    get_graphql_content(response)

    assert mocked_is_active.called
    mocked_payment_action_request.assert_called_once_with(
        TransactionActionData(
            transaction=transaction,
            action_type=TransactionAction.REFUND,
            action_value=expected_called_refund_amount,
        ),
        channel_slug=checkout.channel.slug,
    )

@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
def test_transaction_request_uses_handle_payment_permission(
    mocked_payment_action_request,
    mocked_is_active,
    checkout,
    app_api_client,
    permission_manage_payments,
):
    # given
    mocked_is_active.return_value = True

    transaction = TransactionItem.objects.create(
        status="Captured",
        type="Credit card",
        reference="PSP ref",
        available_actions=["refund"],
        currency="USD",
        checkout_id=checkout.pk,
        charged_value=Decimal("10"),
    )
    refund_amount = Decimal("1")
    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.REFUND.name,
        "amount": refund_amount,
    }

    # when
    response = app_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION,
        variables,
        permissions=[permission_manage_payments],
    )

    # then
    get_graphql_content(response)

    assert mocked_is_active.called
    mocked_payment_action_request.assert_called_once_with(
        TransactionActionData(
            transaction=transaction,
            action_type=TransactionAction.REFUND,
            action_value=refund_amount,
        ),
        channel_slug=checkout.channel.slug,
    )

@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
@patch("saleor.plugins.manager.PluginsManager.transaction_action_request")
def test_transaction_request_uses_manage_orders_permission(
    mocked_payment_action_request,
    mocked_is_active,
    order,
    app_api_client,
    permission_manage_orders,
):
    # given
    mocked_is_active.return_value = True

    transaction = TransactionItem.objects.create(
        status="Captured",
        type="Credit card",
        reference="PSP ref",
        available_actions=["refund"],
        currency="USD",
        order_id=order.pk,
        charged_value=Decimal("10"),
    )
    refund_amount = Decimal("1")
    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.REFUND.name,
        "amount": refund_amount,
    }

    # when
    response = app_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION,
        variables,
        permissions=[permission_manage_orders],
    )

    # then
    get_graphql_content(response)

    assert mocked_is_active.called
    mocked_payment_action_request.assert_called_once_with(
        TransactionActionData(
            transaction=transaction,
            action_type=TransactionAction.REFUND,
            action_value=refund_amount,
        ),
        channel_slug=order.channel.slug,
    )

def test_transaction_request_action_missing_permission(
    app_api_client, order_with_lines
):
    # given

    transaction = TransactionItem.objects.create(
        status="Authorized",
        type="Credit card",
        reference="PSP ref",
        available_actions=["charge", "void"],
        currency="USD",
        order_id=order_with_lines.pk,
        authorized_value=Decimal("10"),
    )
    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.VOID.name,
    }

    # when
    response = app_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION, variables, permissions=[]
    )

    # then
    assert_no_permission(response)

@patch("saleor.plugins.manager.PluginsManager.is_event_active_for_any_plugin")
def test_transaction_request_action_missing_event(
    mocked_is_active, staff_api_client, permission_manage_payments, order
):
    # given
    authorization_value = Decimal("10")
    transaction = TransactionItem.objects.create(
        status="Authorized",
        type="Credit card",
        reference="PSP ref",
        available_actions=["charge", "void"],
        currency="USD",
        order_id=order.pk,
        authorized_value=authorization_value,
    )
    mocked_is_active.return_value = False

    variables = {
        "id": graphene.Node.to_global_id("TransactionItem", transaction.pk),
        "action_type": TransactionActionEnum.VOID.name,
    }

    # when
    response = staff_api_client.post_graphql(
        MUTATION_TRANSACTION_REQUEST_ACTION,
        variables,
        permissions=[
            permission_manage_payments,
        ],
    )

    # then
    content = get_graphql_content(response)
    data = content["data"]["transactionRequestAction"]
    assert len(data["errors"]) == 1
    assert data["errors"][0]["message"] == (
        "No app or plugin is configured to handle payment action requests."
    )
    code_enum = TransactionRequestActionErrorCode
    assert data["errors"][0]["code"] == (
        code_enum.MISSING_TRANSACTION_ACTION_REQUEST_WEBHOOK.name
    )

    assert mocked_is_active.called


text:
std::string getTime() {
    std::time_t stamp;
    struct tm* tm_info;
    std::time(&stamp);
    tm_info = std::localtime(&stamp);
    char buffer[26];
    std::strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);

    return std::string(buffer);
}

void changeColor(int level) {
#ifdef __linux__
    if (level == fogel::core::INFO) {
        std::cout << "\e[1;32m";
    } else if (level == fogel::core::WARN) {
        std::cout << "\e[1;33m";
    } else if (level == fogel::core::ERROR) {
        std::cout << "\e[1;31m";
    } else {
        std::cout << "\e[0m";
    }
#elif __win32
#error Copy and Paste implentation. NOT TESTED!
    static HWHANDLE handle = NULL;
    static WORD saved_attributes = 0;
    if (handle == NULL) {
        handle = GetStdHandle(STD_OUTPUT_NORMAL);
    }

    if (saved_attributes == 0) {
        CONSOLE_SCREEN_BUFFER_INFO buf;
        GetConsoleScreenBufferInfo(handle, &buf);
        saved_attributes = buf.wAttributes;
    }

    if (level == fogel::core::INFO) {
        SetConsoleTextAttribute(handle, FOREGROUND_GREEN);
    } else if (level == fogel::core::WARN) {
        SetConsoleTextAttribute(hamdle, FOREHROUND_YELLOW);
    } else if (level == fogel::core::ERROR) {
        SetConsoleTextAttribute(handle, FOREGROUND_RED);
    } else {
        SetConsoleTextAttribute(handle, saved_attributes);
        saved_attributes = 0;
    }
#endif
}

fogel::core::Log::Log() {
    mOutput = &std::cout;
    mMask = INFO | WARN | ERROR;
}

void fogel::core::Log::log(LogLevel level, std::string msg) {
    if ((level & mMask) == level) {
        std::string name;

        switch (level) {
        case INFO:
            name = "INFO";
            break;
        case WARN:
            name = "WARN";
            break;
        case ERROR:
            name = "ERROR";
            break;
        default:
            name = "ERROR";
            break;
        }

        *mOutput << getTime();

        if (mOutput == &std::cout) {
            changeColor(level);
        }

        *mOutput << " [" + name + "]";

        if (mOutput == &std::cout) {
            changeColor(0);
        }

        *mOutput << ": " << msg << std::endl;
    }
}

void fogel::core::Log::info(std::string msg) {
    log(INFO, msg);
}

void fogel::core::Log::warn(std::string msg) {
    log(WARN, msg);
}

void fogel::core::Log::error(std::string msg) {
    log(ERROR, msg);
}

void fogel::core::Log::setOutput(std::ostream* output) {
    mOutput = output;
}

void fogel::core::Log::enable(int enabled) {
    mMask = enabled;
}

int fogel::core::Log::getEnabled() const {
    return mMask;
}

fogel::core::Log fogel::core::log;

redpajama_set_name: RedPajamaGithub


text:
from django import forms
from edit import models

class DocumentForm(forms.ModelForm):
    class Meta:
        model = models.Document
        fields = ['title', 'description']


text:
// apollo/modules/common/util/file_test.cc

#include "utils/apollo_file.h"

#include "gtest/gtest.h"

namespace bubblefs {
namespace myapollo {
namespace common {
namespace util {

class FileTest : public ::testing::Test {
 protected:
  virtual void SetUp() {
    system("exec rm -rf ${TEST_TMPDIR}/*");
    temp_dir = std::getenv("TEST_TMPDIR");
  }

  std::string FilePath(const std::string &file_name) {
    return temp_dir + "/" + file_name;
  }

  std::string temp_dir;
};

/*
TEST_F(FileTest, GetSetASCIIFile) {
  const std::string path = FilePath("output.pb.txt");

  test::SimpleMessage message;
  message.set_integer(17);
  message.set_text("This is some piece of text.");

  EXPECT_TRUE(SetProtoToASCIIFile(message, path));

  test::SimpleMessage read_message;
  EXPECT_TRUE(GetProtoFromASCIIFile(path, &read_message));

  EXPECT_EQ(message.integer(), read_message.integer());
  EXPECT_EQ(message.text(), read_message.text());
}

TEST_F(FileTest, GetSetBinaryFile) {
  const std::string path = FilePath("output.pb.bin");

  test::SimpleMessage message;
  message.set_integer(17);
  message.set_text("This is some piece of text.");

  EXPECT_TRUE(SetProtoToBinaryFile(message, path));

  test::SimpleMessage read_message;
  EXPECT_TRUE(GetProtoFromBinaryFile(path, &read_message));

  EXPECT_EQ(message.integer(), read_message.integer());
  EXPECT_EQ(message.text(), read_message.text());
}
*/

TEST_F(FileTest, PathExists) {
  EXPECT_TRUE(PathExists("/root"));
  EXPECT_FALSE(PathExists("/something_impossible"));
}

TEST_F(FileTest, EnsureAndRemoveDirectory) {
  const std::string directory_path = FilePath("my_directory/haha/hehe");
  EXPECT_FALSE(DirectoryExists(directory_path));
  EXPECT_TRUE(EnsureDirectory(directory_path));
  EXPECT_TRUE(DirectoryExists(directory_path));
}

TEST_F(FileTest, ListSubDirectories) {
  // Expect {'modules/common/util/testdata'}
  const auto root_subdirs = ListSubDirectories("/");

  // Some common root subdirs should exist.
  EXPECT_NE(root_subdirs.end(),
            std::find(root_subdirs.begin(), root_subdirs.end(), "home"));
  EXPECT_NE(root_subdirs.end(),
            std::find(root_subdirs.begin(), root_subdirs.end(), "root"));
  // Something shouldn't exist.
  EXPECT_EQ(root_subdirs.end(),
            std::find(root_subdirs.begin(), root_subdirs.end(), "impossible"));
}

TEST_F(FileTest, GetAbsolutePath) {
  EXPECT_EQ("./xx.txt", GetAbsolutePath("", "./xx.txt"));
  EXPECT_EQ("/abc", GetAbsolutePath("/abc", ""));
  EXPECT_EQ("/home/work/xx.txt", GetAbsolutePath("/home/work", "xx.txt"));
  EXPECT_EQ("/home/work/xx.txt", GetAbsolutePath("/home/work/", "xx.txt"));
  EXPECT_EQ("/xx.txt", GetAbsolutePath("/home/work", "/xx.txt"));
  EXPECT_EQ("/home/work/./xx.txt", GetAbsolutePath("/home/work", "./xx.txt"));
}

}  // namespace util
}  // namespace common
}  // namespace myapollo
}  // namespace bubblefs


text:
experiment='ap';
seed=4;
nofCities=16;
nofmetainds=50;
nofmaxmetagens=50;
alpha=0.02;
expstring=getExperimentString(experiment,seed,nofCities,nofmetainds,nofmaxmetagens,alpha);

%%
param1='crossprob';
cop=load(strcat(expstring,param1,'.txt'));
param2='cross_alternate_edges';
cx_alt_edge=load(strcat(expstring,param2,'.txt'));
param3='cross_cyclic';
cx_cyclic=load(strcat(expstring,param3,'.txt'));
param4='cross_edge_recombination';
cx_edge_recomb=load(strcat(expstring,param4,'.txt'));
param5='cross_seq_const';
cx_seq_const=load(strcat(expstring,param5,'.txt'));
figure(1)
plotMeanOverGens(nofmaxmetagens,{cop,cx_alt_edge,cx_cyclic,cx_edge_recomb,cx_seq_const})
legend('cross\_pr','alternate\_edges','cyclic','edge\_recombination','seq\_const', 'Location', 'northwest')

param1='muprob';
mup=load(strcat(expstring,param1,'.txt'));
param2='mut_insertion';
mu_insertion=load(strcat(expstring,param2,'.txt'));
param3='mut_inversion';
mu_inversion=load(strcat(expstring,param3,'.txt'));
param4='mut_reciprocal_exchange';
mu_recip=load(strcat(expstring,param4,'.txt'));

figure(2)
plotMeanOverGens(nofmaxmetagens,{mup,mu_insertion,mu_inversion,mu_recip})
legend('mut\_pr','insertion','inversion','reciprocal\_exchange', 'Location', 'northwest')

param1='fitness';
F=load(strcat(expstring,param1,'.txt'));
param2='distance';
D=load(strcat(expstring,param2,'.txt'));
figure(3)
plotMinOverGens(nofmaxmetagens,F,D)
legend('minimale fitness','minimale distance')


text:
import pygame

from rinde.data import Resources
from rinde.stage import Screen
from rinde.stage.builder import StageBuilder

"""
Represents Rinde application.
"""
class Application:

	"""
	Creates new application object and starts it. The application's window is built using files from the stage directory.
	This is an entry point for every Rinde application.
	Notice, that invoking this constructor starts an infinite loop so the program continues its execution in a controller.

	:param title: title of the window
	:param stage_directory: path to directory with files required to build the stage
	:param favicon: path to image file which will be used as icon of the window
	:param cursor: path to image file which will be used as cursor in the window
	"""
	def __init__(self, title, stage_directory, favicon=None, cursor=None):
		self.__init_pygame()

		Screen.init_size()

		Window(title, stage_directory, favicon, cursor)

	"""
	Initializes required library.
	"""
	def __init_pygame(self):
		pygame.init()
		pygame.mixer.init()
		pygame.font.init()

"""
Represents window of the application.
"""
class Window:

	"""
	Creates new window and builds a stage using files from stage directory.

	:param title: title of the window
	:param stage_directory: path to directory with files required to build the stage
	:param favicon: path to image file which will be used as icon of the window
	:param cursor: path to image file which will be used as cursor in the window
	"""
	def __init__(self, title, stage_directory, favicon, cursor):
		self.__init_favicon(favicon)

		self.set_title(title)
		self.set_stage(stage_directory)
		self.set_cursor(cursor)

		self.__updating()

	"""
	Changes window's favicon. Should not be invoked after initializing display.
	"""
	def __init_favicon(self, favicon):
		try:
			self.__try_to_init_favicon(favicon)
		except pygame.error:
			raise IOError("Cannot load file: '%s'" % favicon)

	"""
	Changes window's favicon. Should not be invoked after initializing display.
	"""
	def __try_to_init_favicon(self, favicon):
		if favicon is None:
			favicon = Resources.get_path_to_rinde_file("favicon.png")

		favicon = pygame.image.load(favicon)
		pygame.display.set_icon(favicon)

	"""
	Changes window's title.
	"""
	def set_title(self, title):
		try:
			pygame.display.set_caption(title)
		except TypeError:
			raise TypeError("Title of the window must be a string")

	"""
	Changes window's stage.

	:param stage_directory: path to directory with files required to build the stage
	:param controller: an object that controlls the stage
	"""
	def set_stage(self, stage_directory, controller=None):
		stage_builder = StageBuilder(stage_directory, controller)
		self.__stage = stage_builder.get_stage()

		self.__set_up_display()

		stage_builder.finalize(self)

	"""
	Initializes display.
	"""
	def __set_up_display(self):
		stage_size = self.__stage.get_size()
		stage_mode = self.__stage.get_mode()

		try:
			self.__surface = pygame.display.set_mode(stage_size, stage_mode)
		except TypeError:
			raise ValueError("Incorrect stage size")

	"""
	Changes window's cursor.
	"""
	def set_cursor(self, cursor):
		try:
			self.__try_to_set_cursor(cursor)
		except pygame.error:
			raise IOError("Cannot load file: '%s'" % cursor)

	"""
	Changes window's cursor.
	"""
	def __try_to_set_cursor(self, cursor):
		if cursor:
			image = pygame.image.load(cursor)
			self.__draw_cursor = lambda: self.__surface.blit(image, pygame.mouse.get_pos())
		else:
			image = None
			self.__draw_cursor = lambda: ()

		pygame.mouse.set_visible(image is None)

	"""
	This method invokes an infinite loop that updates window 60 times per second.
	"""
	def __updating(self):
		clock = pygame.time.Clock()

		while True:
			self.__stage.update(self.__surface)
			self.__draw_cursor()

			pygame.display.update()

			clock.tick(60)

	"""
	Centers direct child of a stage in the window on a specified axis.
	"""
	def center_in_stage(self, node, axis):
		self.__stage.center_node(node, axis)

	"""
	Returns size of the window.
	"""
	def get_size(self):
		return self.__stage.get_size()

	"""
	Returns position of the mouse.
	"""
	def get_mouse_position(self):
		return pygame.mouse.get_pos()


text:
"use strict";

exports.__esModule = true;
exports.SERIALIZATION_TYPE = exports.WILDCARD = exports.POSTROBOT_PROXY = exports.BRIDGE_NAME_PREFIX = exports.SEND_STRATEGY = exports.MESSAGE_NAME = exports.MESSAGE_ACK = exports.MESSAGE_TYPE = void 0;
const MESSAGE_TYPE = {
  REQUEST: 'postrobot_message_request',
  RESPONSE: 'postrobot_message_response',
  ACK: 'postrobot_message_ack'
};
exports.MESSAGE_TYPE = MESSAGE_TYPE;
const MESSAGE_ACK = {
  SUCCESS: 'success',
  ERROR: 'error'
};
exports.MESSAGE_ACK = MESSAGE_ACK;
const MESSAGE_NAME = {
  METHOD: 'postrobot_method',
  HELLO: 'postrobot_hello',
  OPEN_TUNNEL: 'postrobot_open_tunnel'
};
exports.MESSAGE_NAME = MESSAGE_NAME;
const SEND_STRATEGY = {
  POST_MESSAGE: 'postrobot_post_message',
  BRIDGE: 'postrobot_bridge',
  GLOBAL: 'postrobot_global'
};
exports.SEND_STRATEGY = SEND_STRATEGY;
const BRIDGE_NAME_PREFIX = '__postrobot_bridge__';
exports.BRIDGE_NAME_PREFIX = BRIDGE_NAME_PREFIX;
const POSTROBOT_PROXY = '__postrobot_proxy__';
exports.POSTROBOT_PROXY = POSTROBOT_PROXY;
const WILDCARD = '*';
exports.WILDCARD = WILDCARD;
const SERIALIZATION_TYPE = {
  CROSS_DOMAIN_ZALGO_PROMISE: 'cross_domain_zalgo_promise',
  CROSS_DOMAIN_FUNCTION: 'cross_domain_function',
  CROSS_DOMAIN_WINDOW: 'cross_domain_window'
};
exports.SERIALIZATION_TYPE = SERIALIZATION_TYPE;


text:
require 'spec_helper'

describe SnippetsFinder do
  let(:user) { create :user }
  let(:user1) { create :user }
  let(:group) { create :group }

  let(:project1) { create(:empty_project, :public,   group: group) }
  let(:project2) { create(:empty_project, :private,  group: group) }

  context ':all filter' do
    before do
      @snippet1 = create(:personal_snippet, visibility_level: Snippet::PRIVATE)
      @snippet2 = create(:personal_snippet, visibility_level: Snippet::INTERNAL)
      @snippet3 = create(:personal_snippet, visibility_level: Snippet::PUBLIC)
    end

    it "returns all private and internal snippets" do
      snippets = SnippetsFinder.new.execute(user, filter: :all)
      snippets.should include(@snippet2, @snippet3)
      snippets.should_not include(@snippet1)
    end

    it "returns all public snippets" do
      snippets = SnippetsFinder.new.execute(nil, filter: :all)
      snippets.should include(@snippet3)
      snippets.should_not include(@snippet1, @snippet2)
    end
  end

  context ':by_user filter' do
    before do
      @snippet1 = create(:personal_snippet, visibility_level: Snippet::PRIVATE, author: user)
      @snippet2 = create(:personal_snippet, visibility_level: Snippet::INTERNAL, author: user)
      @snippet3 = create(:personal_snippet, visibility_level: Snippet::PUBLIC, author: user)
    end

    it "returns all public and internal snippets" do
      snippets = SnippetsFinder.new.execute(user1, filter: :by_user, user: user)
      snippets.should include(@snippet2, @snippet3)
      snippets.should_not include(@snippet1)
    end

    it "returns internal snippets" do
      snippets = SnippetsFinder.new.execute(user, filter: :by_user, user: user, scope: "are_internal")
      snippets.should include(@snippet2)
      snippets.should_not include(@snippet1, @snippet3)
    end

    it "returns private snippets" do
      snippets = SnippetsFinder.new.execute(user, filter: :by_user, user: user, scope: "are_private")
      snippets.should include(@snippet1)
      snippets.should_not include(@snippet2, @snippet3)
    end

    it "returns public snippets" do
      snippets = SnippetsFinder.new.execute(user, filter: :by_user, user: user, scope: "are_public")
      snippets.should include(@snippet3)
      snippets.should_not include(@snippet1, @snippet2)
    end

    it "returns all snippets" do
      snippets = SnippetsFinder.new.execute(user, filter: :by_user, user: user)
      snippets.should include(@snippet1, @snippet2, @snippet3)
    end

    it "returns only public snippets if unauthenticated user" do
      snippets = SnippetsFinder.new.execute(nil, filter: :by_user, user: user)
      snippets.should include(@snippet3)
      snippets.should_not include(@snippet2, @snippet1)
    end

  end

  context 'by_project filter' do
    before do
      @snippet1 = create(:project_snippet, visibility_level: Snippet::PRIVATE, project: project1)
      @snippet2 = create(:project_snippet, visibility_level: Snippet::INTERNAL, project: project1)
      @snippet3 = create(:project_snippet, visibility_level: Snippet::PUBLIC, project: project1)
    end

    it "returns public snippets for unauthorized user" do
      snippets = SnippetsFinder.new.execute(nil, filter: :by_project, project: project1)
      snippets.should include(@snippet3)
      snippets.should_not include(@snippet1, @snippet2)
    end

    it "returns public and internal snippets for none project members" do
      snippets = SnippetsFinder.new.execute(user, filter: :by_project, project: project1)
      snippets.should include(@snippet2, @snippet3)
      snippets.should_not include(@snippet1)
    end

    it "returns all snippets for project members" do
      project1.team << [user, :developer]
      snippets = SnippetsFinder.new.execute(user, filter: :by_project, project: project1)
      snippets.should include(@snippet1, @snippet2, @snippet3)
    end
  end
end


text:
class MPEventLoopRunner(object):

    """This class (concurrently) runs instances of `EventLoop`.

    An instance of this class needs to be initialized with a
    communication channel with workers that actually run the
    `EventLoop`::

        runner = MPEventLoopRunner(communicationChannel)

    An example of a communication channel is an instance of
    `CommunicationChannel`.

    The method `begin()` does nothing in the current version::

        runner.begin()

    In older versions, multiple processes are forked in this method.

    Then, you can give an `EventLoop` with the method `run()`::

        runner.run(eventLoop1)

    This class will send the `EventLoop` to a worker through the
    communication channel. The worker, then, runs the `EventLoop`.

    You can call the method `run()` mutiple times::

        runner.run(eventLoop2)
        runner.run(eventLoop3)
        runner.run(eventLoop4)

    If workers are in the background, this method immediately returns.
    Worker are concurrently running the event loops in the background.
    If the worker is in the foreground, this method won't return until
    the worker finishes running the event loop. Whether workers are in
    the background or foreground depends on the communication channel
    with which this class is initialized.

    After giving all event loops that you need to run to this class,
    you need to call the method `end()`::

        results = runner.end()

    If workers are in the background, this method will wait until
    workers finish running all event loops. If the worker is in the
    foreground, this method immediately returns. This method returns
    the results, the list of the values eventLoops return, sorted in
    the order given with `run()`.

    """

    def __init__(self, communicationChannel):
        self.communicationChannel = communicationChannel
        self.nruns = 0

    def __repr__(self):
        return '{}(communicationChannel = {!r}'.format(
            self.__class__.__name__,
            self.communicationChannel
        )

    def begin(self):
        """does nothing.

        Older versions of this class had implementations.
        """
        pass

    def run(self, eventLoop):
        """run the event loop in the background.

        Args:
            eventLoop (EventLoop): an event loop to run

        """

        self.communicationChannel.put(eventLoop)
        self.nruns += 1

    def end(self):
        """wait until all event loops end and returns the results.

        """

        results = self.communicationChannel.receive()

        if self.nruns != len(results):
            import logging
            logger = logging.getLogger(__name__)
            # logger.setLevel(logging.DEBUG)
            logger.warning(
                'too fee results received: {} results received, {} expected'.format(
                    len(results),
                    self.nruns
                ))

        return results

##__________________________________________________________________||


text:
#include <boost/multiprecision/cpp_dec_float.hpp>
#include <boost/type_traits/is_nothrow_move_constructible.hpp>
#include <boost/type_traits/is_nothrow_move_assignable.hpp>
#include <boost/type_traits/has_nothrow_constructor.hpp>
#include <boost/type_traits/has_nothrow_assign.hpp>
#include <boost/type_traits/has_nothrow_copy.hpp>
#include <boost/static_assert.hpp>

#ifndef BOOST_NO_NOEXCEPT

#if !defined(BOOST_NO_CXX11_NOEXCEPT) && !defined(BOOST_NO_SFINAE_EXPR) || defined(BOOST_IS_NOTHROW_MOVE_CONSTRUCT)
//
// Move construct:
//
BOOST_STATIC_ASSERT(boost::is_nothrow_move_constructible<boost::multiprecision::cpp_dec_float_100>::value);

#endif

#if !defined(BOOST_NO_CXX11_NOEXCEPT) && !defined(BOOST_NO_SFINAE_EXPR) || defined(BOOST_IS_NOTHROW_MOVE_ASSIGN)
//
// Move assign:
//
BOOST_STATIC_ASSERT(boost::is_nothrow_move_assignable<boost::multiprecision::cpp_dec_float_100>::value);

#endif

//
// Construct:
//
#ifdef BOOST_HAS_NOTHROW_CONSTRUCTOR
BOOST_STATIC_ASSERT(boost::has_nothrow_constructor<boost::multiprecision::cpp_dec_float_100>::value);
#endif
//
// Copy construct:
//
#ifdef BOOST_HAS_NOTHROW_COPY
BOOST_STATIC_ASSERT(boost::has_nothrow_copy<boost::multiprecision::cpp_dec_float_100>::value);
#endif
//
// Assign:
//
#ifdef BOOST_HAS_NOTHROW_ASSIGN
BOOST_STATIC_ASSERT(boost::has_nothrow_assign<boost::multiprecision::cpp_dec_float_100>::value);
#endif

#endif // noexcept


text:
const webpack = require('webpack');
const CopyWebpackPlugin = require('copy-webpack-plugin');

module.exports = {
  entry: {
    app: './src/main/js/main.jsx'
  },
  output: {
    path: './build/exploded-app',
    filename: '[name].js'
  },
  externals: {
    'react': 'React',
    'react-dom': 'ReactDOM',
    'react-router': 'ReactRouter'
  },
  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel-loader?presets[]=es2015&presets[]=react'
      },
      {
        test: /\.json$/,
        exclude: /node_modules/,
        loader: 'json-loader'
      },
      {
        test: /\.less$/,
        exclude: /node_modules/,
        loader: 'style!css!less?compress'
      }
    ]
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
      }
    }),
    new CopyWebpackPlugin([
      {from: './static'},
      {from: './node_modules/react/dist/react.min.js'},
      {from: './node_modules/react-dom/dist/react-dom.min.js'},
      {from: './node_modules/react-router/umd/ReactRouter.min.js'},
      {from: './node_modules/bootswatch/lumen/bootstrap.min.css'},
      {from: './node_modules/bootswatch/fonts', to: 'fonts'},
      {from: './src/main/groovlet', to: 'WEB-INF/groovy'}
    ])
  ],
  devServer: {
    historyApiFallback: true,
    contentBase: './static'
  }
};


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

Compare two HTML strings. This library converts HTML into a form that can be diffed using the algorithm found in Git or Linux (comparing entire lines of code) to achieve greater accuracy, then decodes it back into a valid HTML.

## Requirements

- PHP 5.3.0 or later
- [Tidy](http://php.net/manual/en/intro.tidy.php) extension for PHP

## Installation

Add Htmldiff to your `composer.json` file:

```json
"require": {
    "gathercontent/htmldiff": "0.2.*"
}
```

Get composer to install the package:

```bash
$ composer update gathercontent/htmldiff
```

## Usage

The input is going to be parsed by Tidy before diffing. Here's a few examples:

```php
$old = '<span>This is a string</span>';
$new = '<span>This is a text</span>';

$htmldiff = new Htmldiff;
$result = $htmldiff->diff($old, $new);

// result: <span>This is a <del>string</del><ins>text</ins></span>
```

```php
$old = '<p>Hello world, how do you do</p>';
$new = '<p>Hello world, how do <strong>you</strong> do</p>';

$htmldiff = new Htmldiff;
$result = $htmldiff->diff($old, $new);

// result: <p>Hello world, how do <del>you</del><strong><ins>you</ins></strong> do</p>
```

```php
$old = '<p>Hello world</p><p>How do you do</p>';
$new = '<p>Hello world</p><ul><li>first point</li><li>second point</li></ul><p>How do you do</p>';

$htmldiff = new Htmldiff;
$result = $htmldiff->diff($old, $new);

// result: <p>Hello world</p><ul><li><ins>first point</ins></li><li><ins>second point</ins></li></ul><p>How do you do</p>
```

## Testing

Run unit tests:

``` bash
$ ./vendor/bin/phpunit
```

Test compliance with [PSR2 coding style guide](http://www.php-fig.org/psr/psr-2/):

``` bash
$ ./vendor/bin/phpcs --standard=PSR2 ./src
```

# Licence

The MIT License (MIT) - see `README.md`


text:
<title>Symbol-Renaming Pragmas - Using the GNU Compiler Collection (GCC)</title>
<meta http-equiv="Content-Type" content="text/html">
<meta name="description" content="Using the GNU Compiler Collection (GCC)">
<meta name="generator" content="makeinfo 4.13">
<link title="Top" rel="start" href="index.html#Top">
<link rel="up" href="Pragmas.html#Pragmas" title="Pragmas">
<link rel="prev" href="Solaris-Pragmas.html#Solaris-Pragmas" title="Solaris Pragmas">
<link rel="next" href="Structure_002dPacking-Pragmas.html#Structure_002dPacking-Pragmas" title="Structure-Packing Pragmas">
<link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage">

<meta http-equiv="Content-Style-Type" content="text/css">

Next: Structure-Packing Pragmas,
Previous: Solaris Pragmas,
Up: Pragmas

6.59.7 Symbol-Renaming Pragmas

For compatibility with the Solaris system headers, GCC
supports two #pragma directives that change the name used in
assembly for a given declaration. To get this effect
on all platforms supported by GCC, use the asm labels extension (see Asm Labels).

redefine_extname <var>oldname</var> <var>newname</var>

This pragma gives the C function <var>oldname</var> the assembly symbol
<var>newname</var>.  The preprocessor macro __PRAGMA_REDEFINE_EXTNAME
is defined if this pragma is available (currently on all platforms).

This pragma and the asm labels extension interact in a complicated
manner.  Here are some corner cases you may want to be aware of.

Both pragmas silently apply only to declarations with external
linkage.  Asm labels do not have this restriction.

In C++, both pragmas silently apply only to declarations with
“C” linkage.  Again, asm labels do not have this restriction.

If any of the three ways of changing the assembly name of a
declaration is applied to a declaration whose assembly name has
already been determined (either by a previous use of one of these
features, or because the compiler needed the assembly name in order to
generate code), and the new name is different, a warning issues and
the name does not change.

The <var>oldname</var> used by #pragma redefine_extname is
always the C-language name.


text:
@interface RVRunLoopViewController : UIViewController

@end


text:
package br.ifrn.ssaac.business.facade;

import br.ifrn.ssaac.business.model.Student;
import br.ifrn.ssaac.business.userbi.UserBI;

public class SSAACImp implements SSAAC {

	private UserBI userBI;

	public void setUserBI(UserBI userBI) {
		this.userBI = userBI;
	}

	@Override
	public void addStudentAuthor(Student student) {
		userBI.addStudentAuthor(student);
	}
}


text:
using System;
using System.Drawing;
using System.Windows.Forms;
using GUI_LDAPUnitTest.Tests.BusinessLogic;
using GUI_LDAPUnitTest.Tests.GUIStructures;
using GUI_LDAPUnitTest.Tests.GUIStructures.OneItemConfiguration;

namespace GUI_LDAPUnitTest.Forms
{
    public partial class TestForm : Form
    {
        private readonly TestRunner _testRunnerObj;
        private readonly TestTripletRepository _testTripletRepository;

        public TestForm()
        {
            InitializeComponent();
            try
            {
                _testTripletRepository = new TestTripletRepository();

                AddTestTripletsToRepository();

                _testRunnerObj = new TestRunner(LdapLibraryBuilder.SetupLdapLibrary());

                currentUserLabel.Text = _testRunnerObj.UserRepository.GetTestUserCn();

                _testTripletRepository.SetAllStateLabelText(Constants.TestLableUndefined);
            }
            catch (Exception ex)
            {
                MessageBox.Show(
                    String.Format(
                        "Cannot load the Config - Standard LDAP Library Init failed{0}Exception Message: {1}",
                        Environment.NewLine, ex.Message),
                    @"Error Config Loading",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw;
            }
        }

        #region Interface Events

        #region Setup Buttons

        private void configModifyUserDescriptionButton_Click(object sender, EventArgs e)
        {
            using (
                var setupModifyUserDescriptionForm =
                    new OneItemConfigurationForm(OneItemConfigurationState.NewDescription,
                        _testRunnerObj.UserRepository))
            {
                setupModifyUserDescriptionForm.ShowDialog();
            }
        }

        private void configSearchUserButton_Click(object sender, EventArgs e)
        {
            using (
                var setupSearchUserForm = new OneItemConfigurationForm(OneItemConfigurationState.UserToSearch,
                    _testRunnerObj.UserRepository))
            {
                setupSearchUserForm.ShowDialog();
            }
        }

        private void configUserChangePasswordButton_Click(object sender, EventArgs e)
        {
            using (
                var setupNewPasswordForm = new OneItemConfigurationForm(OneItemConfigurationState.NewPassword,
                    _testRunnerObj.UserRepository))
            {
                setupNewPasswordForm.ShowDialog();
            }
        }

        /// <summary>
        ///     launch the newTestUser form and update the main form at return.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void setUserButton_Click(object sender, EventArgs e)
        {
            using (var testUserForm = new TestUserForm(_testRunnerObj.UserRepository))
            {
                testUserForm.ShowDialog();
            }
            currentUserLabel.Text = _testRunnerObj.UserRepository.GetTestUserCn();
        }

        #endregion

        #region ComboBox Visibility Events

        private void testCreateUserCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            testCreateUserLabel.Enabled = testCreateUserCheckBox.Checked;
            stateCreateUserLabel.Enabled = testCreateUserCheckBox.Checked;
        }

        private void testModifyUserDescriptionCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            testModifyUserDescriptionLabel.Enabled = testModifyUserDescriptionCheckBox.Checked;
            stateModifyUserDescriptionLabel.Enabled = testModifyUserDescriptionCheckBox.Checked;
        }

        private void testSearchUserCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            testSearchUserLabel.Enabled = testSearchUsersCheckBox.Checked;
            stateSearchUsersLabel.Enabled = testSearchUsersCheckBox.Checked;
        }

        private void testConnectUserCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            testConnectUserLabel.Enabled = testConnectUserCheckBox.Checked;
            stateConnectUserLabel.Enabled = testConnectUserCheckBox.Checked;
        }

        private void testSearchUserAndConnectCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            testSearchUserAndConnectLabel.Enabled = testSearchUserAndConnectCheckBox.Checked;
            stateSearchUserAndConnectLabel.Enabled = testSearchUserAndConnectCheckBox.Checked;
        }

        private void testUserChangePasswordCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            testUserChangePasswordLabel.Enabled = testUserChangePasswordCheckBox.Checked;
            stateUserChangePasswordLabel.Enabled = testUserChangePasswordCheckBox.Checked;
        }

        private void testDeleteUserCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            testDeleteUserLabel.Enabled = testDeleteUserCheckBox.Checked;
            stateDeleteUserLabel.Enabled = testDeleteUserCheckBox.Checked;
        }

        private void testSearchUsersNoFilterCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            testSearchUserNoFilterLabel.Enabled = testSearchUsersNoFilterCheckBox.Checked;
            stateSearchUsersNoFilterLabel.Enabled = testSearchUsersNoFilterCheckBox.Checked;
            searchUserNoFilterSpinEdit.Enabled = testSearchUsersNoFilterCheckBox.Checked;
        }

        private void testSearchAllNodesCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            testSearchAllNodesLabel.Enabled = testSearchAllNodesCheckBox.Checked;
            stateSearchAllNodesLabel.Enabled = testSearchAllNodesCheckBox.Checked;
            searchAllNodesSpinEdit.Enabled = testSearchAllNodesCheckBox.Checked;
        }
        #endregion

        #region Other Events

        /// <summary>
        ///     Manage the visibility and repositioning of the panels.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void readTestsLabel_Click(object sender, EventArgs e)
        {
            if (readTestsPanel.Height == 35)
            {
                //Expand the read and move the write panel
                readTestsPanel.Height = 261;
                readTestIconLabel.Text = @"-";
                writeTestsPanel.Location = new Point(writeTestsPanel.Location.X, writeTestsPanel.Location.Y + 150);
            }
            else if (readTestsPanel.Height == 261)
            {
                //Collapse the read panel and write panel repositioned.
                readTestsPanel.Height = 35;
                readTestIconLabel.Text = @"+";
                writeTestsPanel.Location = new Point(writeTestsPanel.Location.X, writeTestsPanel.Location.Y - 150);
            }
        }

        private void WriteTestsLabel_Click(object sender, EventArgs e)
        {
            if (writeTestsPanel.Height == 35)
            {
                writeTestsPanel.Height = 220;
                writeTestsIconLabel.Text = @"-";
            }
            else
            {
                writeTestsPanel.Height = 35;
                writeTestsIconLabel.Text = @"+";
            }
        }

        #endregion

        /// <summary>
        ///     Start the tests
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void runButton_Click(object sender, EventArgs e)
        {
            Cursor.Current = Cursors.WaitCursor;
            testsProgressBar.Value = 0;
            _testTripletRepository.SetAllStateLabelText(Constants.TestLableInProgress);

            int progressBarIncrement = 100/Enum.GetNames(typeof (TestType)).Length;
            try
            {
                foreach (TestTriplet t in _testTripletRepository.TestCheckedTripletList)
                {
                    t.TestLabel.Text = Constants.TestLableStarted;
                    if (_testRunnerObj.RunTest(t.TestType))
                    {
                        t.TestLabel.Text = Constants.TestLablePassed;
                        t.TestLabel.ForeColor = Constants.TestPassedColorLable;
                    }
                    else
                    {
                        t.TestLabel.Text = Constants.TestLableFailed;
                        t.TestLabel.ForeColor = Constants.TestFailedColorLable;
                    }
                    testsProgressBar.Value += progressBarIncrement;
                }
            }
            catch (Exception)
            {
                MessageBox.Show(@"Qualcosa non ha funzionato nel programma di test");
            }

            testsProgressBar.Value = 100;

            Cursor.Current = Cursors.Default;
        }

        /// <summary>
        /// numericUpDown for the searchNoFilter users
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            _testRunnerObj.UserRepository.ExpectedSearchNoFilterResultNumber = (int) searchUserNoFilterSpinEdit.Value;
        }

        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {
            _testRunnerObj.UserRepository.ExpectedSearchAllNodesResultNumber = (int)searchAllNodesSpinEdit.Value;
        }

        #endregion

        /// <summary>
        ///     add all controls in relation each other like triplets.
        /// </summary>
        private void AddTestTripletsToRepository()
        {
            _testTripletRepository.AddTestTriplet(new TestTriplet(testStandardInitLibraryNoAdminCheckBox,
                TestType.TestStandardInitLibraryNoAdmin,
                stateStandardInitLibraryNoAdminLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testInitLibraryNoAdminCheckBox,
                TestType.TestInitLibraryNoAdmin,
                stateInitLibraryNoAdminLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testInitLibraryCheckBox,
                TestType.TestInitLibrary,
                stateInitLibraryLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testAdminConnectCheckBox,
                TestType.TestAdminConnection,
                stateAdminConnectLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testConnectUserCheckBox,
                TestType.TestConnectUser,
                stateConnectUserLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testSearchUserAndConnectCheckBox,
                TestType.TestSearchUserAndConnect,
                stateSearchUserAndConnectLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testSearchUsersCheckBox,
                TestType.TestSearchUsers,
                stateSearchUsersLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testCreateUserCheckBox,
                TestType.TestCreateUser,
                stateCreateUserLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testModifyUserDescriptionCheckBox,
                TestType.TestModifyUserDescription,
                stateModifyUserDescriptionLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testUserChangePasswordCheckBox,
                TestType.TestUserChangePassword,
                stateUserChangePasswordLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testDeleteUserCheckBox,
                TestType.TestDeleteUser,
                stateDeleteUserLabel));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testSearchUsersNoFilterCheckBox,
                TestType.TestSearchUsersNoFilter,
                stateSearchUsersNoFilterLabel
                ));

            _testTripletRepository.AddTestTriplet(new TestTriplet(testSearchAllNodesCheckBox,
                TestType.TestSearchAllNodes,
                stateSearchAllNodesLabel
                ));
        }
    }
}


text:
*   First commit, defines basic interfaces, provides an example implementation,
    and basic testcases.


text:
windows_smb
============================

Module for puppet that can be used to create and manage windows SMB shares, and set various configuration options for SMB server / client settings on a windows system.

Very unrestricted limits on settings, I tried to find absolute min/max values for the settings for `windows_smb::manage_smb_server_config` and `window_smb::manage_smb_client_config`.

Stayed away from settings like forcing digital signing etc. as these tend to be managed via group policy.

That's kind of a thing in puppet on windows, you find yourself moving towards replacing things done with GPO.  If people want it, I'll add it.  It is good to reduce infrastructure config to state declaration code.  However, we need to make that transition smooth for admins and not be invasive.

__N.B.__: not making resources depend upon a PowerShell version check - this has been tested OK with version 4 and 5.  Upgrade your Windows Management Framework to 4.0 or higher if you run into bother on old OS.

__tested on__: server 2012R2 OK (PS 4), win 10 enterprise OK (PS 5)

Module Usage
--
__Only supports windows OS__ - `windows_smb::manage_smb_share` only supports windows feature 'FS-BranchCache' where it exists but does NOT restrict attempted auto-install of 'FS-BranchCache feature' - module resources will fail due to dependency if for some reason the windows feature is unavailable for install or the system does not support ps commandlet 'add-windowsfeature'.

Example Use
--
    node 'my_file_server.corp.blah.moo' {
        include 'my_smb_file_shares'
    }

      class my_smb_file_shares {

          #module will NOT ensure share target directory on file system exists, make sure it does and require it in windows_smb::manage_smb_share resource instance

          file { 'c:\temp1': ensure => directory, }

          windows_smb::manage_smb_share { 'testshare':
            smb_share_directory               => 'c:\temp1',
            ensure                            => present,
            smb_share_comments                => 'puppet generated smb share test',
            smb_share_concurrent_user_limit   => 0,
            smb_share_cache                   => 'None',
            smb_share_encrypt_data            => false,
            smb_share_folder_enum_mode        => 'AccessBased',
            smb_share_temporary               => true,
            smb_share_access_full             => ['corp.blah.moo\user0', 'local_admin','user1@corp.blah.moo'],
            smb_share_access_change           => ['corp\domain admins'],
            smb_share_access_read             => [],
            smb_share_access_deny             => [],
            smb_share_autoinstall_branchcache => false,
            require                           => File['c:\temp1'],
          }

          #with defaults - note ensure is assumed => 'present'
          windows_smb::manage_smb_share { 'testshare1':
            smb_share_directory               => 'c:\temp1',
            smb_share_access_full             => ['Everyone'],
            require                           => File['c:\temp1'],
          }

          #server smb config settings example - note the 'title' / resource name isn't used in class
          #note that cannot set ensure to 'absent' as many of these settings REQUIRED for os to function properly - set ensrue => 'default' to reset to defaults
          windows_smb::manage_smb_server_config{$::clientcert:
           ensure                                        => present,
           smb_server_asynchronous_credits               => 1024,
           smb_server_smb2_credits_min                   => 1024,
           smb_server_smb2_credits_max                   => 16384,
           smb_server_max_threads_per_queue              => 64,
           smb_server_treat_host_as_stable_storage       => true,
           smb_server_max_channel_per_session            => 32,
           smb_server_additional_critical_worker_threads => 20,
           smb_server_additional_delayed_worker_threads  => 20,
           smb_server_ntfs_8dot3_name_creation           => 'disabled',
           smb_server_ntfs_disable_last_access_update    => true,
           }

        # reset server config settings to defaults
        # windows_smb::manage_smb_server_config{$::clientcert: ensure => default,}

        windows_smb::manage_smb_client_config{$::clientcert:
         ensure                                               => 'present',
         smb_client_connection_count_per_interface            => 16,
         smb_client_connection_count_per_rss_interface        => 16,
         smb_client_connection_count_per_rdma_interface       => 16,
         smb_client_connection_count_per_server_max           => 64,
         smb_client_dormant_Directory_timeout_seconds         => 500,
         smb_client_directory_cache_lifetime_seconds          => 15,
         smb_client_dormant_file_limit                        => 4096,
         smb_client_directory_cache_entry_size_max_bytes      => 65580,
         smb_client_file_not_found_cache_lifetime_seconds     => 5,
         smb_client_file_not_found_cache_entries_max          => 2048,
         smb_client_file_info_cache_lifetime_seconds          => 5,
         smb_client_file_info_cache_entries_max               => 1024,
         smb_client_enable_bandwidth_throttling               => false,
         smb_client_enable_large_mtu                          => false,
         smb_client_enable_byte_range_locking_read_only_files => false,
         smb_client_enable_multichannel                       => false,
         smb_client_extended_session_timeout_seconds          => 999,
         smb_client_keep_connection_seconds                   => 555,
         smb_client_max_commands                              => 8192,
         smb_client_oplocks_disabled                          => true,
         smb_client_session_timeout_seconds                   => 45,
         smb_client_use_opportunistic_locking                 => false,
         smb_client_window_size_threshold                     => 16
         }

       # reset client config settings to defaults
       # windows_smb::manage_smb_client_config{$::clientcert: ensure => default,}
      }

#`windows_smb::manage_smb_share`
__THIS MODULE DOES NOT SUPPORT CLUSTERED SHARES UNDER CAFS__

##`windows_smb::manage_smb_share` parameters

####`ensure`
Set the ensure state of the smb share. string.

* __'present'__: will ensure the share exists and is set as desired
* __'absent','purge'__: 'absent' / 'purge' will remove the share by share name on the system applying windows_smb::manage_smb_share

__default value__: 'present'

####`smb_share_directory`
Set this to the fully qualified path to share as string.  Note that this class will NOT ensure that the target file system path for share assurance is present.  Doing so would be invasive coding.
Create a File resource for the directory to be shared and make the `windows_smb::manage_smb_share` instance dependent upon it.  this is shown in the example above.

####`smb_share_comments`
Set string to put as comments on the share (description)

__default value__: 'puppet generated smb share'

####`smb_share_concurrent_user_limit`
Set the Uint32 desired concurrent user limit on the share being managed.

__valid integer range__: 0 - 4294967295  --- Setting 0 will result in there not being a share enforced restriction on concurrent user limit.

__default value__: 0

####`smb_share_cache`
Set to one of the valid string options 'None', 'Manual', 'Programs', 'Documents', 'BrancheCache'.

* __None__: Prevents users from storing documents and programs offline.
* __Manual__: Allows users to identify the documents and programs that they want to store offline.
* __Programs__: Automatically stores documents and programs offline.
* __Documents__: Automatically stores documents offline.
* __BranchCache__: Enables BranchCache and manual caching of documents on the shared folder.

__default value__: 'None'

###`smb_share_encrypt_data`
Set bool to indicate if the share utilizes encrytion.

__default value__: false

###`smb_share_folder_enum_mode`
Set string to specify which files and folders in the SMB share will be visible to the users.

* __'AccessBased'__: SMB will not the display the files and folders for a share to a user unless that user has rights to access the files and folders. Via PowerShell, access-based enumeration is disabled by default for new SMB shares.  This is NOT true for this module.
* __'Unrestricted'__: SMB will display files and folders to a user even when the user does not have permission to access those items.

__default value__: 'AccessBased'

###`smb_share_temporary`
Set bool to indicate whether share will persist past system reboot:

* __true__: share will NOT persist past system reboot.  The share is temporary.
* __false__: share is permanent and will persist past system reboot.

__default value__: false

##share permissions params
__N.B.__ Module does NOT support share creation with no permissions whatsoever.  If all permissions params are `[]` (empty array) will cause catalog failure due to resource where that implementation exists.

__N.B.__ CANNOT set permissions entries for user to multiple permission types on a share - i.e. user1 may not have both 'full' and 'change' assignments.  It is not like ACEs at the file system level.  Can only be in one place.  Puppet DSL logic will attempt to reject a configuration made in this way and if somehow slips through the resource create would fail.  if resource exists permissions check would also fail as change in permissions results in share removal and recreate.

__N.B.__ UPN limitation in that it much match the user domain - so user@corp.moo would not work if user domain was user@corp.blah.moo

__N.B.__ permissions return with powershell 'GetSmbAccess' returns object array with UNQUALIFIED domain name as string - cannot accurately resolve scenarion where assigning permissions over trust - e.g. assign permissions for user0@corp.blah.moo AND user0@corp.foo.toyou UNTESTED and may not work

* can use local account unqualified, domain\username or user UPN

###`smb_share_access_full`
string array of users / groups to grant 'full' access permissions to at the smb share level (THIS IS NOT FILE PERMISSIONS ON DISK).

* e.g. ['domain\user0', 'local_admin','user1_upn@domain.blah.moo']

__default value__: []     <<<< EMPTY (STRING) ARRAY

###`smb_share_access_change`
string array of users / groups to grant 'change' access permissions to at the smb share level (THIS IS NOT FILE PERMISSIONS ON DISK)

* e.g. ['domain\user1', 'local_admin_0','user2_upn@domain.blah.moo']

__default value__: []     <<<< EMPTY (STRING) ARRAY

###`smb_share_access_read`
string array of users / groups to grant 'read' access permissions to at the smb share level (THIS IS NOT FILE PERMISSIONS ON DISK)

* e.g. ['domain\user2', 'local_admin_1','user3_upn@domain.blah.moo']

__default value__: []     <<<< EMPTY (STRING) ARRAY

###`smb_share_access_deny`
string array of users / groups to set 'deny' access permissions to at the smb share level (THIS IS NOT FILE PERMISSIONS ON DISK)

* e.g. ['domain\user3', 'local_admin_2','user4_upn@domain.blah.moo']

__default value__: []     <<<< EMPTY (STRING) ARRAY

###`smb_share_autoinstall_branchcache`
set boolean true to attempt to auto-install windows feature 'FS-BranchCache' if available to system via PowerShell 'Add-WindowsFeature'.  Does not ensure state of windows feature via another resource type - it is an exec based get / set.  So safe to use if ensure 'FS-BranchCache' as windows feature elsewhere in catalog.
Share creation made dependent on this exec resource if this param 'true' to ensure proper fail if not available for install and cannot install.

__N.B.__ use in conjunction with `smb_share_cache => 'BranchCache'` if set to true, otherwise not relevant and will not execute.

__N.B.__ can use `smb_share_cache => 'BranchCache'` WITHOUT using `smb_share_autoinstall_branchcache' => true` - it just won't consider windows feature 'FS-BranchCache' presence - caller in this case responsible for it being there

__default value__: false

#`windows_smb::manage_smb_server_config`

##`windows_smb::manage_smb_server_config` parameters
Sensible caps on resource params are not implemented.  You may tweak up to the maximum allowed value and it is assumed you will research impact on system performance / viability to serve.  Good luck, have fun!

###Resource 'Name' / 'Title' is irrelivent - suggest set to `$::fqdn` or `$::clientcert` as in example
Settings are global for the Windows machine the resource is applied against.  For sanity, suggest naming resource `$::fqdn` or `$::clientcert`

####`ensure`
Set the ensure state of the smb share. string.

* __'present'__: will ensure the smb server config exists and is set as desired
* __'default'__: 'default' will reset node values to sensible OS defaults.  These may or may not be the most optimal for node use case.

__default value__: 'present'

###`smb_server_asynchronous_credits`
Limits the number of concurrent asynchronous SMB commands that are allowed on a single connection. Some cases (such as when there is a front-end server with a back-end IIS server) require a large amount of concurrency (for file change notification requests, in particular). The value of this entry can be increased to support these cases.

__default value__: false

###`smb_server_smb2_credits_min`

Uint32. Allow the server to throttle client operation concurrency dynamically within the specified boundaries. Some clients might achieve increased throughput with higher concurrency limits, for example, copying files over high-bandwidth, high-latency links.

__valid integer range__: 1 - `smb_server_smb2_credits_max` (theoretical max 4294967295)

__default value__: 512  << value may not be higher than `smb_server_smb2_credits_max`

__tweaking notes__: You can monitor SMB Client Shares\Credit Stalls /Sec to see if there are any issues with credits.

###`smb_server_smb2_credits_max`
Uint32. Allow the server to throttle client operation concurrency dynamically within the specified boundaries. Some clients might achieve increased throughput with higher concurrency limits, for example, copying files over high-bandwidth, high-latency links.

__valid integer range__: `smb_server_smb2_credits_max` (theoretical min 1) - 4294967295

__default value__: 8192 << value may not be lower than `smb_server_smb2_credits_min`

__tweaking notes__: You can monitor SMB Client Shares\Credit Stalls /Sec to see if there are any issues with credits.

###`smb_server_max_threads_per_queue`
Uint32. Increasing this value raises the number of threads that the file server can use to service concurrent requests. When a large number of active connections need to be serviced, and hardware resources, such as storage bandwidth, are sufficient, increasing the value can improve server scalability, performance, and response times.

__valid integer range__: 1 - 4294967295

__default value__: 20

###`smb_server_treat_host_as_stable_storage`
bool. Set true to disables processing write flush commands from clients. If the value of this param is true, the server performance and client latency for power-protected servers can improve. Workloads that resemble the NetBench file server benchmark benefit from this behavior.

__default value__: false

__tweaking notes__: Note that if you have a clustered file server, it is possible that you may experience data loss if the server fails with this setting enabled. Therefore, evaluate it carefully prior to applying it. __THIS MODULE DOES NOT SUPPORT CLUSTERED SHARES UNDER CAFS__

###`smb_server_max_channel_per_session`
Uint32. Specifies the maximum channels per session.

__valid integer range__: 1 - 4294967295

__default value__: 32

__tweaking notes__: 64 / 128 didn't seem to explode a file server under load, seems a good starting point

###`smb_server_max_session_per_connection`
Uint32. Specifies the maximum sessions per connection.

__valid integer range__: 1 - 4294967295

__default value__: 16384

##Additional work threads
At system startup, Windows creates several server threads that operate as part of the System process. These are called system worker threads. They exist with the sole purpose of performing work on the behalf of other threads generated by the kernel, system device drivers, the system executive and other components. When one of these components puts a work item in a queue, a thread is assigned to process it.
The number of system worker threads should ideally be high enough to accept work tasks as soon as they become assigned. The trade off, of course, is that worker threads sitting idle consume system resources unnecessarily.

###`smb_server_additional_critical_worker_threads`
Uint32. The AdditionalCriticalWorkerThreads value increases the number of critical worker threads created for a specified work queue. Critical worker threads process time-critical work items and have their stack present in physical memory at all times. An insufficient number of threads will reduce the rate at which time-critical work items are serviced; a value that is too high will consume system resources unnecessarily.

The default is 0, which means that no additional critical kernel worker threads are added. This value affects the number of threads that the file system cache uses for read-ahead and write-behind requests. Raising this value can allow for more queued I/O in the storage subsystem, and it can improve I/O performance, particularly on systems with many logical processors and powerful storage hardware.

__valid integer range__: 0 - 4294967295

__default value__: 0

__tweaking notes__: The value may need to be increased if the amount of cache manager dirty data (performance counter Cache\Dirty Pages) is growing to consume a large portion (over ~25%) of memory or if the system is doing lots of synchronous read I/Os.

###`smb_server_additional_delayed_worker_threads`
Uint32. The AdditionalDelayedWorkerThreads value increases the number of delayed worker threads created for the specified work queue.

__valid integer range__: 0 - 4294967295

__default value__: 0

__tweaking notes__: Delayed worker threads process work items that are not considered time-critical and can have their memory stack paged out while waiting for work items. An insufficient number of threads will reduce the rate at which work items are serviced; a value that is too high will consume system resources unnecessarily.

###`smb_server_ntfs_8dot3_name_creation`
String equating to enum.  When a long file name is created using the Windows NTFS file system, the default behavior may be (OS version dependent) to generate a corresponding short file name in the older 8.3 DOS file name convention for compatibility with older operating systems. This functionality can be disabled.

__value values__: [string] - numerics correspond to the raw registry value controlling this setting, which equate to an enum in practice

* __'0' , 'enabled'__: 8.3 name creation is enabled
* __'1' , 'disabled'__: 8.3 name creation is disabled
* __'2' , 'per_volume'__: 8.3 name creation can be configured on a per volume basis

###`smb_server_ntfs_disable_last_access_update`
The default is 1 in newer Windows versions. In versions of Windows earlier than Windows Vista and Windows Server 2008, the default is 0.

__default value__: undef   <<< don't know what OS is being run.

__N.B.__: `ensure => 'default'` will set value to 1 - this will DISABLE last access timestamp updates.

__valid values__:

* __true__:  DISABLE last access timestamp updates
* __false__: ENABLE last access timestamp updates

__tweaking notes__: A value of 0 can reduce performance because the system performs additional storage I/O when files and directories are accessed to update date and time information.

#`windows_smb::manage_smb_client_config`
Avoided `EnableInsecureGuestLogons` as only available windows 10 / server 2016 and documentation I found simply says 'TBD'. so no.

Avoided `EnableLoadBalanceScaleOut` - I do not know enough about impact of this.  Tell me and I'll add it.

Avoided `RequireSecuritySignature` - typically options for client/server digital signing / encryption handled in organization via GPO.  Yes, we can replace a lot of whats going on there with puppet code but at this time I deem that invasive to the Windows OS platform as typically managed in an enterprise.

Manage smb client settings on node.  suggest name resource like so for sanity across your catalog: `windows_smb::manage_smb_client_config{$::clientcert: ensure => present, ...}`

##`windows_smb::manage_smb_client_config` parameters
Sensible caps on resource params are not implemented.  You may tweak up to the maximum allowed value and it is assumed you will research impact on system performance / viability to serve.  Good luck, have fun!

####`ensure`
Set the ensure state of the smb share. string.

* __'present'__: will ensure the smb client config exists and is set as desired
* __'default'__: 'default' will reset node values to sensible OS defaults.  These may or may not be the most optimal for node use case.

__default value__: 'present'

###`smb_client_connection_count_per_interface`
Uint32. Specifies the maximum connections per interface to be established with a smb server running Windows Server for non-RSS interfaces.

__valid integer range__: 1 - 16

__default value__: 1

###`smb_client_connection_count_per_rss_interface`
Uint32. Specifies the maximum connections per rss interface to be established with a server running Windows Server 2012 for RSS interfaces.

__valid integer range__: 1 - 16

__default value__: 4

###`smb_client_connection_count_per_rdma_interface`
Uint32. Specifies the maximum connections per rss interface to be established with a server running Windows Server 2012 for RDMA interfaces.

__valid integer range__: 1 - 16

__default value__: 2

###`smb_client_connection_count_per_server_max`
Uint32. Specifies the maximum number of connections to be established with a single smb server running Windows across all interfaces.

__valid integer range__: 1 - 64

__default value__: 32

###`smb_client_dormant_directory_timeout_seconds`
Uint32. Specifies the maximum time server directory handles held open with directory leases.

__valid integer range__: 0 - 4294967295

__default value__: 600

###`smb_client_directory_cache_lifetime_seconds`
Uint32. Specifies the directory cache timeout.  This parameter controls caching of directory metadata in the absence of directory leases.

__valid integer range__: 0 - 4294967295

__default value__: 10

###`smb_client_dormant_file_limit`
Uint32. Specifies the maximum number of files that should be left open on a shared resource after the application has closed the file.

__valid integer range__: 1 - 4294967295

__default value__: 1023

###`smb_client_directory_cache_entry_size_max_bytes`
Uint32. in bytes. Specifies the maximum size of directory cache entries. The default is 64KB.  Can be increased to max of 16MB.

__valid integer range__: 65536 - 16777216

__default value__: 1023

__tweaking notes__: try 16777216

###`smb_client_directory_cache_entries_max`
Uint32. in bytes. Specifies the amount of directory information that can be cached by the client. Increasing the value can reduce network traffic and increase performance when large directories are accessed.

__valid integer range__: 1 - 4096

__default value__: 16

__tweaking notes__: recommend set to 4096 - ref: <https://msdn.microsoft.com/en-us/library/windows/hardware/dn567661(v=vs.85).aspx>

###`smb_client_file_not_found_cache_lifetime_seconds`
Uint32. in bytes. Specifies the amount of directory information that can be cached by the client. Increasing the value can reduce network traffic and increase performance when large directories are accessed.

__valid integer range__: 0 - 4294967295

__default value__: 5

__tweaking notes__: try increase, e.g. 10 or more, use with `smb_client_file_not_found_cache_entries_max`

###`smb_client_file_not_found_cache_entries_max`
Uint32. Specifies the amount of file name information that can be cached by the client. Increasing the value can reduce network traffic and increase performance when a large number of file names are accessed.

__valid integer range__: 1 - 65536

__default value__: 128

__tweaking notes__: try increase, use with  `smb_client_file_not_found_cache_lifetime_seconds` - suggest 32768 - ref: <https://msdn.microsoft.com/en-us/library/windows/hardware/dn567661(v=vs.85).aspx>

###`smb_client_file_info_cache_lifetime_seconds`
Uint32. The file information cache timeout period.

__valid integer range__: 0 - 4294967295

__default value__: 10

__tweaking notes__: try increase, 15 or more. use with `smb_client_file_info_cache_entries_max`

###`smb_client_file_info_cache_entries_max`
Uint32. Specifies the amount of file metadata that can be cached by the client. Increasing the value can reduce network traffic and increase performance when a large number of files are accessed.

__valid integer range__: 1 - 65536

__default value__: 64

__tweaking notes__: suggest 32768 - ref: <https://msdn.microsoft.com/en-us/library/windows/hardware/dn567661(v=vs.85).aspx>

###`smb_client_enable_bandwidth_throttling`
bool. the SMB redirector throttles throughput across high-latency network connections, in some cases to avoid network-related timeouts. Setting this param to false may result in higher file transfer throughput over high-latency network connections.

__valid values__:

* __true__:  ENABLE bandwidth throttling
* __false__: DISABLE bandwidth throttling

__default value__: true

__tweaking notes__: suggest false - ref: <https://msdn.microsoft.com/en-us/library/windows/hardware/dn567661(v=vs.85).aspx>

###`smb_client_enable_large_mtu`
bool. if enabled (true) the SMB redirector transfers payloads as large as 1 MB per request, which can improve file transfer speed. if disabled, limited to 64 KB.

__valid values__:

* __true__:  ENABLE large MTU
* __false__: DISABLE large MTU

__default value__: true

###`smb_client_enable_byte_range_locking_read_only_files`
bool. Controls whether byte-range locking is enabled on read-only files.

__valid values__:

* __true__:  ENABLE byte-range locking on read-only files
* __false__: DISABLE byte-range locking on read-only files

__default value__: true

###`smb_client_enable_multichannel`
bool. Enable or disable the use of multiple physical network interfaces.

__valid values__:

* __true__:  ENABLE use of multiple physical network interfaces
* __false__: DISABLE use of multiple physical network interfaces

__default value__: true

###`smb_client_extended_session_timeout_seconds`
Uint32. extended session timeout in seconds.

__valid integer range__: 0 - 4294967295

__default value__: 1000

###`smb_client_keep_connection_seconds`
Uint32. How long to keep an smb session open.

__valid integer range__: 0 - 4294967295

__default value__: 600

###`smb_client_max_commands`
Uint32.  Specifies the maximum number of network control blocks that the redirector can reserve. The value of this entry coincides with the number of execution threads that can be outstanding simultaneously.

__valid integer range__: 0 - 4294967295

__default value__: 50

###`smb_client_oplocks_disabled`
bool. set this true if opportunistic locking is to be disabled. See `smb_client_use_opportunistic_locking`.  did not mask this setting into one thing as want to expose as much as possible raw in this module.

__valid values__:

* __true__:  DISABLE use of opportunistic locking
* __false__: ENABLE use of opportunistic locking

__default value__: false

__tweaking notes__: I don't know what you want to do as a devops person / admin / engineer / architect / whatever we're called today; so you're getting both setting exposed and are not locked to setting both in tandem.  Though this is suggested. see `smb_client_use_opportunistic_locking`

###`smb_client_use_opportunistic_locking`
Controls whether the opportunistic-locking (oplock) performance enhancement is enabled. If true, the redirector requests an opportunistic lock on any file opened in "Deny None" mode. As a result, the server performs automatic read-ahead and write-behind caching on behalf of the redirector.

__valid values__:

* __true__:  ENABLE use of opportunistic locking
* __false__: DISABLE use of opportunistic locking

__default value__: true

__tweaking notes__: there may be interference if this is used in certain scenarios but for general use (and os default) sounds like a good idea to use.  leave `smb_client_oplocks_disabled` not specified as a param or specify false for `smb_client_oplocks_disabled` if you want op locking ON.

###`smb_client_session_timeout_seconds`
Uint32. The number of seconds that the client waits before disconnecting an inactive session.

__valid integer range__: 10 - 65535

__default value__: 60

###`smb_client_window_size_threshold`
Uint32. The minimum window size before Multichannel will trigger the use of multiple connections.

__valid integer range__: 10 - 65535

__default value__: 1

__tweaking notes__: The default value is 1 for Windows Server operating systems and 8 for Windows client operating systems.  This module uses 1 as default.  It won't kill the workstation and is what server wants.

References
--
__Set-SmbShare documentation__: <https://technet.microsoft.com/en-us/%5Clibrary/jj635727(v=wps.630).aspx>

__Set-SmbServerConfiguration__: <https://technet.microsoft.com/en-us/library/jj635714(v=wps.630).aspx>

__Performance Tuning for File Servers__: <https://msdn.microsoft.com/en-us/library/windows/hardware/dn567661(v=vs.85).aspx>

__Optimizing Operating System Performance__: <https://msdn.microsoft.com/en-us/library/cc615012(v=bts.10).aspx>

__CIFS and SMB Timeouts in Windows__: <https://blogs.msdn.microsoft.com/openspecification/2013/03/19/cifs-and-smb-timeouts-in-windows/>

__SetConfiguration method of the MSFT_SmbClientConfiguration class__: <https://msdn.microsoft.com/en-us/library/hh830477(v=vs.85).aspx>


text:
 #
 #  Filename    : versioncheck.py
 #  Description : Functions for detecting require tool version
 #  Author      : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
 #
#*******************************************************************************

from distutils.version import LooseVersion
import sys
import subprocess

python_version_min = (2,7)
python_version_max = (3,0)
xrdfs_version_min = "4.2.1"

def CheckVersionReq():

    requirements="""
    Requirements:
      - python{0}
      - xrdfs > {1}
    """.format(
        ".".join( str(x) for  x in python_version_min ) ,
        xrdfs_version_min
    )
    pyversion_str = [ str(x) for x in sys.version_info ]
    pyversion_str = '.'.join( pyversion_str )

    if sys.version_info >= python_version_max:
        print "Your python is too new! ", pyversion_str
        print requirements
        raise Exception("Version Error")
    if sys.version_info <  python_version_min:
        print "Your python is too old! ", pyversion_str
        print requirements
        raise Exception("Version Error")

    proc = subprocess.Popen(
        ["xrdcp", "--version" ],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE
    )
    out, xrdversion = proc.communicate()

    if xrdversion.startswith('v'):
        xrdversion = xrdversion.strip("v")
    if LooseVersion(xrdversion) < LooseVersion(xrdfs_version_min):
        print "You xrdfs is too old!", xrdversion
        print requirements
        raise Exception("Version Error")

if __name__ == "__main__" :
    CheckVersionReq()


text:
<!-- Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.yahoo.vespa</groupId>
        <artifactId>parent</artifactId>
        <version>8-SNAPSHOT</version>
        <relativePath>../parent/pom.xml</relativePath>
    </parent>
    <artifactId>clustercontroller-utils</artifactId>
    <version>8-SNAPSHOT</version>
    <packaging>container-plugin</packaging>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>
        <dependency>
            <groupId>com.yahoo.vespa</groupId>
            <artifactId>annotations</artifactId>
            <version>${project.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.yahoo.vespa</groupId>
            <artifactId>vespajlib</artifactId>
            <version>${project.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>com.yahoo.vespa</groupId>
                <artifactId>bundle-plugin</artifactId>
                <extensions>true</extensions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


text:
// This code is distributed under MIT license. Copyright (c) 2013 George Mamaladze
// See license.txt or http://opensource.org/licenses/mit-license.php
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;

namespace Gma.DataStructures.StringSearch.Test.TestCaseGeneration
{
    public static class NonsenseGeneration
    {
        public const int DefaultAverageWordCount = 15;
        public const string VocabularyFileName = "english-words.txt";

        public static string[] GetVocabulary()
        {
            return GetWords(VocabularyFileName).ToArray();
        }

        public static IEnumerable<IEnumerable<string>> GetRandomSentences(string[] vocabulary,
                                                                          int sentenceCount,
                                                                          int averageWordCount = DefaultAverageWordCount)
        {
            var random = new Random();
            int wordCount = random.Next(2 * averageWordCount) + 1;
            for (int i = 0; i < sentenceCount; i++)
            {
                yield return GetRandomWords(vocabulary, wordCount, random);
            }
        }

        public static IEnumerable<string> GetRandomWords(string[] vocabulary, int wordCount)
        {
            return GetRandomWords(vocabulary, wordCount, new Random());
        }

        public static IEnumerable<string> GetRandomNeighbourWordGroups(string[] vocabulary, int wordCount)
        {
            var words = new Stack<string>();
            var random = new Random();
            while (words.Count<wordCount)
            {
                foreach (var neighbour in GetRandomNeighbourWords(vocabulary, random, 3))
                {
                    words.Push(neighbour);
                }
            }
            return words.Take(wordCount);
        }

        public static IEnumerable<string> GetRandomWords(string[] vocabulary, int wordCount, Random random)
        {
            for (int i = 0; i < wordCount; i++)
            {
                var randomWord = GetRandomWord(vocabulary, random);
                if (string.IsNullOrEmpty(randomWord)) continue;
                yield return randomWord;
            }
        }

        private static string GetRandomWord(string[] vocabulary, Random random)
        {
            int randomIndex = random.Next(vocabulary.Length);
            return vocabulary[randomIndex];
        }

        private static IEnumerable<string> GetRandomNeighbourWords(string[] vocabulary, Random random, int neighbourCount)
        {
            int randomIndex = random.Next(vocabulary.Length);
            for (int i = 0; i < neighbourCount; i++)
            {
                yield return vocabulary[randomIndex];
                randomIndex = randomIndex + random.Next(5);
                if (randomIndex>=vocabulary.Length)
                {
                    yield break;
                }
            }

        }

        public static IEnumerable<string> GetWords(string fileName)
        {
            var assembly = Assembly.GetExecutingAssembly();
            var resourceName = typeof(NonsenseGeneration).Namespace + "." + fileName;
            using (var stream = assembly.GetManifestResourceStream(resourceName))
            {
                Debug.Assert(stream != null, $"Could not find resource {resourceName}");
                using (var file = new StreamReader(stream))
                {
                    var word = new StringBuilder();
                    while (!file.EndOfStream)
                    {
                        string line = file.ReadLine() ?? String.Empty;
                        foreach (char ch in line)
                        {
                            if (Char.IsLetterOrDigit(ch))
                            {
                                word.Append(ch);
                            }
                            else
                            {
                                yield return word.ToString();
                                word.Clear();
                            }
                        }
                        if (word.Length == 0) continue;
                        yield return word.ToString();
                        word.Clear();
                    }
                }
            }
        }
    }
}


text:
<def-group>
  <definition class="compliance" id="no_insecure_locks_exports" version="1">
    <metadata>
      <title>Ensure insecure_locks is disabled</title>
      <affected family="unix">
        <platform>Red Hat Enterprise Linux 6</platform>
        <platform>Red Hat Enterprise Linux 7</platform>
        <platform>Fedora 20</platform>
      </affected>
      <description>Allowing insecure file locking could allow for sensitive
      data to be viewed or edited by an unauthorized user.</description>
      <reference source="galford" ref_id="20140813" ref_url="test_attestation" />
    </metadata>
    <criteria>
      <criterion comment="Check for insecure NFS locks in /etc/exports"
      test_ref="test_no_insecure_locks_exports" />
    </criteria>
  </definition>
  <ind:textfilecontent54_test check="all" check_existence="none_exist"
  comment="Tests the value of the insecure locks in /etc/exports"
  id="test_no_insecure_locks_exports" version="1">
    <ind:object object_ref="obj_no_insecure_locks_exports" />
  </ind:textfilecontent54_test>
  <ind:textfilecontent54_object id="obj_no_insecure_locks_exports"
  version="2">
    <ind:filepath>/etc/exports</ind:filepath>
    <ind:pattern operation="pattern match">^(.*?(\binsecure_locks\b)[^$]*)$</ind:pattern>
    <ind:instance datatype="int">1</ind:instance>
  </ind:textfilecontent54_object>
</def-group>