text:
from __future__ import annotations

from unittest import TestCase, mock

from google.api_core.gapic_v1.method import _MethodDefault
from google.api_core.retry import Retry
from google.protobuf.field_mask_pb2 import FieldMask

from airflow.providers.google.cloud.operators.dataproc_metastore import (
    DataprocMetastoreCreateBackupOperator,
    DataprocMetastoreCreateMetadataImportOperator,
    DataprocMetastoreCreateServiceOperator,
    DataprocMetastoreDeleteBackupOperator,
    DataprocMetastoreDeleteServiceOperator,
    DataprocMetastoreExportMetadataOperator,
    DataprocMetastoreGetServiceOperator,
    DataprocMetastoreListBackupsOperator,
    DataprocMetastoreRestoreServiceOperator,
    DataprocMetastoreUpdateServiceOperator,
)

TASK_ID: str = "task_id"
GCP_LOCATION: str = "test-location"
GCP_PROJECT_ID: str = "test-project-id"

GCP_CONN_ID: str = "test-gcp-conn-id"
IMPERSONATION_CHAIN = ["ACCOUNT_1", "ACCOUNT_2", "ACCOUNT_3"]

TEST_SERVICE: dict = {"name": "test-service"}
TEST_SERVICE_ID: str = "test-service-id"

TEST_TIMEOUT = 120
TEST_RETRY: Retry | _MethodDefault = mock.MagicMock(Retry)
TEST_METADATA = [("key", "value")]
TEST_REQUEST_ID = "request_id_uuid"

TEST_BACKUP: dict = {"name": "test-backup"}
TEST_BACKUP_ID: str = "test-backup-id"
TEST_METADATA_IMPORT: dict = {
    "name": "test-metadata-import",
    "database_dump": {
        "gcs_uri": "gs://bucket_name/path_inside_bucket",
        "database_type": "MYSQL",
    },
}
TEST_METADATA_IMPORT_ID: str = "test-metadata-import-id"
TEST_SERVICE_TO_UPDATE = {
    "labels": {
        "first_key": "first_value",
        "second_key": "second_value",
    }
}
TEST_UPDATE_MASK: FieldMask = FieldMask(paths=["labels"])
TEST_DESTINATION_GCS_FOLDER: str = "gs://bucket_name/path_inside_bucket"

class TestDataprocMetastoreCreateBackupOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.Backup")
    def test_assert_valid_hook_call(self, mock_backup, mock_hook) -> None:
        task = DataprocMetastoreCreateBackupOperator(
            task_id=TASK_ID,
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            backup=TEST_BACKUP,
            backup_id=TEST_BACKUP_ID,
            service_id=TEST_SERVICE_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_hook.return_value.wait_for_operation.return_value = None
        mock_backup.return_value.to_dict.return_value = None
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.create_backup.assert_called_once_with(
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            backup=TEST_BACKUP,
            backup_id=TEST_BACKUP_ID,
            service_id=TEST_SERVICE_ID,
            request_id=None,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
        )

class TestDataprocMetastoreCreateMetadataImportOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.MetadataImport")
    def test_assert_valid_hook_call(self, mock_metadata_import, mock_hook) -> None:
        task = DataprocMetastoreCreateMetadataImportOperator(
            task_id=TASK_ID,
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            service_id=TEST_SERVICE_ID,
            metadata_import=mock_metadata_import(name=TEST_METADATA_IMPORT),
            metadata_import_id=TEST_METADATA_IMPORT_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_hook.return_value.wait_for_operation.return_value = None
        mock_metadata_import.return_value.to_dict.return_value = None
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.create_metadata_import.assert_called_once_with(
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            service_id=TEST_SERVICE_ID,
            metadata_import=mock_metadata_import(name=TEST_METADATA_IMPORT),
            metadata_import_id=TEST_METADATA_IMPORT_ID,
            request_id=None,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
        )

class TestDataprocMetastoreCreateServiceOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.Service")
    def test_execute(self, mock_service, mock_hook) -> None:
        task = DataprocMetastoreCreateServiceOperator(
            task_id=TASK_ID,
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service=TEST_SERVICE,
            service_id=TEST_SERVICE_ID,
            request_id=TEST_REQUEST_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_hook.return_value.wait_for_operation.return_value = None
        mock_service.return_value.to_dict.return_value = None
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.create_service.assert_called_once_with(
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service=TEST_SERVICE,
            service_id=TEST_SERVICE_ID,
            request_id=TEST_REQUEST_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
        )

class TestDataprocMetastoreDeleteBackupOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    def test_assert_valid_hook_call(self, mock_hook) -> None:
        task = DataprocMetastoreDeleteBackupOperator(
            task_id=TASK_ID,
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            retry=TEST_RETRY,
            service_id=TEST_SERVICE_ID,
            backup_id=TEST_BACKUP_ID,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_hook.return_value.wait_for_operation.return_value = None
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.delete_backup.assert_called_once_with(
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            service_id=TEST_SERVICE_ID,
            backup_id=TEST_BACKUP_ID,
            request_id=None,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
        )

class TestDataprocMetastoreDeleteServiceOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    def test_execute(self, mock_hook) -> None:
        task = DataprocMetastoreDeleteServiceOperator(
            task_id=TASK_ID,
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service_id=TEST_SERVICE_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_hook.return_value.wait_for_operation.return_value = None
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.delete_service.assert_called_once_with(
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service_id=TEST_SERVICE_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
        )

class TestDataprocMetastoreExportMetadataOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.MetadataExport")
    @mock.patch(
        "airflow.providers.google.cloud.operators.dataproc_metastore"
        ".DataprocMetastoreExportMetadataOperator._wait_for_export_metadata"
    )
    def test_assert_valid_hook_call(self, mock_wait, mock_export_metadata, mock_hook) -> None:
        task = DataprocMetastoreExportMetadataOperator(
            task_id=TASK_ID,
            service_id=TEST_SERVICE_ID,
            destination_gcs_folder=TEST_DESTINATION_GCS_FOLDER,
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_wait.return_value = None
        mock_export_metadata.return_value.to_dict.return_value = None
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.export_metadata.assert_called_once_with(
            database_dump_type=None,
            destination_gcs_folder=TEST_DESTINATION_GCS_FOLDER,
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            service_id=TEST_SERVICE_ID,
            request_id=None,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
        )

class TestDataprocMetastoreGetServiceOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.Service")
    def test_execute(self, mock_service, mock_hook) -> None:
        task = DataprocMetastoreGetServiceOperator(
            task_id=TASK_ID,
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service_id=TEST_SERVICE_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_hook.return_value.wait_for_operation.return_value = None
        mock_service.return_value.to_dict.return_value = None
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.get_service.assert_called_once_with(
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service_id=TEST_SERVICE_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
        )

class TestDataprocMetastoreListBackupsOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.Backup")
    def test_assert_valid_hook_call(self, mock_backup, mock_hook) -> None:
        task = DataprocMetastoreListBackupsOperator(
            task_id=TASK_ID,
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            service_id=TEST_SERVICE_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_hook.return_value.wait_for_operation.return_value = None
        mock_backup.return_value.to_dict.return_value = None
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.list_backups.assert_called_once_with(
            project_id=GCP_PROJECT_ID,
            region=GCP_LOCATION,
            service_id=TEST_SERVICE_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            filter=None,
            order_by=None,
            page_size=None,
            page_token=None,
        )

class TestDataprocMetastoreRestoreServiceOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    @mock.patch(
        "airflow.providers.google.cloud.operators.dataproc_metastore"
        ".DataprocMetastoreRestoreServiceOperator._wait_for_restore_service"
    )
    def test_assert_valid_hook_call(self, mock_wait, mock_hook) -> None:
        task = DataprocMetastoreRestoreServiceOperator(
            task_id=TASK_ID,
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service_id=TEST_SERVICE_ID,
            backup_id=TEST_BACKUP_ID,
            backup_region=GCP_LOCATION,
            backup_project_id=GCP_PROJECT_ID,
            backup_service_id=TEST_SERVICE_ID,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        mock_wait.return_value = None
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.restore_service.assert_called_once_with(
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service_id=TEST_SERVICE_ID,
            backup_id=TEST_BACKUP_ID,
            backup_region=GCP_LOCATION,
            backup_project_id=GCP_PROJECT_ID,
            backup_service_id=TEST_SERVICE_ID,
            restore_type=None,
            request_id=None,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
        )

class TestDataprocMetastoreUpdateServiceOperator(TestCase):
    @mock.patch("airflow.providers.google.cloud.operators.dataproc_metastore.DataprocMetastoreHook")
    def test_assert_valid_hook_call(self, mock_hook) -> None:
        task = DataprocMetastoreUpdateServiceOperator(
            task_id=TASK_ID,
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service_id=TEST_SERVICE_ID,
            service=TEST_SERVICE_TO_UPDATE,
            update_mask=TEST_UPDATE_MASK,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
            gcp_conn_id=GCP_CONN_ID,
            impersonation_chain=IMPERSONATION_CHAIN,
        )
        task.execute(context=mock.MagicMock())
        mock_hook.assert_called_once_with(gcp_conn_id=GCP_CONN_ID, impersonation_chain=IMPERSONATION_CHAIN)
        mock_hook.return_value.update_service.assert_called_once_with(
            region=GCP_LOCATION,
            project_id=GCP_PROJECT_ID,
            service_id=TEST_SERVICE_ID,
            service=TEST_SERVICE_TO_UPDATE,
            update_mask=TEST_UPDATE_MASK,
            request_id=None,
            retry=TEST_RETRY,
            timeout=TEST_TIMEOUT,
            metadata=TEST_METADATA,
        )


text:
namespace EZOper.NetSiteUtilities.Jayrock
{
    public sealed class EmptyJsonWriter : JsonWriterBase
    {
        protected override void WriteStartObjectImpl() {}
        protected override void WriteEndObjectImpl() {}
        protected override void WriteMemberImpl(string name) {}
        protected override void WriteStartArrayImpl() {}
        protected override void WriteEndArrayImpl() {}
        protected override void WriteStringImpl(string value) {}
        protected override void WriteNumberImpl(string value) {}
        protected override void WriteBooleanImpl(bool value) {}
        protected override void WriteNullImpl() {}
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.component.socket.processing;

import java.util.logging.Logger;

import com.component.socket.threading.ClientListenerThread;

/**
 * Processing protocol for clientListener threads.
 *
 * Data is passed into this class' only method, "processInput()", in the form of a serialized JSON
 * string. The method then processes the input, which usually involves queuing it on the
 * serverListener thread's queue (or, as we say, "passing the buck").
 *
 * @author Colin Lam
 */
public class ClientListenerProtocol {

    /**
     * Parse a string and perform an action based on its format.
     *
     * The bulk action will be queuing up the incoming data on another thread, which will process
     * it. For the most part, serialized objects will be queued on the serverListener's queue.
     *
     * @param inputLine
     *   String to be parsed.
     * @param clientListener
     *   The clientListenerThread to send this input to.
     */
    public void processInput(String inputLine, ClientListenerThread clientListener) {
        // Log the incoming string.
        Logger logger = Logger.getLogger("global");
        logger.info("INCOMING DATA: " + inputLine);

        // Immediately queue data on the serverListener, without doing anything.
        ServerRequest newRequest = new ServerRequest();
        newRequest.setCentralProcessorResponse(false);
        newRequest.setStringData(inputLine);
        clientListener.getServerListenerThread().queue(newRequest);
    }
}


text:
using System.Drawing;
using System.Drawing.Drawing2D;

namespace WeifenLuo.WinFormsUI.Docking.Skins
{
    internal static class DockPanelSkinBuilder
    {
        public static DockPanelSkin Create(Style style)
        {
            switch (style)
            {
                case Style.VisualStudio2005:
                default:
                    return CreateVisualStudio2005();
            }
        }

        private static DockPanelSkin CreateVisualStudio2005()
        {
            DockPanelSkin skin = new DockPanelSkin();

            skin.AutoHideStripSkin.DockStripGradient.StartColor = SystemColors.ControlLight;
            skin.AutoHideStripSkin.DockStripGradient.EndColor = SystemColors.ControlLight;
            skin.AutoHideStripSkin.TabGradient.TextColor = SystemColors.ControlDarkDark;

            skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.StartColor = SystemColors.Control;
            skin.DockPaneStripSkin.DocumentGradient.DockStripGradient.EndColor = SystemColors.Control;
            skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.StartColor = SystemColors.ControlLightLight;
            skin.DockPaneStripSkin.DocumentGradient.ActiveTabGradient.EndColor = SystemColors.ControlLightLight;
            skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.StartColor = SystemColors.ControlLight;
            skin.DockPaneStripSkin.DocumentGradient.InactiveTabGradient.EndColor = SystemColors.ControlLight;

            skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.StartColor = SystemColors.ControlLight;
            skin.DockPaneStripSkin.ToolWindowGradient.DockStripGradient.EndColor = SystemColors.ControlLight;

            skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.StartColor = SystemColors.Control;
            skin.DockPaneStripSkin.ToolWindowGradient.ActiveTabGradient.EndColor = SystemColors.Control;

            skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.StartColor = Color.Transparent;
            skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.EndColor = Color.Transparent;
            skin.DockPaneStripSkin.ToolWindowGradient.InactiveTabGradient.TextColor = SystemColors.ControlDarkDark;

            skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.StartColor = SystemColors.GradientActiveCaption;
            skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.EndColor = SystemColors.ActiveCaption;
            skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical;
            skin.DockPaneStripSkin.ToolWindowGradient.ActiveCaptionGradient.TextColor = SystemColors.ActiveCaptionText;

            skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.StartColor = SystemColors.GradientInactiveCaption;
            skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.EndColor = SystemColors.InactiveCaption;
            skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.LinearGradientMode = LinearGradientMode.Vertical;
            skin.DockPaneStripSkin.ToolWindowGradient.InactiveCaptionGradient.TextColor = SystemColors.InactiveCaptionText;

            return skin;
        }

    }
}


text:
package ec2

import (
	"context"
	awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
	"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
	"github.com/aws/aws-sdk-go-v2/service/ec2/types"
	"github.com/aws/smithy-go/middleware"
	smithyhttp "github.com/aws/smithy-go/transport/http"
)

// Gets the content for the specified Network Access Scope.
func (c *Client) GetNetworkInsightsAccessScopeContent(ctx context.Context, params *GetNetworkInsightsAccessScopeContentInput, optFns ...func(*Options)) (*GetNetworkInsightsAccessScopeContentOutput, error) {
	if params == nil {
		params = &GetNetworkInsightsAccessScopeContentInput{}
	}

	result, metadata, err := c.invokeOperation(ctx, "GetNetworkInsightsAccessScopeContent", params, optFns, c.addOperationGetNetworkInsightsAccessScopeContentMiddlewares)
	if err != nil {
		return nil, err
	}

	out := result.(*GetNetworkInsightsAccessScopeContentOutput)
	out.ResultMetadata = metadata
	return out, nil
}

type GetNetworkInsightsAccessScopeContentInput struct {

	// The ID of the Network Access Scope.
	//
	// This member is required.
	NetworkInsightsAccessScopeId *string

	// Checks whether you have the required permissions for the action, without
	// actually making the request, and provides an error response. If you have the
	// required permissions, the error response is DryRunOperation. Otherwise, it is
	// UnauthorizedOperation.
	DryRun *bool

	noSmithyDocumentSerde
}

type GetNetworkInsightsAccessScopeContentOutput struct {

	// The Network Access Scope content.
	NetworkInsightsAccessScopeContent *types.NetworkInsightsAccessScopeContent

	// Metadata pertaining to the operation's result.
	ResultMetadata middleware.Metadata

	noSmithyDocumentSerde
}

func (c *Client) addOperationGetNetworkInsightsAccessScopeContentMiddlewares(stack *middleware.Stack, options Options) (err error) {
	err = stack.Serialize.Add(&awsEc2query_serializeOpGetNetworkInsightsAccessScopeContent{}, middleware.After)
	if err != nil {
		return err
	}
	err = stack.Deserialize.Add(&awsEc2query_deserializeOpGetNetworkInsightsAccessScopeContent{}, middleware.After)
	if err != nil {
		return err
	}
	if err = addSetLoggerMiddleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddClientRequestIDMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddComputeContentLengthMiddleware(stack); err != nil {
		return err
	}
	if err = addResolveEndpointMiddleware(stack, options); err != nil {
		return err
	}
	if err = v4.AddComputePayloadSHA256Middleware(stack); err != nil {
		return err
	}
	if err = addRetryMiddlewares(stack, options); err != nil {
		return err
	}
	if err = addHTTPSignerV4Middleware(stack, options); err != nil {
		return err
	}
	if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil {
		return err
	}
	if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil {
		return err
	}
	if err = addClientUserAgent(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil {
		return err
	}
	if err = addOpGetNetworkInsightsAccessScopeContentValidationMiddleware(stack); err != nil {
		return err
	}
	if err = stack.Initialize.Add(newServiceMetadataMiddleware_opGetNetworkInsightsAccessScopeContent(options.Region), middleware.Before); err != nil {
		return err
	}
	if err = addRequestIDRetrieverMiddleware(stack); err != nil {
		return err
	}
	if err = addResponseErrorMiddleware(stack); err != nil {
		return err
	}
	if err = addRequestResponseLogging(stack, options); err != nil {
		return err
	}
	return nil
}

func newServiceMetadataMiddleware_opGetNetworkInsightsAccessScopeContent(region string) *awsmiddleware.RegisterServiceMetadata {
	return &awsmiddleware.RegisterServiceMetadata{
		Region:        region,
		ServiceID:     ServiceID,
		SigningName:   "ec2",
		OperationName: "GetNetworkInsightsAccessScopeContent",
	}
}


text:
package pjson

import (
	"fmt"
	"reflect"

	p "github.com/Dwarfartisan/goparsec2"
)

// Skip 忽略匹配指定算子的内容
var Skip = p.Skip(p.Space)

// Comma 逗号分隔符
var Comma = p.Str(",")

// Colon 冒号分隔符
var Colon = p.Str(":")

func listBodyParser(st p.State) (interface{}, error) {
	value, err := p.SepBy(ValueParser(), Skip.Then(Comma).Then(Skip))(st)
	return value, err
}

// ListParser 实现数组解析器
func ListParser() p.P {
	return func(st p.State) (interface{}, error) {
		left := p.Chr('[').Then(Skip)
		right := Skip.Then(p.Chr(']'))
		empty := p.Between(left, right, Skip)

		//		list, err := p.Between(left, right, p.UnionAll(listBodyParser))(st)
		list, err := p.Between(left, right, listBodyParser)(st)

		if err != nil {
			_, e := empty(st)
			if e != nil {
				return nil, err
			}
			return List{}, nil
		}

		switch l := list.(type) {
		case List:
			return L(l), nil
		case []interface{}:
			return list.([]interface{}), nil
		default:
			return nil, fmt.Errorf("List Parser Error: %v type is unexpected: %v", list, reflect.TypeOf(list))
		}
	}
}

// key只能是string,value可以为任意值,中间以冒号分隔
func objectKeyValueParser() p.P {
	return func(st p.State) (interface{}, error) {
		pair := Pair{}
		s, err := Skip.Then(StringParser)(st)
		if err != nil {
			return nil, err
		}

		if str, ok := s.(string); ok {
			pair.Key = str
		} else {
			return nil, fmt.Errorf("%v is not a string", s)
		}

		_, err = Skip.Then(Colon).Then(Skip)(st)
		if err != nil {
			return nil, err
		}

		v, err := ValueParser()(st)
		if err != nil {
			return nil, err
		}

		pair.Value = v

		return pair, nil
	}
}

// key,value通过逗号进行分隔,类似list处理
func objectBodyParser(st p.State) (interface{}, error) {
	value, err := p.SepBy(objectKeyValueParser(), Skip.Then(Comma).Then(Skip))(st)
	if err != nil {
		return nil, err
	}

	o := Object{}
	if vlist, ok := value.([]interface{}); ok {
		for _, p := range vlist {
			if pair, ok := p.(Pair); ok {
				o[pair.Key] = pair.Value
			}
		}
	}

	return o, nil
}

// ObjectParser 实现数组解析器
func ObjectParser() p.P {
	return func(st p.State) (interface{}, error) {
		left := p.Chr('{').Then(Skip)
		right := Skip.Then(p.Chr('}'))
		empty := p.Between(left, right, Skip)

		object, err := p.Between(left, right, objectBodyParser)(st)
		if err != nil {
			_, e := empty(st)
			if e != nil {
				return nil, err
			}
			return Object{}, nil
		}

		switch o := object.(type) {
		case Object:
			return O(o), nil
		case map[string]interface{}:
			return object.(map[string]interface{}), nil
		default:
			return nil, fmt.Errorf("Object Parser Error: %v type is unexpected: %v", object, reflect.TypeOf(object))
		}

	}
}

// ValueParser 实现简单的值解释器
func ValueParser() p.P {
	return func(st p.State) (interface{}, error) {
		value, err := p.Choice(p.Try(StringParser),
			p.Try(FloatParser),
			p.Try(ObjectParser()),
			p.Try(ListParser()),
			p.Try(BoolParser),
			p.Try(NullParser),
		)(st)

		return value, err
	}
}


text:
Welcome!
========

This library contains the scripts and configuration files to install
Big Switch Network OpenStack modules and IVS to enable a Big Switch
Networks fabric as Openstack Neutron backend.

External Resources:
===================

Big Switch Networks Website: http://www.bigswitch.com


text:
require_relative 'request'
require_relative 'response_logger'
require_relative 'null_logger'

module Carto
  module Http

    class Client

      private_class_method :new

      def self.get(tag, extra_options = {})
        logger = build_logger(tag, extra_options)
        new(logger)
      end

      def self.build_logger(tag, extra_options)
        if extra_options[:log_requests] && ResponseLogger.enabled?
          ResponseLogger.new(tag)
        else
          NullLogger.new()
        end
      end

      # Returns a wrapper to a typhoeus request object
      def request(url, options = {})
        Request.new(@logger, url, options)
      end

      def get(url, options = {})
        perform_request(__method__, url, options)
      end

      def post(url, options = {})
        perform_request(__method__, url, options)
      end

      def head(url, options = {})
        perform_request(__method__, url, options)
      end

      def put(url, options = {})
        perform_request(__method__, url, options)
      end

      def delete(url, options = {})
        perform_request(__method__, url, options)
      end

      private

      def initialize(logger)
        @logger = logger
      end

      def perform_request(method, url, options)
        request = Request.new(@logger, url, options.merge(method: method))
        request.run
      end

    end

  end
end


text:
{% extends "oauth_api/base.html" %}

{% load i18n %}

{% block content%}

    {% if error %}

{% trans "Could not authorize the client" %}

            Error:

            {{ error.error }}

    {% else %}

{% trans "An application would like to connect to your account" %}

                {% blocktrans with name=application.name %}
                The app {{ name }} would like have following permissions on your data:
                {% endblocktrans %}

                {% for scope in scopes_descriptions %}

{{ scope }}

                {% endfor %}

            <form id="authorization" method="post">
                {% csrf_token %}

                {% for hidden in form.hidden_fields %}
                {{ hidden }}
                {% endfor %}

                {{ form.errors }}
                {{ form.non_field_errors }}

                <input type="submit" class="btn btn-large" value="{% trans 'Cancel' %}">
                <input type="submit" class="btn btn-large btn-primary" name="allow" value="{% trans 'Authorize' %}">
            </form>

    {% endif %}

{% endblock content%}


text:
title: 7th District school spending in Hamilton County, Tennessee
date: 2016-05-25 00:00:00 -04:00
permalink: "/projects/the-cost-of-education/brief/district-7/"
layout: the-cost-of-education/brief
boe: Donna Horn
commission: Sabrena Turner-Smedley
fn: district-7
district: 7th District
description: Learn about school funding in Hamilton County, Tennessee.
project: The cost of education
main: article
---

      School
      Enrollment
      Per-student spending

      Apison Elementary
      628
      $6,551

      Bess T. Shepherd Elementary
      553
      $7,201

      East Brainerd Elementary
      663
      $7,101

      East Hamilton Middle-High
      1,707
      $6,712

      Westview Elementary
      706
      $6,463


text:
package com.microsoft.azure.storage;

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

/**
 * Represents a Cross-Origin Resource Sharing (CORS) rule.
 */
public class CorsRule {

    /**
     * The domain names allowed via CORS.
     */
    private List<String> allowedOrigins = new ArrayList<String>();

    /**
     * The response headers that should be exposed to client via CORS.
     */
    private List<String> exposedHeaders = new ArrayList<String>();

    /**
     * The headers allowed to be part of the CORS request.
     */
    private List<String> allowedHeaders = new ArrayList<String>();

    /**
     * The HTTP methods permitted to execute for the allowedOrigins.
     */
    private EnumSet<CorsHttpMethods> allowedMethods = EnumSet.noneOf(CorsHttpMethods.class);

    /**
     * The length of time in seconds that a preflight response should be cached by browser.
     */
    private int maxAgeInSeconds = 0;

    /**
     * Gets the allowed origins.
     *
     * @return A List object which contains the allowed origins.
     */
    public List<String> getAllowedOrigins() {
        return this.allowedOrigins;
    }

    /**
     * Sets the allowed origins.
     *
     * Limited to 64 origins OR "*" to allow all origins, no more than 256 characters each.
     *
     * @param allowedOrigins
     *            A List object which contains the allowed origins.
     */
    public void setAllowedOrigins(List<String> allowedOrigins) {
        this.allowedOrigins = allowedOrigins;
    }

    /**
     * Gets the exposed headers.
     *
     * @return A List object which contains the exposed headers.
     */
    public List<String> getExposedHeaders() {
        return this.exposedHeaders;
    }

    /**
     * Sets the exposed headers.
     *
     * Limited to 64 defined headers and two prefixed headers, no more than 256 characters each.
     *
     * @param exposedHeaders
     *            A List object which contains the exposed headers.
     */
    public void setExposedHeaders(List<String> exposedHeaders) {
        this.exposedHeaders = exposedHeaders;
    }

    /**
     * Gets the allowed headers.
     *
     * @return A List object which contains the allowed headers.
     */
    public List<String> getAllowedHeaders() {
        return this.allowedHeaders;
    }

    /**
     * Sets the allowed headers.
     *
     * Limited to 64 defined headers and two prefixed headers, no more than 256 characters each.
     *
     * @param allowedHeaders
     *            A List object which contains the allowed headers.
     */
    public void setAllowedHeaders(List<String> allowedHeaders) {
        this.allowedHeaders = allowedHeaders;
    }

    /**
     * Gets the allowed methods.
     *
     * @return A List object which contains the allowed methods.
     */
    public EnumSet<CorsHttpMethods> getAllowedMethods() {
        return this.allowedMethods;
    }

    /**
     * Sets the allowed methods.
     *
     * @param allowedMethods
     *            A List object which contains the allowed methods.
     */
    public void setAllowedMethods(EnumSet<CorsHttpMethods> allowedMethods) {
        this.allowedMethods = allowedMethods;
    }

    /**
     * Gets the maximum age in seconds.
     *
     * @return An int which represents the the maximum age in seconds.
     */
    public int getMaxAgeInSeconds() {
        return this.maxAgeInSeconds;
    }

    /**
     * Sets the maximum age in seconds.
     *
     * @param maxAgeInSeconds
     *            An int which represents the the maximum age in seconds.
     */
    public void setMaxAgeInSeconds(int maxAgeInSeconds) {
        this.maxAgeInSeconds = maxAgeInSeconds;
    }

}


text:
package com.guestful.jaxrs.security.cookie.auth;

import java.security.Principal;

/**
 * @author Mathieu Carbou (mathieu.carbou@gmail.com)
 */
public class CookieSubject {

    private Principal principal;
    private boolean authenticated = false;

    public CookieSubject(Principal principal) {
        this.principal = principal;
    }

    public boolean isAnonymous() {
        return principal == null;
    }

    public boolean isRemembered() {
        return principal != null && !authenticated;
    }

    public boolean isAuthenticated() {
        return principal != null && authenticated;
    }

    public Principal getPrincipal() {
        return principal;
    }

    public void logout() {
        this.principal = null;
        this.authenticated = false;
    }

    public void login(Principal principal) {
        if (principal == null) throw new NullPointerException();
        this.principal = principal;
        this.authenticated = true;
    }

}


text:
package com.blogspot.techzealous.usbplug.utils;

import java.util.ArrayList;

public class UpConstants extends Object {

	private UpConstants() {

	}

	/** boolean preference indicating if the eula was accepted */
	public static final String PREF_EULA = "eula";
	/** int preference holding the count of usb plug-ins/outs */
	public static final String PREF_COUNT = "count";
	/** int preference holding the count of usb plugs set in the setup (previouse use) */
	public static final String PREF_COUNT_BYSETUP = "countbysetup";
	public static final String PREF_FIRST_START = "first";
	public static final String PREF_LAST_CONNECT_TYPE = "contype";

	public static final int MAX_HISTORY_SIZE = 50;
	public static ArrayList<ConnectionInfoUP> history = new ArrayList<ConnectionInfoUP>(MAX_HISTORY_SIZE);

	public static final String UP_DB = "updb";
	public static final String TIME_TABLE = "connections";
	public static final String TIME_TABLE_COLUM_TIME = "time";
	public static final String TIME_TABLE_COLUM_STATUS = "status";
	public static final String TIME_TABLE_COLUM_TYPE = "type";
	public static final String TIME_TABLE_COLUM_CHARGE = "charge";
	/** string for creating the table "connections"*/
	public static final String UP_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + UpConstants.TIME_TABLE
			+ " (_id INTEGER PRIMARY KEY AUTOINCREMENT, " + UpConstants.TIME_TABLE_COLUM_TIME + " INTEGER NOT NULL, " + UpConstants.TIME_TABLE_COLUM_STATUS + " INTEGER NOT NULL, " + UpConstants.TIME_TABLE_COLUM_TYPE + " TEXT, " + UpConstants.TIME_TABLE_COLUM_CHARGE + " INTEGER);";

}


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

namespace DrawShip.Viewer.ComInterop
{
	internal static class WinError
	{
		public const int S_OK = 0x0000;
		public const int S_FALSE = 0x0001;
		public const int E_FAIL = -2147467259;
		public const int E_INVALIDARG = -2147024809;
		public const int E_OUTOFMEMORY = -2147024882;
		public const int STRSAFE_E_INSUFFICIENT_BUFFER = -2147024774;

		public const uint SEVERITY_SUCCESS = 0;
		public const uint SEVERITY_ERROR = 1;

		/// <summary>
		/// Create an HRESULT value from component pieces.
		/// </summary>
		/// <param name="sev">The severity to be used</param>
		/// <param name="fac">The facility to be used</param>
		/// <param name="code">The error number</param>
		/// <returns>A HRESULT constructed from the above 3 values</returns>
		public static int MAKE_HRESULT(uint sev, uint fac, uint code)
		{
			return (int)((sev << 31) | (fac << 16) | code);
		}
	}
}


text:
<?php

namespace Slick\Database\Sql\Ddl\Constraint;

/**
 * Abstract able constraint
 *
 * @package   Slick\Database\Sql\Ddl\Column
 * @author    Filipe Silva <silvam.filipe@gmail.com>
 */
class AbstractConstraint implements ConstraintInterface
{
    /**
     * @var string
     */
    protected $_name;

    /**
     * Creates a new constraint
     *
     * @param string $name
     * @param array $options
     */
    public function __construct($name, $options = [])
    {
        $this->_name = $name;
        foreach ($options as $key => $value) {
            $prop = "_{$key}";
            if (property_exists($this, $prop)) {
                $this->$prop = $value;
            }
        }
    }

    /**
     * Returns constraint name
     *
     * @return string
     */
    public function getName()
    {
        return $this->_name;
    }
}


text:
package name.prokop.bart.fps.datamodel;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import name.prokop.bart.fps.util.BPMath;
import name.prokop.bart.fps.util.StringGenerator;

/**
 *
 * @author Bart
 */
public class Invoice {

    /**
     * Generuje testowy paragon, z obrotem 4 gr. i VAT wynoszącym 0,00 zł
     *
     * @return Przykladowy paragon
     */
    public static Invoice getTestInvoice() {
        Invoice slip = new Invoice();
        slip.setReference("R-k " + StringGenerator.generateRandomNumericId(6));
        slip.setCashbox("BP01");
        slip.setCashierName("Bartek Prokop");
        slip.addLine("Towar.22", 1, 0.01, VATRate.VAT22);
//        slip.addLine("Towar.07RK", 1, 0.02, VATRate.VAT07, DiscountType.AmountDiscount, 0.01);
//        slip.addLine("Towar.07RP", 1, 0.02, VATRate.VAT07, DiscountType.RateDiscount, 0.5);
        slip.addLine("Towar.07", 1, 0.01, VATRate.VAT07);
//        slip.addLine("Test_03", 1, 0.01, VATRate.VAT03);
        slip.addLine("Towar.00", 1, 0.01, VATRate.VAT00);
        slip.addLine("Towar.ZW", 1, 0.01, VATRate.VATzw);
        return slip;
    }

    /**
     * Generuje przykładowy paragon, do celów czysto testowych
     *
     * @return Przykładowy paragon
     */
    public static Invoice getSampleSlip() {
        Invoice slip = new Invoice();

        // numer zewnetrzny paragonu z waszej aplikacji
        slip.setReference("R-k " + StringGenerator.generateRandomNumericId(6));

        // poszczególne linijki paragonu
        slip.addLine("Deska drewniania", 0.999, 22.13, VATRate.VAT22);
        //slip.addLine("Lejek metalowy", 1.0, 18.01, VATRate.VAT07, DiscountType.AmountDiscount, 18.0);
        slip.addLine("Lejek metalowy", 1.0, 18.01, VATRate.VAT07, DiscountType.RateDiscount, 0.5);
        slip.addLine("Pampers", 1.0, 39.99, VATRate.VAT00);
        //linijka wywo┼éa wyj─ůtek - cena bruto == zero
        //slip.addLine("Drut 15 mm", 0.123456, 0.01, SlipLine.VATRate.VATzw);
        slip.addLine("LiteryĄĆĘÓąćęó", 123, 0.12, VATRate.VAT22);
        slip.addLine("Cement", 9.99, 99.99, VATRate.VAT22);
        slip.addLine("Pustak", 9.99, 0.01, VATRate.VAT07);
        slip.addLine("Beton", 48.0011, 1005.01, VATRate.VAT07);
        //slip.addLine("Mleko szkolne", 5, 3, SlipLine.VATRate.VAT03);
        slip.addLine("Paliwo", 34.87, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.871, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.872, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.873, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.874, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.875, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.876, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.877, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.878, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.879, 4.37, VATRate.VAT07);
        slip.addLine("Paliwo", 34.880, 4.37, VATRate.VAT07);

        slip.setCashierName("Jacek Bielarski");
        slip.setCashbox("BP01");
        return slip;
    }

    /**
     * Dodaje pozycje do paragonu
     *
     * @param name Nazwa towaru
     * @param amount Ilość towaru
     * @param price Cena brutto towaru
     * @param taxRate Stawka VAT na towar
     */
    public void addLine(String name, double amount, double price, VATRate taxRate) {
        addLine(new SaleLine(name, amount, price, taxRate));
    }

    public void addLine(String name, double amount, double price, VATRate taxRate, DiscountType discountType, double discount) {
        addLine(new SaleLine(name, amount, price, taxRate, discountType, discount));
    }

    public void addLine(SaleLine slipLine) {
        slipLines.add(slipLine);
    }

    /**
     * Getter for property noOfLines.
     *
     * @return Value of property noOfLines.
     */
    public int getNoOfLines() {
        return slipLines.size();
    }

    /**
     * Indexed getter for property payment.
     *
     * @param index Index of the property.
     * @return Value of the property at index.
     */
    public SaleLine getLine(int index) {
        return slipLines.get(index);
    }

    /**
     * Służy pozyskaniu wartości brutto całego paragonu
     *
     * @return Wartość brutto całego paragonu
     */
    public double getTotal() {
        double sum = 0.0;
        for (int i = 0; i < slipLines.size(); i++) {
            sum += slipLines.get(i).getTotal();
        }
        return BPMath.round(sum + 0.000001, 2);
    }

    /**
     * Enum dla okreslenia stanu danego paragonu
     */
    public enum PrintingState {

        /**
         * Nowo utworzony paragom
         */
        Created,
        /**
         * LOCK - podczas drukowania
         */
        DuringPrinting,
        /**
         * Wydrukowany - wszystko w porzadku jest
         */
        Printed,
        /**
         * Paragon z bledem
         */
        Errored;

        @Override
        public String toString() {
            switch (this) {
                case Created:
                    return "Nowy";
                case DuringPrinting:
                    return "Drukuje sie";
                case Errored:
                    return "Bledny";
                case Printed:
                    return "Wydrukowany";
                default:
                    throw new IllegalStateException();
            }
        }
    }

    @Override
    public String toString() {
        String retVal = "Slip: Reference: " + reference + " Kasa: " + getCashbox() + "\n";
        for (SaleLine sl : slipLines) {
            retVal += sl + "\n";
        }
        retVal += "Suma paragonu: " + getTotal() + " Kasjer: " + getCashierName();
        return retVal;
    }
    /**
     * referencja dla paragonu. musi byc unikalna
     */
    private String reference;
    /**
     * Data utworzenia paragonu
     */
    private Date created = new Date();
    /**
     * Data wydrukowania paragonu (jego fiskalizacji)
     */
    private Date printed = null;
    /**
     * Nazwa kasy - pole na paragonie określające nazwę kasy fiskalnej. Używane
     * również do rozróżnienia gdzie należy kolejkować wydruki.
     */
    private String cashbox;
    /**
     * Imie i Nazwisko kasjera
     */
    private String cashierName;
    /**
     * Linijki paragonu
     */
    private List<SaleLine> slipLines = new ArrayList<>();
    /**
     * Stan paragonu
     */
    private PrintingState printingState = PrintingState.Created;
    /**
     * Opis bledu w paragonie
     */
    private String errorNote = PrintingState.Created.toString();

    public Date getCreated() {
        return created;
    }

    public void setCreated(Date created) {
        this.created = created;
    }

    public Date getPrinted() {
        return printed;
    }

    public void setPrinted(Date printed) {
        this.printed = printed;
    }

    public List<SaleLine> getSlipLines() {
        return slipLines;
    }

    public void setSlipLines(List<SaleLine> slipLines) {
        this.slipLines = slipLines;
    }

    public String getCashbox() {
        return cashbox;
    }

    public void setCashbox(String cashbox) {
        if (cashbox != null) {
            cashbox = cashbox.trim();
        }
        this.cashbox = cashbox;
    }

    public String getCashierName() {
        return cashierName;
    }

    public void setCashierName(String cashierName) {
        if (cashierName != null) {
            cashierName = cashierName.trim();
        }
        this.cashierName = cashierName;
    }

    public PrintingState getPrintingState() {
        return printingState;
    }

    public void setPrintingState(PrintingState printingState) {
        this.printingState = printingState;
    }

    public String getReference() {
        return reference;
    }

    public void setReference(String reference) {
        if (reference != null) {
            reference = reference.trim();
        }
        this.reference = reference;
    }

    public String getErrorNote() {
        return errorNote;
    }

    public void setErrorNote(String errorNote) {
        if (errorNote != null) {
            errorNote = errorNote.trim();
        }
        this.errorNote = errorNote;
    }

    public String getNip() {
        return nip;
    }

    public void setNip(String nip) {
        this.nip = nip;
    }

    public String getPaymentDue() {
        return paymentDue;
    }

    public void setPaymentDue(String paymentDue) {
        this.paymentDue = paymentDue;
    }

    public String getPaymentType() {
        return paymentType;
    }

    public void setPaymentType(String paymentType) {
        this.paymentType = paymentType;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }
    /**
     * "813-188-60-14"
     */
    private String nip;
    /**
     * "nigdy"
     */
    private String paymentDue;
    /**
     * "przelew"
     */
    private String paymentType;
    /**
     * "Firma\nul. Przemysłowa 9A\n35-111 Rzeszów"
     */
    private String header;
}


text:
package bot

import (
	"log"

	"cirello.io/gochatbot/messages"
	"cirello.io/gochatbot/providers"
)

// MessageProvider is the self-referencing option that plugs Message Providers
// into the robot.
func MessageProvider(provider providers.Provider) Option {
	return func(s *Self) {
		log.Printf("bot: changing message provider %T\n", provider)
		s.providerIn = provider.IncomingChannel()
		s.providerOut = provider.OutgoingChannel()
	}
}

// RuleParser explains the interface needed for a certain type to be considered
// a valid message parsing rule.
type RuleParser interface {
	Name() string
	Boot(*Self)
	HelpMessage(Self, string) string
	ParseMessage(Self, messages.Message) []messages.Message
}

// RegisterRuleset is the self-referencing option that plugs Rules into the robot.
func RegisterRuleset(rule RuleParser) Option {
	return func(s *Self) {
		log.Printf("bot: registering ruleset %T", rule)
		rule.Boot(s)
		s.rules = append(s.rules, rule)
	}
}


text:
namespace serial
{
  namespace pts
  {
    inline m2::PointU D2U(m2::PointD const & p, uint32_t coordBits)
    {
      return PointD2PointU(p, coordBits);
    }

    inline m2::PointD U2D(m2::PointU const & p, uint32_t coordBits)
    {
      m2::PointD const pt = PointU2PointD(p, coordBits);
      ASSERT(MercatorBounds::minX <= pt.x && pt.y <= MercatorBounds::maxX,
             (p, pt, coordBits));
      ASSERT(MercatorBounds::minY <= pt.x && pt.y <= MercatorBounds::maxY,
             (p, pt, coordBits));
      return pt;
    }

    inline m2::PointU GetMaxPoint(CodingParams const & params)
    {
      return D2U(m2::PointD(MercatorBounds::maxX, MercatorBounds::maxY), params.GetCoordBits());
    }

    inline m2::PointU GetBasePoint(CodingParams const & params)
    {
      return params.GetBasePoint();
    }

    typedef buffer_vector<m2::PointU, 32> upoints_t;
  }

  void Encode(EncodeFunT fn, vector<m2::PointD> const & points,
              CodingParams const & params, DeltasT & deltas)
  {
    size_t const count = points.size();

    pts::upoints_t upoints;
    upoints.reserve(count);

    transform(points.begin(), points.end(), back_inserter(upoints),
              bind(&pts::D2U, _1, params.GetCoordBits()));

    ASSERT ( deltas.empty(), () );
    deltas.resize(count);

    geo_coding::OutDeltasT adapt(deltas);
    (*fn)(make_read_adapter(upoints), pts::GetBasePoint(params), pts::GetMaxPoint(params), adapt);
  }

  template <class TDecodeFun, class TOutPoints>
  void DecodeImpl(TDecodeFun fn, DeltasT const & deltas, CodingParams const & params,
                  TOutPoints & points, size_t reserveF)
  {
    size_t const count = deltas.size() * reserveF;

    pts::upoints_t upoints;
    upoints.resize(count);

    geo_coding::OutPointsT adapt(upoints);
    (*fn)(make_read_adapter(deltas), pts::GetBasePoint(params), pts::GetMaxPoint(params), adapt);

    if (points.size() < 2)
    {
      // Do not call reserve when loading triangles - they are accumulated to one vector.
      points.reserve(count);
    }

    transform(upoints.begin(), upoints.begin() + adapt.size(), back_inserter(points),
              bind(&pts::U2D, _1, params.GetCoordBits()));
  }

  void Decode(DecodeFunT fn, DeltasT const & deltas, CodingParams const & params,
              OutPointsT & points, size_t reserveF)
  {
    DecodeImpl(fn, deltas, params, points, reserveF);
  }

  void Decode(DecodeFunT fn, DeltasT const & deltas, CodingParams const & params,
              vector<m2::PointD> & points, size_t reserveF)
  {
    DecodeImpl(fn, deltas, params, points, reserveF);
  }

  void const * LoadInner(DecodeFunT fn, void const * pBeg, size_t count,
                         CodingParams const & params, OutPointsT & points)
  {
    DeltasT deltas;
    deltas.reserve(count);
    void const * ret = ReadVarUint64Array(static_cast<char const *>(pBeg), count,
                                          MakeBackInsertFunctor(deltas));

    Decode(fn, deltas, params, points);
    return ret;
  }

  TrianglesChainSaver::TrianglesChainSaver(CodingParams const & params)
  {
    m_base = pts::GetBasePoint(params);
    m_max = pts::GetMaxPoint(params);
  }

  namespace
  {
    struct edge_less_p0
    {
      typedef tesselator::Edge edge_t;

      bool operator() (edge_t const & e1, edge_t const & e2) const
      {
        return (e1.m_p[0] == e2.m_p[0]) ? (e1.m_side < e2.m_side) : (e1.m_p[0] < e2.m_p[0]);
      }
      bool operator() (edge_t const & e1, int e2) const
      {
        return e1.m_p[0] < e2;
      }
      bool operator() (int e1, edge_t const & e2) const
      {
        return e1 < e2.m_p[0];
      }
    };
  }

  void TrianglesChainSaver::operator() (TPoint arr[3], vector<TEdge> edges)
  {
    m_buffers.push_back(TBuffer());
    MemWriter<TBuffer> writer(m_buffers.back());

    WriteVarUint(writer, EncodeDelta(arr[0], m_base));
    WriteVarUint(writer, EncodeDelta(arr[1], arr[0]));

    TEdge curr = edges.front();
    curr.m_delta = EncodeDelta(arr[2], arr[1]);

    sort(edges.begin(), edges.end(), edge_less_p0());

    stack<TEdge> st;
    while (true)
    {
      CHECK_EQUAL ( curr.m_delta >> 62, 0, () );
      uint64_t delta = curr.m_delta << 2;

      // find next edges
      int const nextNode = curr.m_p[1];
      auto i = lower_bound(edges.begin(), edges.end(), nextNode, edge_less_p0());
      bool const found = (i != edges.end() && i->m_p[0] == nextNode);
      if (found)
      {
        // fill 2 tree-struct bites
        ASSERT_NOT_EQUAL(i->m_side, -1, ());

        uint64_t const one = 1;

        // first child
        delta |= (one << i->m_side);

        vector<TEdge>::iterator j = i+1;
        if (j != edges.end() && j->m_p[0] == nextNode)
        {
          // second child
          ASSERT_EQUAL(i->m_side, 0, ());
          ASSERT_EQUAL(j->m_side, 1, ());

          delta |= (one << j->m_side);

          // push to stack for further processing
          st.push(*j);
        }

        curr = *i;
      }

      // write delta for current element
      WriteVarUint(writer, delta);

      if (!found)
      {
        // end of chain - pop current from stack or exit
        if (st.empty())
          break;
        else
        {
          curr = st.top();
          st.pop();
        }
      }
    }
  }

  void DecodeTriangles(geo_coding::InDeltasT const & deltas,
                       m2::PointU const & basePoint,
                       m2::PointU const & maxPoint,
                       geo_coding::OutPointsT & points)
  {
    size_t const count = deltas.size();
    ASSERT_GREATER ( count, 2, () );

    points.push_back(DecodeDelta(deltas[0], basePoint));
    points.push_back(DecodeDelta(deltas[1], points.back()));
    points.push_back(DecodeDelta(deltas[2] >> 2, points.back()));

    stack<size_t> st;

    size_t ind = 2;
    uint8_t treeBits = deltas[2] & 3;

    for (size_t i = 3; i < count;)
    {
      // points 0, 1 - is a common edge
      // point 2 - is an opposite point for new triangle to calculate prediction
      size_t trg[3];

      if (treeBits & 1)
      {
        // common edge is 1->2
        trg[0] = ind;
        trg[1] = ind-1;
        trg[2] = ind-2;

        // push to stack for further processing
        if (treeBits & 2)
          st.push(ind);
      }
      else if (treeBits & 2)
      {
        // common edge is 2->0
        trg[0] = ind-2;
        trg[1] = ind;
        trg[2] = ind-1;
      }
      else
      {
        // end of chain - pop current from stack
        ASSERT ( !st.empty(), () );
        ind = st.top();
        st.pop();
        treeBits = 2;
        continue;
      }

      // push points
      points.push_back(points[trg[0]]);
      points.push_back(points[trg[1]]);
      points.push_back(DecodeDelta(deltas[i] >> 2,
                                   PredictPointInTriangle(maxPoint,
                                                          points[trg[0]],
                                                          points[trg[1]],
                                                          points[trg[2]])));

      // next step
      treeBits = deltas[i] & 3;
      ind = points.size() - 1;
      ++i;
    }

    ASSERT ( treeBits == 0 && st.empty(), () );
  }
}


text:
package com.github.spikevlg.habraparserscala

case class HabraItem(
                      id : Int
                      , title : String
                      , countStars : Int
                      , author : String
                      , pageView : Int
                      , isTranslate : Boolean
                      , score : Option[Double]
                      , hubs : List[String]
                      , tags : List[String]
)


text:
<?php

namespace Matthias\SymfonyConfigTest\PhpUnit;

use Symfony\Component\Config\Definition\ConfigurationInterface;

class ProcessedConfigurationEqualsConstraint extends AbstractConfigurationConstraint
{
    private $configurationValues;

    public function __construct(ConfigurationInterface $configuration, array $configurationValues)
    {
        $this->validateConfigurationValuesArray($configurationValues);
        $this->configurationValues = $configurationValues;

        parent::__construct($configuration);
    }

    public function evaluate($other, $description = '', $returnResult = false)
    {
        $processedConfiguration = $this->processConfiguration($this->configurationValues);

        $constraint = new \PHPUnit_Framework_Constraint_IsEqual($other);

        return $constraint->evaluate($processedConfiguration, '', $returnResult);
    }

    public function toString()
    {
        // won't be used, this constraint only wraps \PHPUnit_Framework_Constraint_IsEqual
    }
}


text:
#include "tests.h"
#include "tests_timestack.h"
#include "../src/timestack.h"

#include <string.h>

void
test_timestack_create(UNUSED void **state)
{
    timestack_t *timestack = timestack_new(4);

    assert_int_equal(0, timestack->count);

    timestack_destroy(timestack);
}

void
test_timestack_add(UNUSED void **state)
{
    uint32_t count = 100;

    timestack_t *timestack = timestack_new(4);

    assert_int_equal(0, timestack->count);

    for (uint32_t i = 0; i < count; i++)
    {
        timestack_add(timestack, i);
    }

    assert_int_equal(4, timestack->count);

    assert_int_equal(96, timestack_oldest(timestack));
    assert_int_equal(99, timestack_newest(timestack));

    timestack_destroy(timestack);
}

/* vim: set et sw=4 sts=4 tw=80: */


text:
import scrapy
import re
from Result import Result
import Globals

class Post:

    def __init__(self, html : str, rootURL : str):
        self.HTML = html# celoten HTML v postu
        self.isParsed = False # zastavica, ki pove, ce je post prebran
        self.URL = rootURL # URL do posta
        self.results = [] # seznam rezultatov
        self.HTMLselector : scrapy.Selector
        self.nickname : str

        self.parse()

    def __setURL(self):
        postID = self.HTMLselector.xpath('//div/a/@name').extract_first() # dobi ID posta, ki je uporabljen za URL
        urlParts = self.URL.split('/')
        for i in range(len(urlParts) - 1, 0, -1):
            if urlParts[i].startswith("t"):
                break
            else:
                del urlParts[i]
        self.URL = '/'.join(urlParts) + "/" + postID + "#" + postID

    def __getNickname(self):
        self.nickname = self.HTMLselector.xpath('//h4/a/text()').extract_first()  # dobi ID posta, ki je uporabljen za URL

    def __getResults(self):
        content = self.HTMLselector.xpath('//div[contains(@class, "content")]/descendant-or-self::*').extract_first() # dobi text vsebino posta
        content = re.sub(r'
', "\n", content) # zamenjaj HTML line break za string line break
        content = re.sub(r'<.*?>', "", content) # odstrani HTML značke

        if (Globals.IgnoreFlag in content):
            return []

        lines = content.split('\n')
        lineNumber = 0
        for line in lines:
            data = line.split(Globals.Delim) # split result

            if len(data) > 1:
                try:
                    try:
                        keyScore = float(data[Globals.KeyScorePosition].replace(',', '.')) # parsaj (glavni) rezultat
                    except ValueError:
                        # poskusimo kompenzirati potencialno napacen link msg na koncu ?
                        if (len(data) >= 2 and (Globals.KeyScorePosition == -1 or Globals.KeyScorePosition == len(data) - 2)):
                            keyScore = float(data[Globals.KeyScorePosition - 1].replace(',', '.'))  # parsaj (glavni) rezultat (kompenziraj napacen link desno od njega)
                            del data[-1] # odstanimo napacen link
                        else:
                            raise ValueError
                    # make bold
                    data[Globals.KeyScorePosition] = "" + data[Globals.KeyScorePosition].strip() + ""

                    label = self.__findLabel(lineNumber, lines)

                    # odstrani hardcodan nickname iz rezultata
                    if Globals.ExpectedNicknamePosition < len(data):
                        del data[Globals.ExpectedNicknamePosition]
                    for i in range(len(data)):
                        if data[i].strip() == self.nickname:
                            del data[i]
                            break

                    result = Result(Globals.Delim.join(data), keyScore, self.nickname, self.URL, label)
                    self.results.append(result)
                except ValueError:
                    pass
                except IndexError:
                    print("INDEX ERROR at post: " + self.URL + " ... napačen input score/nickname index mogoče?")
            lineNumber += 1

        return self.results

    def __findLabel(self, lineNumber : int, lines : [str]):
        lineNumber -= 1
        while(lineNumber >= 0):
            maxIndex = 0
            labelIndex = -1
            for j in range(len(Globals.Labels)):
                foundIndex = lines[lineNumber].lower().rfind(Globals.Labels[j].lower())
                if foundIndex >= maxIndex:
                    maxIndex = foundIndex
                    labelIndex = j
            if labelIndex != -1:
                return labelIndex # vrni najdeno indeks najdene labele
            lineNumber -= 1

        return -1 # nismo našli labele

    # preparsaj nastavljen HTML
    def parse(self):
        self.HTMLselector = scrapy.Selector(text=self.HTML) # html string --> selector
        self.__getNickname()
        self.__setURL()
        return self.__getResults()


text:
import express                    = require('express');
import IImport                    = require("./IImport");
import ITransform                 = require("./ITransform");
import IStore                     = require("./IStore");
import IImporterRepositoryService = require("./IImporterRepositoryService");
import ConfigurationService       = require('../configuration/ConfigurationService');
import request                    = require("request");
import JSONStream                 = require('JSONStream');

var es = require('event-stream');

/* Multiple storage engine supported, e.g. file system, mongo  */
class ImporterRepositoryService implements IImporterRepositoryService {
    private baseUrl: string;
    private store: IStore;

    private transformers: ITransform[] = [];

    constructor(server: express.Express, config: ConfigurationService, store: IStore) {
        this.baseUrl = config['importAddress'] || '/importers';
        this.store = store;

        server.get(this.baseUrl, (req, res) => {
            var importers = this.getAll();
            res.send(importers);
        });

        server.get(this.baseUrl + "/transformers", (req, res) => {
            var transformers = this.getAllTransformers();
            res.send(transformers);
        });

        /**
         * Create
         */
        server.post(this.baseUrl, (req, res) => {
            var importer = req.body;
            console.log(importer);
            res.send(this.create(importer));
        });

        /**
         * Read
         */
        server.get(this.baseUrl + '/:id', (req, res) => {
            var id = req.params.id;
            res.send(this.get(id));
        });

        /**
         * Run
         */
        server.get(this.baseUrl + '/:id/run', (req, res) => {
            var id = req.params.id;

            var importer = this.get(id);
            importer.lastRun = new Date();

            request({ url: importer.sourceUrl })
                .pipe(JSONStream.parse('rows.*'))
                .pipe(es.mapSync(function(data) {
                    console.error(data)
                    return data
                }));

            res.send("");
        });

        /**
         * Update
         */
        server.put(this.baseUrl + '/:id', (req, res) => {
            var id = req.params.id;
            var importer = req.body;
            res.send(this.update(importer));
        });

        /**
         * Delete
         */
        server.delete(this.baseUrl + '/:id', (req, res) => {
            var id = req.params.id;
            res.send(this.delete(id));
        });
    }

    init(transformers: ITransform[]) {
        this.transformers = transformers;
    }

    getAllTransformers() {
        return this.transformers;
    }

    getAll() {
        return this.store.getAll();
    }

    get(id: string) {
        return this.store.get(id);
    }

    create(importer: IImport): IImport {
        return this.store.create(importer);
    }

    delete(id: string) {
        this.store.delete(id);
    }

    update(importer: IImport) {
        this.store.update(importer);
    }

}
export=ImporterRepositoryService;


text:
package metamodel.access;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;

import metamodel.access.testobject.POJO;
import metamodel.access.testobject.POJO_;
import metamodel.access.testobject.SubClassWithSameFieldName;
import metamodel.access.testobject.SubClassWithSameFieldName_;

import org.junit.Test;

/**
 * Tests ObjectAccessor.
 *
 * @author Michael Kroll
 */
public class ObjectAccessorTest {

	@Test
	public void testPOJOSetterGetter() throws Exception {
		final POJO pojo = new POJO();
		pojo.setMyint(42);
		pojo.setMyInteger(23);

		assertEquals(new Integer(42), Accessor.on(pojo).field(POJO_.myint).get());
		assertEquals(new Integer(23), Accessor.on(pojo).field(POJO_.myInteger).get());

		Accessor.on(pojo).field(POJO_.myint).set(13);
		Accessor.on(pojo).field(POJO_.myInteger).set(7);

		assertEquals(13, pojo.getMyint());
		assertEquals(Integer.valueOf(7), pojo.getMyInteger());
	}

	@Test
	public void testPOJOWildcardGetterSetter() throws Exception {
		final POJO pojo = new POJO();
		pojo.setWildcardList(Arrays.asList(new String("Charly!"), new Integer(42)));

		assertEquals(Arrays.asList(new String("Charly!"), new Integer(42)),
		        Accessor.on(pojo).field(POJO_.wildcardList).get());

		Accessor.on(pojo).field(POJO_.wildcardList).set(Arrays.asList(new String("Nope!"), new Integer(7)));

		assertEquals(Arrays.asList(new String("Nope!"), new Integer(7)), pojo.getWildcardList());
	}

	@Test
	public void testSubClassBaseClassGetterSetter() throws Exception {
		final SubClassWithSameFieldName pojo = new SubClassWithSameFieldName();

		pojo.setMyInteger(42);
		assertEquals(new Integer(42), Accessor.on(pojo).field(SubClassWithSameFieldName_.myInteger).get());

		Accessor.on(pojo).field(POJO_.myInteger).set(7);
		assertEquals(Integer.valueOf(7), pojo.getMyInteger());

		Accessor.on(pojo).field(SubClassWithSameFieldName_.myInteger).set(13);
		assertEquals(Integer.valueOf(13), pojo.getMyInteger());

		pojo.setMyInteger(42);
		assertEquals(new Integer(42), Accessor.on(pojo).field(SubClassWithSameFieldName_.myInteger).get());
	}

	@Test
	public void testSubClassHasSameFieldNameAsBaseClassGetterSetter() throws Exception {
		final SubClassWithSameFieldName pojo = new SubClassWithSameFieldName();

		pojo.setMyint(42);
		pojo.sub_setMyint(23);
		assertEquals(new Integer(42), Accessor.on(pojo).field(POJO_.myint).get());
		assertEquals(new Integer(23), Accessor.on(pojo).field(SubClassWithSameFieldName_.myint).get());

		Accessor.on(pojo).field(POJO_.myint).set(7);
		Accessor.on(pojo).field(SubClassWithSameFieldName_.myint).set(13);
		assertEquals(7, pojo.getMyint());
		assertEquals(13, pojo.sub_getMyint());
	}

	@Test
	public void testFieldAccessInClassHierarchy() throws Exception {
		final SubClassWithSameFieldName sub = new SubClassWithSameFieldName();
		final POJO pojo = new POJO();

		Accessor.on(pojo).field(POJO_.myInteger).set(5);
		// implicit downcast should not be allowed:
		// AccessorUtil.on(pojo).field(SubClassWithSameFieldName_.subString).set("hello world");

		Accessor.on(sub).field(POJO_.myInteger).set(5);
		Accessor.on(sub).field(SubClassWithSameFieldName_.subString).set("hello world");
	}

	@Test
	public void testMethodAccessInClassHierarchy() throws Exception {
		final SubClassWithSameFieldName sub = new SubClassWithSameFieldName();
		final POJO pojo = new POJO();

		Accessor.on(pojo).method(POJO_.setMyint).invoke(5);
		// implicit downcast should not be allowed:
		// AccessorUtil.on(pojo).method(SubClassWithSameFieldName_.sub_setMyint).invoke(5);

		Accessor.on(sub).method(POJO_.setMyint).invoke(5);
		Accessor.on(sub).method(SubClassWithSameFieldName_.sub_setMyint).invoke(5);
	}

	@Test
	public void testMethodWithObjectArray() throws Exception {
		final POJO pojo = new POJO();
		Accessor.on(pojo).method(POJO_.methodWithObjectArray).invoke(new Long[] { 5L, 7L });
	}

	@Test
	public void testMethodWithPrimitiveArray() throws Exception {
		final POJO pojo = new POJO();
		Accessor.on(pojo).method(POJO_.methodWithPrimitiveArray).invoke(new int[] { 5, 7 });
	}
}


text:
title: Locking/Thread Synchronization Performance Question
categories: .Net
tags: Performance
date: 2007-12-19 12:48:00 +10:00
---

Here is my scenario:

I have a static method which checks some static generic dictionaries to determine whether keys exist. If keys don't exist, they will get added along with a value.

Rough "metrics" will be:

* the static method will get called a lot
* items will rarely get added to the dictionary
* items are never removed from the dictionary
* the dictionary will only contain a few items
* as many times as the method is called, the dictionary will be referenced using the ContainsKey property (and the indexer property where ContainsKey == true)

In order to ensure thread safety of adding a new item to the dictionary, a lock is required. Two options I see are as follows:

<!--more-->

**#1 - This is what people would normally do**

```csharp
lock (MyDictionary)
{
    // Check if a value needs to be stored
    if (MyDictionary.ContainsKey(myKey) == false)
    {
        // Store the value
        MyDictionary.Add(myKey, myValue);
    }
}
```

**#2 - I think this would perform better**

```csharp
// Check if a value needs to be stored
if (MyDictionary.ContainsKey(myKey) == false)
{
    lock (MyDictionary)
    {
        // Check if a value needs to be stored
        if (MyDictionary.ContainsKey(myKey) == false)
        {
            // Store the value
            MyDictionary.Add(myKey, myValue);
        }
    }
}
```

The reason I think the second solution will perform better is that the first if statement gets executed as part of the normal code flow of the method. This means lots of executions on multiple threads. It will first check that an item needs to be added before causing the lock. This results in the lock only happening in rare cases. Inside the lock, it ensures that another thread isn't about to do the same thing by making a defensive call to ContainsKey.

In contrast, the first solution will lock out all other threads from checking to see if an item needs to be added causing a major bottleneck.

Keeping in mind the metrics outlined above, is this a good solution? It seems like the best trade-off between thread safety and avoiding bottlenecks with the sacrifice being another call to ContainsKey.

Thoughts?


text:
@class Country;

@protocol CitiesStorage <NSObject>

- (void)storeCities:(NSArray *)cities
        fromCountry:(Country *)country;

@end


text:
import { connect } from "react-redux";
import PreviousNextButtons from "../components/previous_next_buttons";
import { showNewObservation } from "../ducks/observation";

function mapStateToProps( state ) {
  return {
    observation: state.observation,
    otherObservations: state.otherObservations,
    config: state.config
  };
}

function mapDispatchToProps( dispatch ) {
  return {
    showNewObservation: ( observation, options ) => {
      dispatch( showNewObservation( observation, options ) );
    }
  };
}

const PreviousNextButtonsContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)( PreviousNextButtons );

export default PreviousNextButtonsContainer;


text:
package whitebox.endpoint.client;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

import jakarta.xml.ws.Endpoint;
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import java.net.URL;
import java.io.*;
import jakarta.xml.ws.Provider;
import javax.xml.transform.Source;
import jakarta.xml.ws.WebServiceProvider;
import java.io.StringReader;
import jakarta.annotation.Resource;
import jakarta.xml.ws.WebServiceContext;
import jakarta.xml.ws.handler.MessageContext;
import jakarta.xml.ws.http.HTTPBinding;
import java.util.Map;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Iterator;
import jakarta.xml.ws.WebServiceException;

import com.sun.xml.ws.developer.JAXWSProperties;
import com.sun.net.httpserver.HttpExchange;

/**
 * @author Jitendra Kotamraju
 */
public class MessageContextTester extends TestCase {

    @WebServiceProvider
    static class MyProvider implements Provider<Source> {
        @Resource
        WebServiceContext ctxt;

        public Source invoke(Source source) {
            MessageContext msgCtxt = ctxt.getMessageContext();

            // toString()
            System.out.println("MessageContext="+msgCtxt);

            // Test Map.get()
            String method = (String)msgCtxt.get(MessageContext.HTTP_REQUEST_METHOD);
            if (method == null || !method.equals("GET")) {
                throw new WebServiceException("Expected method=GET but got="+method);
            }

            // Test iterator
            Iterator<Map.Entry<String, Object>> i = msgCtxt.entrySet().iterator();
            while(i.hasNext()) {
                Map.Entry<String, Object> e = i.next();
            }

            // Test keySet() iterator
            Iterator<String> i1 = msgCtxt.keySet().iterator();
            while(i1.hasNext()) {
                i1.next();
            }

            // Test Map.size()
            int no = msgCtxt.size();

            // Test Map.put()
            msgCtxt.put("key", "value");

            // Test Map.get() for the new addition
            String value = (String)msgCtxt.get("key");
            if (value == null || !value.equals("value")) {
                throw new WebServiceException("Expected=value but got="+value);
            }

            // Test Map.size() for the new addition
            int num = msgCtxt.size();
            if (num != no+1) {
                throw new WebServiceException("Expected no="+(no+1)+" but got="+num);
            }

            // Test Map.remove() for the new addition
            value = (String)msgCtxt.remove("key");
            if (value == null || !value.equals("value")) {
                throw new WebServiceException("Expected=value but got="+value);
            }

            // Test Map.size() for the removal
            num = msgCtxt.size();
            if (num != no) {
                throw new WebServiceException("Expected="+no+" but got="+num);
            }

            // Test iterator.remove()
            msgCtxt.put("key", "value");
            i = msgCtxt.entrySet().iterator();
            while(i.hasNext()) {
                Map.Entry<String, Object> e = i.next();
                if (e.getKey().equals("key")) {
                    i.remove();
                }
            }
            num = msgCtxt.size();
            if (num != no) {
                throw new WebServiceException("Expected="+no+" but got="+num);
            }
            value = (String)msgCtxt.get("key");
            if (value != null) {
                throw new WebServiceException("Expected=null"+" but got="+value);
            }

            // Test Map.putAll()
            Map<String, Object> two = new HashMap<String, Object>();
            two.put("key1", "value1");
            two.put("key2", "value2");
            msgCtxt.putAll(two);
            num = msgCtxt.size();
            if (num != no+2) {
                throw new WebServiceException("Expected="+(no+2)+" but got="+num);
            }
            value = (String)msgCtxt.get("key1");
            if (value == null || !value.equals("value1")) {
                throw new WebServiceException("Expected=value1"+" but got="+value);
            }
            value = (String)msgCtxt.get("key2");
            if (value == null || !value.equals("value2")) {
                throw new WebServiceException("Expected=value2"+" but got="+value);
            }

            String replyElement = new String("
hello world
");
            StreamSource reply = new StreamSource(new StringReader (replyElement));
            return reply;
        }
    }

    public void testMessageContext() throws Exception {
        int port = Util.getFreePort();
        String address = "http://127.0.0.1:"+port+"/";
        Endpoint e = Endpoint.create(HTTPBinding.HTTP_BINDING, new MyProvider());
        e.publish(address);

        URL url = new URL(address);
        InputStream in = url.openStream();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
        String str;
        while ((str=rdr.readLine()) != null);

        e.stop();
    }

    @WebServiceProvider
    static class MessageContextProvider implements Provider<Source> {
        @Resource
        WebServiceContext ctxt;

        public Source invoke(Source source) {
            MessageContext msgCtxt = ctxt.getMessageContext();

            String qs = (String)msgCtxt.get(MessageContext.QUERY_STRING);
            if (qs == null || !qs.equals("a=b")) {
                throw new WebServiceException("Unexpected QUERY_STRING. Expected: "+"a=b"+" Got: "+qs);
            }

            String pathInfo = (String)msgCtxt.get(MessageContext.PATH_INFO);
            if (pathInfo == null || !pathInfo.equals("/a/b")) {
                throw new WebServiceException("Unexpected PATH_INFO. Expected: "+"/a/b"+" Got: "+pathInfo);
            }

            HttpExchange exchange = (HttpExchange)msgCtxt.get(JAXWSProperties.HTTP_EXCHANGE);
            if (exchange == null ) {
                throw new WebServiceException("HttpExchange object is not populated");
            }

            String replyElement = new String("
hello world
");
            StreamSource reply = new StreamSource(new StringReader (replyElement));
            return reply;
        }
    }

    public void testHttpProperties() throws Exception {
        int port = Util.getFreePort();
        String address = "http://127.0.0.1:"+port+"/hello";
        Endpoint e = Endpoint.create(HTTPBinding.HTTP_BINDING, new MessageContextProvider());
        e.publish(address);

        URL url = new URL(address+"/a/b?a=b");
        InputStream in = url.openStream();
        BufferedReader rdr = new BufferedReader(new InputStreamReader(in));
        String str;
        while ((str=rdr.readLine()) != null);

        e.stop();
    }

}


text:
Create a new instance of `Template`, optionally passing default `options` to initialize with.

* `options` **{Object}**: Options to initialize with.

**Example:**

```js
var Template = require('template');
var template = new Template();
```

### [.transform](index.js#L225)

Assign transform `fn` to `name` or return the value of `name` if no other arguments are passed.

* `name` **{String}**: The name of the transform to add.
* `fn` **{Function}**: The actual transform function.
* `returns` **{Object}**: Returns `Template` for chaining.

Transforms are run immediately during init, and are used to
extend or modify the `cache.data` object, but really anything
on the `this` object can be tranformed.

```js
template.transform('username', function(app) {
  var url = app.cache.data.author.url.split('/');
  app.cache.data.username = url[2];
});
```

### [.route](index.js#L303)

Proxy to the engine `Router#route()` Returns a new `Route` instance for the `path`.

* `path` **{String}**

Routes are isolated middleware stacks for specific paths.
See the `Route` api docs for details.

### [.param](index.js#L321)

Proxy to `Router#param()` with one added api feature. The `name` parameter can be an array of names.

* `name` **{String|Array}**
* `fn` **{Function}**
* `returns` **{Object}** `Template`: for chaining

See the `Router#param()` docs for more details.

Delegate `.METHOD(...)` calls to `router.METHOD(...)`

### [.all](index.js#L431)

Special-cased "all" method, applying the given route `path`, middleware, and callback.

* `path` **{String}**
* **{Function}**: Callback
* `returns` **{Object}** `Template`: for chaining

```js
template.all(/\.md$/, function (file, next) {
  // do stuff next();
});
```

### [.engine](index.js#L517)

* `exts` **{String|Array}**: File extension or array of extensions.
* `fn` **{Function|Object}**: or `options`
* `options` **{Object}**
* `returns` **{Object}** `Template`: to enable chaining

<%= docs("api-engine") %>

Register the given view engine callback `fn` as `ext`. If only `ext`
is passed, the engine registered for `ext` is returned. If no `ext`
is passed, the entire cache is returned.

### [.getEngine](index.js#L538)

Get the engine settings registered for the given `ext`.

* `ext` **{String}**: The engine to get.
* `returns` **{Object}**: Object with methods and settings for the specified engine.

<%= docs("api-getEngine") %>

```js
template.getEngine('.html');
```

### [.getExt](index.js#L565)

Used in the `.render()` method to select the `ext` to use for picking an engine.

* `template` **{Object}**: Template object
* `locals` **{Object}**: Locals object
* `returns` **{String}** `ext`: For determining the engine to use.

This logic can be overridden by passing a custom
function on `options.getExt`, e.g.:

**Example:**

```js
template.option('getExt', function(template, locals) {
  return path.extname(template.path);
});
```

### [.helper](index.js#L604)

Register generic template helpers that can be used with any engine.

* `key` **{String}**: Helper name
* `fn` **{Function}**: Helper function.

Helpers registered using this method will be passed to every
engine, so this method is best for generic javascript functions -
unless you want to see Lo-Dash blow up from `Handlebars.SafeString`.

```js
template.helper('lower', function(str) {
  return str.toLowerCase();
});
```

### [.helpers](index.js#L625)

Register multiple helpers.

* `helpers` **{Object|Array}**: Object, array of objects, or glob patterns.

```js
template.addHelpers({
  a: function() {},
  b: function() {},
  c: function() {},
});
```

### [.asyncHelper](index.js#L657)

Register generic async template helpers that are not specific to an engine.

* `name` **{String}**: Helper name.
* `fn` **{Function}**: Helper function

As with the sync version, helpers registered using this method will
be passed to every engine, so this method is best for generic
javascript functions.

```js
template.asyncHelper('lower', function(str, next) {
  str = str.toLowerCase();
  next();
});
```

### [.asyncHelpers](index.js#L678)

Register multiple async helpers.

* `helpers` **{Object|Array}**: Object, array of objects, or glob patterns.

```js
template.addAsyncHelpers({
  a: function() {},
  b: function() {},
  c: function() {},
});
```

### [.engineHelpers](index.js#L700)

Register an object of helpers for the given `ext` (engine).

* `ext` **{String}**: The engine to register helpers with.
* `returns` **{Object}**: Object of helpers for the specified engine.

```js
template.helpers(require('handlebars-helpers'));
```

### [.validate](index.js#L875)

* `template` **{String}**: a template object

Validate a template object to ensure that it has the properties
expected for applying layouts, choosing engines, and so on.

### [.view](index.js#L930)

* `collection` **{String}**
* `name` **{String}**
* `returns`: {Object}

Get the given view `collection` from views. Optionally
pass a `name` to get a specific template from the
collection.

### [.getType](index.js#L1013)

Get all views of the given [type]. Valid values are `renderable`, `layout` or `partial`.

* `type` **{String}**
* `opts` **{Object}**

```js
var pages = template.getType('renderable');
//=> { pages: { 'home.hbs': { ... }, 'about.hbs': { ... }}, posts: { ... }}
```

### [.mergeType](index.js#L1039)

Merge all collections of the given `type` into a single collection. e.g. `partials` and `includes` would be merged.

* `type` **{String}**: The template type to search.
* `keys` **{String}**: Optionally pass an array of view collection names

If an array of `collections` is passed, only those collections
will be merged and the order in which the collections are defined
in the array will be respected.

### [.mergeLayouts](index.js#L1068)

Merge all `layout` collections based on user-defined options.

* `type` **{String}**: The template type to search.
* `collections` **{String}**: Optionally pass an array of collections

```js

### [.mergePartials](index.js#L1116)

Default method for determining how partials are to be passed to engines. By default, all `partial` collections are merged onto a single `partials` object. To keep each collection on a separate object, you can do `template.disable('mergePartials')`.

* `locals` **{Object}**: Locals should have layout delimiters, if defined
* `returns`: {Object}

If you want to control how partials are merged, you can also
pass a function to the `mergePartials` option:

```js
template.option('mergePartials', function(locals) {
  // do stuff
});
```

### [.findRenderable](index.js#L1205)

Search all renderable `subtypes`, returning the first template with the given `key`.

* `key` **{String}**: The template to search for.
* `subtypes` **{Array}**

  - If `key` is not found an error is thrown.
  - Optionally limit the search to the specified `subtypes`.

### [.findLayout](index.js#L1221)

Search all layout `subtypes`, returning the first template with the given `key`.

* `key` **{String}**: The template to search for.
* `subtypes` **{Array}**

  - If `key` is not found an error is thrown.
  - Optionally limit the search to the specified `subtypes`.

### [.findPartial](index.js#L1237)

Search all partial `subtypes`, returning the first template with the given `key`.

* `key` **{String}**: The template to search for.
* `subtypes` **{Array}**

  - If `key` is not found an error is thrown.
  - Optionally limit the search to the specified `subtypes`.

### [.lookup](index.js#L1251)

* `plural` **{String}**: The view collection to search.
* `name` **{String}**: The name of the template.
* `ext` **{String}**: Optionally pass a file extension to append to `name`

Convenience method for finding a template by `name` on
the given collection. Optionally specify a file extension.

### [.create](index.js#L1284)

Create a new `view` collection and associated convience methods.

* `subtype` **{String}**: Singular name of the collection to create, e.g. `page`.
* `plural` **{String}**: Plural name of the collection, e.g. `pages`.
* `options` **{Object}**: Options for the collection.
    - `isRenderable` **{Boolean}**: Templates that may be rendered at some point
    - `isLayout` **{Boolean}**: Templates to be used as layouts
    - `isPartial` **{Boolean}**: Templates to be used as partial views or includes

* `stack` **{Function|Array}**: Loader function or functions to be run for every template of this type.
* `returns` **{Object}** `Template`: to enable chaining.

Note that when you only specify a name for the type, a plural form is created
automatically (e.g. `page` and `pages`). However, you can define the
`plural` form explicitly if necessary.

### [.compileTemplate](index.js#L1383)

* `template` **{Object}**: The template object with content to compile.
* `options` **{Object}**: Options to pass along to the engine when compile. May include a `context` property to bind to helpers.
* `returns` **{Object}**: Template object to enable chaining.

Compile content on the given `template` object with the specified
engine `options`.

### [.compile](index.js#L1435)

* `file` **{Object|String}**: String or normalized template object.
* `options` **{Object}**
* `isAsync` **{Boolean}**: Load async helpers
* `returns` **{Function}**: Compiled function.

Compile `content` with the given `options`.

### [.compileString](index.js#L1467)

Compile the given string with the specified `options`.

* `str` **{String}**: The string to compile.
* `options` **{Object}**: Options to pass to registered view engines.
* `async` **{Boolean}**: Load async helpers
* `returns`: {Function}

The primary purpose of this method is to get the engine before
passing args to `.compileBase()`.

### [.renderTemplate](index.js#L1516)

* `template` **{Object}**: The template object with content to render.
* `locals` **{Object}**: Locals and/or options to pass to registered view engines.
* `returns`: {String}

Render content on the given `template` object with the specified
engine `options` and `callback`.

### [.render](index.js#L1657)

* `file` **{Object|String}**: String or normalized template object.
* `locals` **{Object}**: Locals and/or options to pass to registered view engines.
* `returns` **{String}**: Rendered string.

Render `content` with the given `options` and optional `callback`.

### [.renderString](index.js#L1685)

Render the given string with the specified `locals` and `callback`.

* `str` **{String}**: The string to render.
* `locals` **{Object}**: Locals and/or options to pass to registered view engines.
* `returns`: {String}

The primary purpose of this method is to get the engine before
passing args to `.renderBase()`.

### [.renderSubtype](index.js#L1713)

Returns a render function for rendering templates of the given `subtype`.

* `plural` **{String}**: Template subtype, e.g. `pages`
* `str` **{String}**: The string to render.
* `locals` **{Object}**: Locals and/or options to pass to registered view engines.
* `returns` **{Function}** `params`

* `returns` **{String}** `string`: The rendered string.

Mostly used internally as a private method, but it's exposed as a
public method since there are cases when it might be useful, like
for rendering templates in a gulp/grunt/assemble plugin.

### [.renderType](index.js#L1745)

* `str` **{String}**: The string to render.
* `locals` **{Object}**: Locals and/or options to pass to registered view engines.
* `returns`: {String}

Render the given string with the specified `locals` and `callback`.


text: package applicationdiscoveryservice