text:
import proto  # type: ignore

from google.cloud.aiplatform_v1.types import (
    batch_prediction_job as gca_batch_prediction_job,
)
from google.cloud.aiplatform_v1.types import custom_job as gca_custom_job
from google.cloud.aiplatform_v1.types import data_labeling_job as gca_data_labeling_job
from google.cloud.aiplatform_v1.types import (
    hyperparameter_tuning_job as gca_hyperparameter_tuning_job,
)
from google.protobuf import field_mask_pb2  # type: ignore

__protobuf__ = proto.module(
    package="google.cloud.aiplatform.v1",
    manifest={
        "CreateCustomJobRequest",
        "GetCustomJobRequest",
        "ListCustomJobsRequest",
        "ListCustomJobsResponse",
        "DeleteCustomJobRequest",
        "CancelCustomJobRequest",
        "CreateDataLabelingJobRequest",
        "GetDataLabelingJobRequest",
        "ListDataLabelingJobsRequest",
        "ListDataLabelingJobsResponse",
        "DeleteDataLabelingJobRequest",
        "CancelDataLabelingJobRequest",
        "CreateHyperparameterTuningJobRequest",
        "GetHyperparameterTuningJobRequest",
        "ListHyperparameterTuningJobsRequest",
        "ListHyperparameterTuningJobsResponse",
        "DeleteHyperparameterTuningJobRequest",
        "CancelHyperparameterTuningJobRequest",
        "CreateBatchPredictionJobRequest",
        "GetBatchPredictionJobRequest",
        "ListBatchPredictionJobsRequest",
        "ListBatchPredictionJobsResponse",
        "DeleteBatchPredictionJobRequest",
        "CancelBatchPredictionJobRequest",
    },
)

class CreateCustomJobRequest(proto.Message):
    r"""Request message for
    [JobService.CreateCustomJob][google.cloud.aiplatform.v1.JobService.CreateCustomJob].

    Attributes:
        parent (str):
            Required. The resource name of the Location to create the
            CustomJob in. Format:
            ``projects/{project}/locations/{location}``
        custom_job (google.cloud.aiplatform_v1.types.CustomJob):
            Required. The CustomJob to create.
    """

    parent = proto.Field(proto.STRING, number=1,)
    custom_job = proto.Field(proto.MESSAGE, number=2, message=gca_custom_job.CustomJob,)

class GetCustomJobRequest(proto.Message):
    r"""Request message for
    [JobService.GetCustomJob][google.cloud.aiplatform.v1.JobService.GetCustomJob].

    Attributes:
        name (str):
            Required. The name of the CustomJob resource. Format:
            ``projects/{project}/locations/{location}/customJobs/{custom_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class ListCustomJobsRequest(proto.Message):
    r"""Request message for
    [JobService.ListCustomJobs][google.cloud.aiplatform.v1.JobService.ListCustomJobs].

    Attributes:
        parent (str):
            Required. The resource name of the Location to list the
            CustomJobs from. Format:
            ``projects/{project}/locations/{location}``
        filter (str):
            The standard list filter.

            Supported fields:

            -  ``display_name`` supports = and !=.

            -  ``state`` supports = and !=.

            Some examples of using the filter are:

            -  ``state="JOB_STATE_SUCCEEDED" AND display_name="my_job"``

            -  ``state="JOB_STATE_RUNNING" OR display_name="my_job"``

            -  ``NOT display_name="my_job"``

            -  ``state="JOB_STATE_FAILED"``
        page_size (int):
            The standard list page size.
        page_token (str):
            The standard list page token. Typically obtained via
            [ListCustomJobsResponse.next_page_token][google.cloud.aiplatform.v1.ListCustomJobsResponse.next_page_token]
            of the previous
            [JobService.ListCustomJobs][google.cloud.aiplatform.v1.JobService.ListCustomJobs]
            call.
        read_mask (google.protobuf.field_mask_pb2.FieldMask):
            Mask specifying which fields to read.
    """

    parent = proto.Field(proto.STRING, number=1,)
    filter = proto.Field(proto.STRING, number=2,)
    page_size = proto.Field(proto.INT32, number=3,)
    page_token = proto.Field(proto.STRING, number=4,)
    read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,)

class ListCustomJobsResponse(proto.Message):
    r"""Response message for
    [JobService.ListCustomJobs][google.cloud.aiplatform.v1.JobService.ListCustomJobs]

    Attributes:
        custom_jobs (Sequence[google.cloud.aiplatform_v1.types.CustomJob]):
            List of CustomJobs in the requested page.
        next_page_token (str):
            A token to retrieve the next page of results. Pass to
            [ListCustomJobsRequest.page_token][google.cloud.aiplatform.v1.ListCustomJobsRequest.page_token]
            to obtain that page.
    """

    @property
    def raw_page(self):
        return self

    custom_jobs = proto.RepeatedField(
        proto.MESSAGE, number=1, message=gca_custom_job.CustomJob,
    )
    next_page_token = proto.Field(proto.STRING, number=2,)

class DeleteCustomJobRequest(proto.Message):
    r"""Request message for
    [JobService.DeleteCustomJob][google.cloud.aiplatform.v1.JobService.DeleteCustomJob].

    Attributes:
        name (str):
            Required. The name of the CustomJob resource to be deleted.
            Format:
            ``projects/{project}/locations/{location}/customJobs/{custom_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class CancelCustomJobRequest(proto.Message):
    r"""Request message for
    [JobService.CancelCustomJob][google.cloud.aiplatform.v1.JobService.CancelCustomJob].

    Attributes:
        name (str):
            Required. The name of the CustomJob to cancel. Format:
            ``projects/{project}/locations/{location}/customJobs/{custom_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class CreateDataLabelingJobRequest(proto.Message):
    r"""Request message for
    [JobService.CreateDataLabelingJob][google.cloud.aiplatform.v1.JobService.CreateDataLabelingJob].

    Attributes:
        parent (str):
            Required. The parent of the DataLabelingJob. Format:
            ``projects/{project}/locations/{location}``
        data_labeling_job (google.cloud.aiplatform_v1.types.DataLabelingJob):
            Required. The DataLabelingJob to create.
    """

    parent = proto.Field(proto.STRING, number=1,)
    data_labeling_job = proto.Field(
        proto.MESSAGE, number=2, message=gca_data_labeling_job.DataLabelingJob,
    )

class GetDataLabelingJobRequest(proto.Message):
    r"""Request message for
    [JobService.GetDataLabelingJob][google.cloud.aiplatform.v1.JobService.GetDataLabelingJob].

    Attributes:
        name (str):
            Required. The name of the DataLabelingJob. Format:
            ``projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class ListDataLabelingJobsRequest(proto.Message):
    r"""Request message for
    [JobService.ListDataLabelingJobs][google.cloud.aiplatform.v1.JobService.ListDataLabelingJobs].

    Attributes:
        parent (str):
            Required. The parent of the DataLabelingJob. Format:
            ``projects/{project}/locations/{location}``
        filter (str):
            The standard list filter.

            Supported fields:

            -  ``display_name`` supports = and !=.

            -  ``state`` supports = and !=.

            Some examples of using the filter are:

            -  ``state="JOB_STATE_SUCCEEDED" AND display_name="my_job"``

            -  ``state="JOB_STATE_RUNNING" OR display_name="my_job"``

            -  ``NOT display_name="my_job"``

            -  ``state="JOB_STATE_FAILED"``
        page_size (int):
            The standard list page size.
        page_token (str):
            The standard list page token.
        read_mask (google.protobuf.field_mask_pb2.FieldMask):
            Mask specifying which fields to read. FieldMask represents a
            set of symbolic field paths. For example, the mask can be
            ``paths: "name"``. The "name" here is a field in
            DataLabelingJob. If this field is not set, all fields of the
            DataLabelingJob are returned.
        order_by (str):
            A comma-separated list of fields to order by, sorted in
            ascending order by default. Use ``desc`` after a field name
            for descending.
    """

    parent = proto.Field(proto.STRING, number=1,)
    filter = proto.Field(proto.STRING, number=2,)
    page_size = proto.Field(proto.INT32, number=3,)
    page_token = proto.Field(proto.STRING, number=4,)
    read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,)
    order_by = proto.Field(proto.STRING, number=6,)

class ListDataLabelingJobsResponse(proto.Message):
    r"""Response message for
    [JobService.ListDataLabelingJobs][google.cloud.aiplatform.v1.JobService.ListDataLabelingJobs].

    Attributes:
        data_labeling_jobs (Sequence[google.cloud.aiplatform_v1.types.DataLabelingJob]):
            A list of DataLabelingJobs that matches the
            specified filter in the request.
        next_page_token (str):
            The standard List next-page token.
    """

    @property
    def raw_page(self):
        return self

    data_labeling_jobs = proto.RepeatedField(
        proto.MESSAGE, number=1, message=gca_data_labeling_job.DataLabelingJob,
    )
    next_page_token = proto.Field(proto.STRING, number=2,)

class DeleteDataLabelingJobRequest(proto.Message):
    r"""Request message for
    [JobService.DeleteDataLabelingJob][google.cloud.aiplatform.v1.JobService.DeleteDataLabelingJob].

    Attributes:
        name (str):
            Required. The name of the DataLabelingJob to be deleted.
            Format:
            ``projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class CancelDataLabelingJobRequest(proto.Message):
    r"""Request message for
    [JobService.CancelDataLabelingJob][google.cloud.aiplatform.v1.JobService.CancelDataLabelingJob].

    Attributes:
        name (str):
            Required. The name of the DataLabelingJob. Format:
            ``projects/{project}/locations/{location}/dataLabelingJobs/{data_labeling_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class CreateHyperparameterTuningJobRequest(proto.Message):
    r"""Request message for
    [JobService.CreateHyperparameterTuningJob][google.cloud.aiplatform.v1.JobService.CreateHyperparameterTuningJob].

    Attributes:
        parent (str):
            Required. The resource name of the Location to create the
            HyperparameterTuningJob in. Format:
            ``projects/{project}/locations/{location}``
        hyperparameter_tuning_job (google.cloud.aiplatform_v1.types.HyperparameterTuningJob):
            Required. The HyperparameterTuningJob to
            create.
    """

    parent = proto.Field(proto.STRING, number=1,)
    hyperparameter_tuning_job = proto.Field(
        proto.MESSAGE,
        number=2,
        message=gca_hyperparameter_tuning_job.HyperparameterTuningJob,
    )

class GetHyperparameterTuningJobRequest(proto.Message):
    r"""Request message for
    [JobService.GetHyperparameterTuningJob][google.cloud.aiplatform.v1.JobService.GetHyperparameterTuningJob].

    Attributes:
        name (str):
            Required. The name of the HyperparameterTuningJob resource.
            Format:
            ``projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class ListHyperparameterTuningJobsRequest(proto.Message):
    r"""Request message for
    [JobService.ListHyperparameterTuningJobs][google.cloud.aiplatform.v1.JobService.ListHyperparameterTuningJobs].

    Attributes:
        parent (str):
            Required. The resource name of the Location to list the
            HyperparameterTuningJobs from. Format:
            ``projects/{project}/locations/{location}``
        filter (str):
            The standard list filter.

            Supported fields:

            -  ``display_name`` supports = and !=.

            -  ``state`` supports = and !=.

            Some examples of using the filter are:

            -  ``state="JOB_STATE_SUCCEEDED" AND display_name="my_job"``

            -  ``state="JOB_STATE_RUNNING" OR display_name="my_job"``

            -  ``NOT display_name="my_job"``

            -  ``state="JOB_STATE_FAILED"``
        page_size (int):
            The standard list page size.
        page_token (str):
            The standard list page token. Typically obtained via
            [ListHyperparameterTuningJobsResponse.next_page_token][google.cloud.aiplatform.v1.ListHyperparameterTuningJobsResponse.next_page_token]
            of the previous
            [JobService.ListHyperparameterTuningJobs][google.cloud.aiplatform.v1.JobService.ListHyperparameterTuningJobs]
            call.
        read_mask (google.protobuf.field_mask_pb2.FieldMask):
            Mask specifying which fields to read.
    """

    parent = proto.Field(proto.STRING, number=1,)
    filter = proto.Field(proto.STRING, number=2,)
    page_size = proto.Field(proto.INT32, number=3,)
    page_token = proto.Field(proto.STRING, number=4,)
    read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,)

class ListHyperparameterTuningJobsResponse(proto.Message):
    r"""Response message for
    [JobService.ListHyperparameterTuningJobs][google.cloud.aiplatform.v1.JobService.ListHyperparameterTuningJobs]

    Attributes:
        hyperparameter_tuning_jobs (Sequence[google.cloud.aiplatform_v1.types.HyperparameterTuningJob]):
            List of HyperparameterTuningJobs in the requested page.
            [HyperparameterTuningJob.trials][google.cloud.aiplatform.v1.HyperparameterTuningJob.trials]
            of the jobs will be not be returned.
        next_page_token (str):
            A token to retrieve the next page of results. Pass to
            [ListHyperparameterTuningJobsRequest.page_token][google.cloud.aiplatform.v1.ListHyperparameterTuningJobsRequest.page_token]
            to obtain that page.
    """

    @property
    def raw_page(self):
        return self

    hyperparameter_tuning_jobs = proto.RepeatedField(
        proto.MESSAGE,
        number=1,
        message=gca_hyperparameter_tuning_job.HyperparameterTuningJob,
    )
    next_page_token = proto.Field(proto.STRING, number=2,)

class DeleteHyperparameterTuningJobRequest(proto.Message):
    r"""Request message for
    [JobService.DeleteHyperparameterTuningJob][google.cloud.aiplatform.v1.JobService.DeleteHyperparameterTuningJob].

    Attributes:
        name (str):
            Required. The name of the HyperparameterTuningJob resource
            to be deleted. Format:
            ``projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class CancelHyperparameterTuningJobRequest(proto.Message):
    r"""Request message for
    [JobService.CancelHyperparameterTuningJob][google.cloud.aiplatform.v1.JobService.CancelHyperparameterTuningJob].

    Attributes:
        name (str):
            Required. The name of the HyperparameterTuningJob to cancel.
            Format:
            ``projects/{project}/locations/{location}/hyperparameterTuningJobs/{hyperparameter_tuning_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class CreateBatchPredictionJobRequest(proto.Message):
    r"""Request message for
    [JobService.CreateBatchPredictionJob][google.cloud.aiplatform.v1.JobService.CreateBatchPredictionJob].

    Attributes:
        parent (str):
            Required. The resource name of the Location to create the
            BatchPredictionJob in. Format:
            ``projects/{project}/locations/{location}``
        batch_prediction_job (google.cloud.aiplatform_v1.types.BatchPredictionJob):
            Required. The BatchPredictionJob to create.
    """

    parent = proto.Field(proto.STRING, number=1,)
    batch_prediction_job = proto.Field(
        proto.MESSAGE, number=2, message=gca_batch_prediction_job.BatchPredictionJob,
    )

class GetBatchPredictionJobRequest(proto.Message):
    r"""Request message for
    [JobService.GetBatchPredictionJob][google.cloud.aiplatform.v1.JobService.GetBatchPredictionJob].

    Attributes:
        name (str):
            Required. The name of the BatchPredictionJob resource.
            Format:
            ``projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class ListBatchPredictionJobsRequest(proto.Message):
    r"""Request message for
    [JobService.ListBatchPredictionJobs][google.cloud.aiplatform.v1.JobService.ListBatchPredictionJobs].

    Attributes:
        parent (str):
            Required. The resource name of the Location to list the
            BatchPredictionJobs from. Format:
            ``projects/{project}/locations/{location}``
        filter (str):
            The standard list filter.

            Supported fields:

            -  ``display_name`` supports = and !=.

            -  ``state`` supports = and !=.

            -  ``model_display_name`` supports = and !=

            Some examples of using the filter are:

            -  ``state="JOB_STATE_SUCCEEDED" AND display_name="my_job"``

            -  ``state="JOB_STATE_RUNNING" OR display_name="my_job"``

            -  ``NOT display_name="my_job"``

            -  ``state="JOB_STATE_FAILED"``
        page_size (int):
            The standard list page size.
        page_token (str):
            The standard list page token. Typically obtained via
            [ListBatchPredictionJobsResponse.next_page_token][google.cloud.aiplatform.v1.ListBatchPredictionJobsResponse.next_page_token]
            of the previous
            [JobService.ListBatchPredictionJobs][google.cloud.aiplatform.v1.JobService.ListBatchPredictionJobs]
            call.
        read_mask (google.protobuf.field_mask_pb2.FieldMask):
            Mask specifying which fields to read.
    """

    parent = proto.Field(proto.STRING, number=1,)
    filter = proto.Field(proto.STRING, number=2,)
    page_size = proto.Field(proto.INT32, number=3,)
    page_token = proto.Field(proto.STRING, number=4,)
    read_mask = proto.Field(proto.MESSAGE, number=5, message=field_mask_pb2.FieldMask,)

class ListBatchPredictionJobsResponse(proto.Message):
    r"""Response message for
    [JobService.ListBatchPredictionJobs][google.cloud.aiplatform.v1.JobService.ListBatchPredictionJobs]

    Attributes:
        batch_prediction_jobs (Sequence[google.cloud.aiplatform_v1.types.BatchPredictionJob]):
            List of BatchPredictionJobs in the requested
            page.
        next_page_token (str):
            A token to retrieve the next page of results. Pass to
            [ListBatchPredictionJobsRequest.page_token][google.cloud.aiplatform.v1.ListBatchPredictionJobsRequest.page_token]
            to obtain that page.
    """

    @property
    def raw_page(self):
        return self

    batch_prediction_jobs = proto.RepeatedField(
        proto.MESSAGE, number=1, message=gca_batch_prediction_job.BatchPredictionJob,
    )
    next_page_token = proto.Field(proto.STRING, number=2,)

class DeleteBatchPredictionJobRequest(proto.Message):
    r"""Request message for
    [JobService.DeleteBatchPredictionJob][google.cloud.aiplatform.v1.JobService.DeleteBatchPredictionJob].

    Attributes:
        name (str):
            Required. The name of the BatchPredictionJob resource to be
            deleted. Format:
            ``projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

class CancelBatchPredictionJobRequest(proto.Message):
    r"""Request message for
    [JobService.CancelBatchPredictionJob][google.cloud.aiplatform.v1.JobService.CancelBatchPredictionJob].

    Attributes:
        name (str):
            Required. The name of the BatchPredictionJob to cancel.
            Format:
            ``projects/{project}/locations/{location}/batchPredictionJobs/{batch_prediction_job}``
    """

    name = proto.Field(proto.STRING, number=1,)

__all__ = tuple(sorted(__protobuf__.manifest))


text:
package apps.lightrays.raytracer.scene;

/**
 * The Class CameraAnimation.
 */
public class CameraAnimation {

	/** The end eye position. */
	public Vector endEyePosition;

	/** The frames. */
	public int frames;

	/** The start eye position. */
	public Vector startEyePosition;

	/**
	 * Instantiates a new camera animation.
	 */
	public CameraAnimation() {

	}

	/**
	 * Gets the camera position for frame.
	 *
	 * @param frame
	 *            the frame
	 * @return the camera position for frame
	 */
	public Vector getCameraPositionForFrame(int frame) {
		Vector v = new Vector();

		double dx = endEyePosition.x - startEyePosition.x;
		double dy = endEyePosition.y - startEyePosition.y;
		double dz = endEyePosition.z - startEyePosition.z;

		double f = ((double) frame / (double) frames);

		dx *= f;
		dy *= f;
		dz *= f;

		v.x = startEyePosition.x + dx;
		v.y = startEyePosition.y + dy;
		v.z = startEyePosition.z + dz;

		return v;
	}

}

redpajama_set_name: RedPajamaGithub


text:
//-----------------------------------------------------------------------
// <copyright file="BoundedStashImpl.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2015 Typesafe Inc. <http://www.typesafe.com>
//     Copyright (C) 2013-2015 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

namespace Akka.Actor.Internal
{
    /// <summary>INTERNAL
    /// A stash implementation that is bounded
    /// <remarks>Note! Part of internal API. Breaking changes may occur without notice. Use at own risk.</remarks>
    /// </summary>
    public class BoundedStashImpl : AbstractStash
    {
        /// <summary>INTERNAL
        /// A stash implementation that is bounded
        /// <remarks>Note! Part of internal API. Breaking changes may occur without notice. Use at own risk.</remarks>
        /// </summary>
        public BoundedStashImpl(IActorContext context, int capacity = 100)
            : base(context, capacity)
        {
        }
    }
}


text:
using NUnit.Framework;
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Pash;

namespace PashConsoleTests
{
    [TestFixture]
    public class ConsoleStartTest
    {
        // NOTE: make sure when using functions with "args", that the arguments
        // only use *SINGLE* quotes itself

        private Regex _whiteSpaceRegex = new Regex(@"\s");

        private String QuoteWithSpace(string input)
        {
            if (_whiteSpaceRegex.IsMatch(input))
            {
                return String.Format(@"""{0}""", input);
            }
            return input;
        }

        private Process CreateDotNetProcess(string command, params string[] args)
        {
            string realCmd = null;
            List<string> realArgs = new List<string>();
            // find out which runtime environment we have: MS .NET or Mono
            if (Type.GetType("Mono.Runtime") != null)
            {
                realCmd = "mono";
                realArgs.Add(QuoteWithSpace(command));
            }
            else
            {
                realCmd = command;
            }

            foreach (var arg in args)
            {
                realArgs.Add(QuoteWithSpace(arg));
            }
            var process = new Process();
            process.StartInfo.FileName = realCmd;
            process.StartInfo.Arguments = String.Join(" ", realArgs);
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            return process;
        }

        private Process CreatePashProcess(params string[] args)
        {
            var cmd = new Uri(typeof(Pash.Program).Assembly.CodeBase).LocalPath;
            return CreateDotNetProcess(cmd, args);
        }

        private string FinishProcess(Process process, bool closeInput = true)
        {
            if (closeInput)
            {
                process.StandardInput.Flush();
                process.StandardInput.Close();
            }
            var output = process.StandardOutput.ReadToEnd();
            if (!process.WaitForExit(3000))
            {
                process.Kill();
                throw new Exception("Pash didn't exit");
            }
            return output;
        }

        [Test]
        public void StartAndExitWithoutError()
        {
            var process = CreatePashProcess();
            process.Start();
            FinishProcess(process);
            Assert.AreEqual(0, process.ExitCode);
        }

        [Test]
        public void StartAndExitByCommand()
        {
            var process = CreatePashProcess();
            process.Start();
            process.StandardInput.WriteLine("exit");
            process.StandardInput.WriteLine(@"Write-Host 'foo'");
            var output = FinishProcess(process);
            Assert.False(output.Contains("foo"));
        }

        [Test]
        public void StartWithCommandInArg()
        {
            var process = CreatePashProcess(@"Write-Host 'foo'");
            process.Start();
            var output = FinishProcess(process);
            // pash should only execute the command, show no banner and not
            // be in interactive mode. so the output should only contain the
            // command's output
            Assert.AreEqual("foo" + Environment.NewLine, output);
        }

        [Test]
        public void StartWithMultipleArgs()
        {
            var process = CreatePashProcess(@"Write-Host 'foo'", @"Write-Host 'bar'");
            process.Start();
            process.StandardInput.WriteLine(@"Write-Host 'interactiveInput'"); // should be ignored by pash process
            var output = FinishProcess(process);
            // pash should only execute the command, show no banner and not
            // be in interactive mode. so the output should only contain the
            // command's output
            Assert.AreEqual("foo" + Environment.NewLine + "bar" + Environment.NewLine, output);
        }

        [Test]
        public void StartWithArgsAndInteractiveInput()
        {
            var process = CreatePashProcess("-noexit", @"Write-Host 'foo'");
            process.Start();
            process.StandardInput.WriteLine(@"Write-Host 'interactiveInput'"); // should be ignored by pash process
            var output = FinishProcess(process);
            // pash should execute the provided args and what's coming from stdin
            // as it will also print a prompt, we won't do an exact comparison
            Assert.True(output.Contains("foo"));
            Assert.True(output.Contains("interactiveInput"));
            Assert.False(output.Contains(FullHost.BannerText));
        }
    }
}


text:
package org.apache.wiki.api.filters;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class FilterSupportOperationsTest {

    @Test
    public void testFilterSupportOperations() {
        // the other branch of these methods is properly tested through the jspwiki-210-adapers module
        Assertions.assertNull( FilterSupportOperations.methodOfNonPublicAPI( new TestPageFilter(), "preTranslate" ) );
        Assertions.assertEquals( "duh", FilterSupportOperations.executePageFilterPhase( () -> "duh", null, new TestPageFilter() ) );
    }

}


text:
class cPig :
	public cPassiveMonster
{
	typedef cPassiveMonster super;

public:
	cPig(void);

	CLASS_PROTODEF(cPig);

	virtual void GetDrops(cItems & a_Drops, cEntity * a_Killer = NULL) override;
	virtual void OnRightClicked(cPlayer & a_Player) override;

	virtual const cItem GetFollowedItem(void) const override { return cItem(E_ITEM_CARROT); }

	bool IsSaddled(void) const { return m_bIsSaddled; }

private:

	bool m_bIsSaddled;

} ;


text:
$("#enqFrm").validate({
    rules: {email: {require_from_group: [1, ".cntgrp"]},
        mobile: {
            require_from_group: [1, ".cntgrp"]
        }
    },
    messages: {
        email: {
            require_from_group: "Either Mobile or Email Id"
        },
        mobile: {
            require_from_group: "Either Mobile or Email Id"
        }
    },
    submitHandler: function (form) {
        var btn = $("#enqFrm button[type='submit']").loading('set');
        $.post($(form).attr('action'), $(form).serialize(), function (o) {
            if (o.sts == 'success') {
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.reload();
                    }});
            } else
                $.alert({title: 'Sorry!', content: o.msg});
        }, 'json').always(function () {
            btn.loading('reset');
        });
        return false;
    }
});
$(document).ready(function () {
    $('input:radio[name=visitedbefore]').change(function () {

        if (this.value == 'yes') {

            $('#visitedbefore_form').show();
        } else if (this.value == 'no') {

            $('#visitedbefore_form').hide();
        }
    });
    $('input:radio[name=extendstay]').change(function () {

        if (this.value == 'yes') {

            $('#extendstaydetails').show();
        } else if (this.value == 'no') {

            $('#extendstaydetails').hide();
        }
    });
    $('input:checkbox[name=agreement]').change(function () {

        if (this.checked == true) {

            $('#payment').show();
        } else {

            $('#payment').hide();
        }
    });
});
function agrement()
{
    if ($('#agreement').checked == true) {

        $('#payment').show();
    } else {

        $('#payment').hide();
    }
}
function sameaddress(f) {
    if (f.sameAddress.checked == true) {
        f.phouseno.value = f.houseno.value;
        f.pcity.value = f.city.value;
        f.pdistrict.value = f.district.value;
    }
}
function maritalStatus(val) {
    if (val == 'Married') {
        $('#spouse_form').show();
    } else {
        $('#spouse_form').hide();
    }
}

$(document).ready(function () {
    $('input:radio[name=grand_pak]').change(function () {
        if (this.value == 'yes') {

            $('#pak_details').show();
        } else if (this.value == 'no') {

            $('#pak_details').hide();
        }
    });
    $('input:radio[name=military]').change(function () {
        if (this.value == 'yes') {

            $('#military_form').show();
        } else if (this.value == 'no') {

            $('#military_form').hide();
        }
    });
});
$("#applyVisaFrm").validate({
    onkeyup: function (element) {
        if ((element.name == 'v_code'))
            return false;
        else
            $(element).valid();
    },
    rules: {
        re_email: {equalTo: "#email"},
    },
    messages: {
        re_email: {equalTo: "Please enter the same Email as above"},
    },
    submitHandler: function (form) {
        var btn = $("#applyVisaFrm button[type='submit']").loading('set');
        $.post($(form).attr('action'), $(form).serialize(), function (o) {
            if (o.sts == 'success') {
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.href = o.url;
                    }});
            } else
                $.alert({title: 'Sorry!', content: o.msg});
        }, 'json').always(function () {
            btn.loading('reset');
        });
        return false;
    }
});
$("#searchAppFrm").validate({
    submitHandler: function (form) {
        var btn = $("#searchAppstsFrm button[type='submit']").loading('set');
        $.post($(form).attr('action'), $(form).serialize(), function (o) {
            if (o.sts == 'success') {
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.href = o.url;
                    }});
            } else if (o.sts == 'pending') {
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.reload();
                    }});
            } else if (o.sts == 'complete') {
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.reload();
                    }});
            } else
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.reload();
                    }});
        }, 'json').always(function () {
            btn.loading('reset');
        });
        return false;
    }
});
$("#searchAppstsFrm").validate({
    submitHandler: function (form) {
        var btn = $("#searchAppstsFrm button[type='submit']").loading('set');
        $.post($(form).attr('action'), $(form).serialize(), function (o) {
            if (o.sts == 'success') {
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.href = o.url;
                    }});
            } else if (o.sts == 'pending') {
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.reload();
                    }});
            } else if (o.sts == 'complete') {
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.reload();
                    }});
            } else
                $.alert({title: o.title, content: o.msg, confirm: function () {
                        window.location.reload();
                    }});
        }, 'json').always(function () {
            btn.loading('reset');
        });
        return false;
    }
});
$("#visa_regFrm").validate({
    submitHandler: function (form) {
        return true;
    }
});
$("#step3").validate({
    submitHandler: function (form) {
        return true;
    }
});
$("#step4Form").validate({
    submitHandler: function (form) {
        return true;
    }
});
$("#passport_uploadFrm").validate({
    submitHandler: function (form) {
        return true;
    }
});
function acquire_naturalization(val) {
    if (val == 'Naturalization') {
        $('#prev_nationality').show();
    } else {
        $('#prev_nationality').hide();
    }
}
$(document).ready(function () {
    $('input:radio[name=ic]').change(function () {
        if (this.value == 'yes') {
            $('#ic_form').show();
        } else if (this.value == 'no') {
            $('#ic_form').hide();
        }
    });
    $('select[name=religion]').change(function () {
        var v = $(this).val();
        if (v == 'Others') {
            $('#other_relation').prop('disabled', false).attr('placeholder', 'Please specify your Religion');
        } else {
            $('#other_relation').prop('disabled', true).attr('placeholder', '');
        }
    });
});
$(document).on('click', "[name='have_previous_name']", function () {
    var th = $(this);
    if (th.prop('checked')) {
        $('#previous_name').show();
    } else {
        $('#previous_name').hide();
    }
});

$(function () {
    $('.date_picker').datetimepicker({
//        viewMode: 'years',
        format: 'DD/MM/YYYY'
    });
});


text:
import React,{Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

import Sidebar from "./sidebar";
import Workspace from "./workspace";
import Footer from "./footer";
import Modal from "./modal";

class Index extends Component {

    constructor(props){
        super(props);
        this.state = {};
    }

    render() {
        return (

                    <Sidebar />
                    <Workspace />

                <Modal />

        );
    }
}

function mapStateToProps({}){
    return {};
}

function mapDispatchToProps(dispatch){
    return bindActionCreators({},dispatch);
}

export default connect (mapStateToProps,mapDispatchToProps)(Index);


text:
require 'active_record'

module Carto
  class LayersUserTable < ActiveRecord::Base

    belongs_to :layer, class_name: Carto::Layer
    belongs_to :user_table, class_name: Carto::UserTable, foreign_key: :table_id

  end
end


text:
var App = require('app');
var date = require('utils/date/date');
var sort = require('views/common/sort_view');
require('views/main/service/info/metrics/flume/flume_agent_metrics_section');

App.MainDashboardServiceFlumeView = App.TableView.extend(App.MainDashboardServiceViewWrapper, {
  templateName: require('templates/main/service/services/flume'),

  isFullWidth: true,

  pagination: false,

  selectedHost: null,

  flumeAgentsCount: 0,

  content: function () {
    var flumeAgents = this.get('service.agents'),
      content = [];

    flumeAgents.mapProperty('hostName').uniq().forEach(function (hostName) {
      var agents = flumeAgents.filterProperty('hostName', hostName);
      content.push(
        Em.Object.create({
          hostName: hostName,
          agents: agents,
          rowspan: agents.length,
          firtstAgent: agents[0],
          otherAgents: agents.without(agents[0])
        })
      );
    });
    return content;
  }.property('App.FlumeAgent.@each.id', 'flumeAgentsCount'),

  summaryHeader: function () {
    var agentCount = App.FlumeService.find().objectAt(0).get('agents.length'),
      hostCount = this.get('service.flumeHandlersTotal');
    return this.t("dashboard.services.flume.summary.title")
      .format(hostCount, (hostCount > 1 ? "s" : ""), agentCount, (agentCount > 1 ? "s" : ""));
  }.property('service.agents', 'service.hostComponents.length'),

  flumeHandlerComponent: Em.Object.create({
    componentName: 'FLUME_HANDLER'
  }),

  agentView: Em.View.extend({
    content: null,
    tagName: 'tr',

    click: function (e) {
      var numberOfAgents = this.get('content.agents').length;
      if ($(e.target).attr('class') == "agent-host-name" || $(e.target).attr('class') == "agent-host-link") {
        var currentTargetRow = $(e.currentTarget);
        if ($(e.target).attr('class') == "agent-host-link") {
          currentTargetRow = currentTargetRow.parent(".agent-host-name").parent();
        }
        currentTargetRow.parents("table:first").find('tr').removeClass('highlight');
        currentTargetRow.addClass('highlight').nextAll("tr").slice(0, numberOfAgents - 1).addClass('highlight');
        this.get('parentView').showAgentInfo(this.get('content'));
      }
    }
  }),

  sortView: sort.wrapperView,

  hostSort: sort.fieldView.extend({
    column: '1',
    name: 'hostName',
    displayName: Em.I18n.t('common.host')
  }),

  didInsertElement: function () {
    var self = this;
    this.filter();
    this.$().on('click', '.flume-agents-actions .dropdown-toggle', function (e) {
      self.setDropdownPosition(this);
    });
  },

  /**
   * Locate dropdown menu absolutely outside of scrollable block
   * @param element
   */
  setDropdownPosition: function (element) {
    var button = $(element);
    var dropdown = button.parent().find('.dropdown-menu');
    dropdown.css('top', button.offset().top + button.outerHeight() + "px");
    dropdown.css('left', button.offset().left + "px");
  },

  willDestroyElement: function () {
    this.$().off();
  },

  /**
   * Change classes for dropdown DOM elements after status change of selected agent
   */
  setActionsDropdownClasses: function () {
    this.get('content').forEach(function (hosts) {
      hosts.agents.forEach(function (agent) {
        agent.set('isStartAgentDisabled', agent.get('status') !== 'NOT_RUNNING');
        agent.set('isStopAgentDisabled', agent.get('status') !== 'RUNNING');
      });
    });
  }.observes('service.agents.@each.status'),

  updateFlumeAgentsCount: function () {
    this.set('flumeAgentsCount', this.get('service.agents.length'));
  }.observes('service.agents.length'),

  /**
   * Action handler from flume template.
   * Highlight selected row and show metrics graphs of selected agent.
   *
   * @method showAgentInfo
   * @param {object} host
   */
  showAgentInfo: function (host) {
    this.set('selectedHost', host);
    this.setAgentMetrics(host);
  },
  /**
   * Show Flume agent metric.
   *
   * @method setFlumeAgentMetric
   * @param {object} host
   */
  setAgentMetrics: function (host) {
    var mockMetricData = [
      {
        header: 'channelName',
        metricType: 'CHANNEL'
      },
      {
        header: 'sinkName',
        metricType: 'SINK'
      },
      {
        header: 'sourceName',
        metricType: 'SOURCE'
      }
    ];
    var metricViews = mockMetricData.map(function (mockData, index) {
      return App.FlumeAgentMetricsSectionView.extend({
        index: index,
        metricTypeKey: mockData.header,
        metricView: App.MainServiceInfoFlumeGraphsView.extend(),
        metricViewData: {
          agent: host,
          metricType: mockData.metricType
        }
      });
    });
    this.set('parentView.collapsedSections', metricViews);
  }
});


text:
title: Introduction
id: tuto-1-introduction
slug: 1-introduction
---

This tutorial shows how to build a real-world application with React and Foal. It assumes that you have already read the first guide *[How to build a Simple To-Do List](../simple-todo-list/1-installation.md)* and that you have a basic knowledge of React.

In this tutorial, you will learn to:
- establish a connection with MySQL or Postgres,
- provide credentials to the application in a secure way,
- create models with many-to-one relations,
- use a query builder,
- generate an interface to test your API (Swagger UI),
- fix same-origin policy errors,
- allow users to log in and register with an email and a password,
- authenticate users on the frontend and the backend,
- manage access control,
- protect against CSRF attacks,
- upload and save files,
- allow users to connect with a social provider (Google),
- and build the application for production.

> *For the sake of simplicity, the front-end application will not use a state management library (such as [redux](https://redux.js.org/)). But you can of course add one if you wish. The logic to follow will remain mainly the same.*

## Application Overview

The application you will create is a social website where users can share interesting links to tutorials. All posts will be public, so no authentication will be required to view them. Publishing a post, on the other hand, will require the creation of an account.

*Feed page*
![Feed page](./images/feed.png)

*Profile page*
![Profile page](./images/profile.png)

*Registration and login pages*
![Registration and login pages](./images/sign-up-and-log-in.png)

## Get Started

Let's get started. First of all, create a new directory.

```bash
mkdir foal-react-tuto
```

Generate the backend application.

```bash
cd foal-react-tuto
foal createapp backend-app
```

Then start the development server.

```bash
cd backend-app
npm run dev
```

Go to [http://localhost:3001](http://localhost:3001) in your browser. You should see the *Welcome on board* message.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MbUnit.Framework;

using WatchMeRun.Library;

namespace WatchMeRun.Library.Tests
{
  [TestFixture]
  public class ConfigLoaderTests
  {
    [Test]
    public void Test1()
    {
      var dirs = ConfigLoader.Load("app.toml");
      Assert.IsNotNull(dirs);
      WatchDirectory dir = dirs.First();

      Assert.AreEqual(@"c:\directory",dir.Path);
      Assert.AreEqual("watchme",dir.Watch);
      Assert.AreEqual("runme.bat",dir.Run);

      dir = dirs.ElementAt(1);
      Assert.AreEqual(@"c:\directory2", dir.Path);
      Assert.AreEqual("build", dir.Watch);
      Assert.AreEqual("build.bat", dir.Run);
    }
  }
}


text:
package main

import (
	"fmt"
	"os/exec"
	"syscall"
)

const (
	StateNil = iota
	StateInitialized
	StateRunning
)

type Program struct {
	config *ProgramConfig
	state  int
	cmd    *exec.Cmd
}

// ProgramConfig holds all the parameters for going to run and maintain the
// state of the supervised process. These variables are all configurable via
// the program's yaml format config file.
type ProgramConfig struct {
	Command     string
	Name        string
	Environment map[string]string
	StopSignal  syscall.Signal
	Dir         string
}

// init sets up other data and structs and performs checks to make sure
// everything is available to properly run. The logger param is sent by the
// parent going struct.
func (p *Program) init() error {
	var err error

	p.cmd = exec.Command(p.config.Command)
	p.cmd.Dir = p.config.Dir
	for key, value := range p.config.Environment {
		p.cmd.Env = append(p.cmd.Env, key+"="+value)
	}

	p.state = StateInitialized

	return err
}

func (p *Program) run() {
	p.cmd.Run()

}

func newProgramConfig(filename string) (*ProgramConfig, error) {
	c := new(ProgramConfig)
	err := loadYaml(filename, c)

	if err != nil {
		err = fmt.Errorf("Could not load program config file \"%s\": %s", filename, err)
	}
	return c, err
}


text:
package com.badlogic.gdx.maps.objects;

import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.math.Rectangle;

/**
 * @brief Represents rectangle shaped map object
 */
public class RectangleMapObject extends MapObject {

	private Rectangle rectangle;

	/**
	 * @return rectangle shape
	 */
	public Rectangle getRectangle() {
		return rectangle;
	}

	/**
	 * Creates a rectangle object which lower left corner is at (0, 0) with width=1 and height=1
	 */
	public RectangleMapObject() {
		this(0.0f, 0.0f, 1.0f, 1.0f);
	}

	/**
	 * @param x
	 * @param y
	 * @param width
	 * @param height
	 */
	public RectangleMapObject(float x, float y, float width, float height) {
		super();
		rectangle = new Rectangle(x, y, width, height);
	}

}


text:
'use strict';

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

var React = require('react');
var StylePropable = require('./mixins/style-propable');
var TextField = require('./text-field');
var DropDownMenu = require('./drop-down-menu');
var DefaultRawTheme = require('./styles/raw-themes/light-raw-theme');
var ThemeManager = require('./styles/theme-manager');
var ContextPure = require('./mixins/context-pure');

var SelectField = React.createClass({
  displayName: 'SelectField',

  mixins: [StylePropable, ContextPure],

  contextTypes: {
    muiTheme: React.PropTypes.object
  },

  statics: {
    getChildrenClasses: function getChildrenClasses() {
      return [TextField, DropDownMenu];
    }
  },

  propTypes: {
    errorText: React.PropTypes.string,
    floatingLabelText: React.PropTypes.string,
    selectFieldRoot: React.PropTypes.object,
    underlineStyle: React.PropTypes.object,
    labelStyle: React.PropTypes.object,
    errorStyle: React.PropTypes.object,
    hintText: React.PropTypes.string,
    id: React.PropTypes.string,
    multiLine: React.PropTypes.bool,
    onBlur: React.PropTypes.func,
    onChange: React.PropTypes.func,
    onFocus: React.PropTypes.func,
    onKeyDown: React.PropTypes.func,
    onEnterKeyDown: React.PropTypes.func,
    type: React.PropTypes.string,
    rows: React.PropTypes.number,
    inputStyle: React.PropTypes.object,
    iconStyle: React.PropTypes.object,
    floatingLabelStyle: React.PropTypes.object,
    autoWidth: React.PropTypes.bool,
    menuItems: React.PropTypes.array.isRequired,
    menuItemStyle: React.PropTypes.object,
    selectedIndex: React.PropTypes.number,
    style: React.PropTypes.object
  },

  //for passing default theme context to children
  childContextTypes: {
    muiTheme: React.PropTypes.object
  },

  getChildContext: function getChildContext() {
    return {
      muiTheme: this.state.muiTheme
    };
  },

  getInitialState: function getInitialState() {
    return {
      muiTheme: this.context.muiTheme ? this.context.muiTheme : ThemeManager.getMuiTheme(DefaultRawTheme)
    };
  },

  getDefaultProps: function getDefaultProps() {
    return {
      fullWidth: false
    };
  },

  //to update theme inside state whenever a new theme is passed down
  //from the parent / owner using context
  componentWillReceiveProps: function componentWillReceiveProps(nextProps, nextContext) {
    var newMuiTheme = nextContext.muiTheme ? nextContext.muiTheme : this.state.muiTheme;
    this.setState({ muiTheme: newMuiTheme });
  },

  getStyles: function getStyles() {
    var styles = {
      root: {
        height: 46,
        position: 'relative',
        width: '100%',
        top: 16,
        fontSize: 16
      },
      label: {
        paddingLeft: 0,
        top: 4,
        width: '100%'
      },
      icon: {
        top: 20,
        right: 0
      },
      underline: {
        borderTop: 'none'
      },
      input: {},
      error: {}
    };

    if (!this.props.floatingLabelText) {
      if (this.props.hintText) {
        styles.root.top = -5;
        styles.label.top = 1;
        styles.icon.top = 17;
      } else {
        styles.root.top = -8;
      }
    } else {
      styles.error.bottom = -15;
    }

    return styles;
  },

  render: function render() {
    var styles = this.getStyles();
    var _props = this.props;
    var style = _props.style;
    var labelStyle = _props.labelStyle;
    var iconStyle = _props.iconStyle;
    var underlineStyle = _props.underlineStyle;
    var errorStyle = _props.errorStyle;
    var selectFieldRoot = _props.selectFieldRoot;
    var menuItems = _props.menuItems;
    var disabled = _props.disabled;
    var floatingLabelText = _props.floatingLabelText;
    var floatingLabelStyle = _props.floatingLabelStyle;
    var hintText = _props.hintText;
    var fullWidth = _props.fullWidth;
    var errorText = _props.errorText;

    var other = _objectWithoutProperties(_props, ['style', 'labelStyle', 'iconStyle', 'underlineStyle', 'errorStyle', 'selectFieldRoot', 'menuItems', 'disabled', 'floatingLabelText', 'floatingLabelStyle', 'hintText', 'fullWidth', 'errorText']);

    var textFieldProps = {
      style: this.mergeAndPrefix(styles.input, style),
      floatingLabelText: floatingLabelText,
      floatingLabelStyle: floatingLabelStyle,
      hintText: !hintText && !floatingLabelText ? ' ' : hintText,
      fullWidth: fullWidth,
      errorText: errorText,
      errorStyle: this.mergeAndPrefix(styles.error, errorStyle)
    };
    var dropDownMenuProps = {
      menuItems: menuItems,
      disabled: disabled,
      style: this.mergeAndPrefix(styles.root, selectFieldRoot),
      labelStyle: this.mergeAndPrefix(styles.label, labelStyle),
      iconStyle: this.mergeAndPrefix(styles.icon, iconStyle),
      underlineStyle: this.mergeAndPrefix(styles.underline, underlineStyle),
      autoWidth: false
    };

    return React.createElement(
      TextField,
      textFieldProps,
      React.createElement(DropDownMenu, _extends({}, dropDownMenuProps, other))
    );
  }
});

module.exports = SelectField;


text:
package download

import (
	"github.com/pufferpanel/pufferd/v2/programs/operations/ops"
	"github.com/spf13/cast"
)

type OperationFactory struct {
	ops.OperationFactory
}

func (of OperationFactory) Create(op ops.CreateOperation) ops.Operation {
	files := cast.ToStringSlice(op.OperationArgs["files"])
	return &Download{Files: files}
}

func (of OperationFactory) Key() string {
	return "download"
}

var Factory OperationFactory


text:
/***************************************************************************
 * Textures generated from float point arrays
 ***************************************************************************/

#ifndef FLOAT_TEXTURE_H_
#define FLOAT_TEXTURE_H_

#include "objects/textures/texture.h"
#include "util/gvr_log.h"

namespace gvr {
class FloatTexture: public Texture {
public:
    explicit FloatTexture() :
            Texture(new GLTexture(TARGET)) {
    }

    bool update(int width, int height, float* data) {
        glBindTexture(GL_TEXTURE_2D, gl_texture_->id());
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RG32F, width, height, 0,
                GL_RG, GL_FLOAT, data);
        return (glGetError() == 0) ? 1 : 0;
    }

    GLenum getTarget() const {
        return TARGET;
    }

private:
    FloatTexture(const FloatTexture& float_texture);
    FloatTexture(FloatTexture&& float_texture);
    FloatTexture& operator=(const FloatTexture& float_texture);
    FloatTexture& operator=(FloatTexture&& float_texture);

private:
    static const GLenum TARGET = GL_TEXTURE_2D;
};

}
#endif


text:
import copy

def domain_socket_path(port):
    return '/tmp/v0.16/ThriftTest.thrift.%d' % port

def merge_dict(base, update):
    """Update dict concatenating list values"""
    res = copy.deepcopy(base)
    for k, v in list(update.items()):
        if k in list(res.keys()) and isinstance(v, list):
            res[k].extend(v)
        else:
            res[k] = v
    return res


text:
""""
This file is part of python-tdbus. Python-tdbus is free software
available under the terms of the MIT license. See the file "LICENSE" that
was provided together with this source file for the licensing terms.

Copyright (c) 2012 the python-tdbus authors. See the file "AUTHORS" for a
complete list.
"""

import fnmatch
import logging

from tdbus import _tdbus, DBusError

def method(path=None, member=None, interface=None):
    def _decorate(func):
        func.method = True
        func.member = member or func.__name__
        func.path = path
        func.interface = interface
        return func
    return _decorate

def signal_handler(path=None, member=None, interface=None):
    def _decorate(func):
        func.signal_handler = True
        func.member = member or func.__name__
        func.path = path
        func.interface = interface
        return func
    return _decorate

def dbus_object(cls):
    _init_handlers(cls)
    return cls

def _connection(self):
    return self.local.connection

def _message(self):
    return self.local.message

def _set_response(self, format, args):
    """Used by method call handlers to set the response arguments."""
    self.logger.debug("Returning: (%s, %s)", format, args)
    self.local.response = (format, args)

def _init_handlers(cls):
    methods = {}
    signal_handlers = {}

    for name in dir(cls):
        handler = getattr(cls, name)

        if getattr(handler, 'method', False):
            methods[handler.member] = handler
        elif getattr(handler, 'signal_handler', False):
            signal_handlers[handler.member] = handler

    def dispatch(self, connection, message, ignore_path=False):
        """Dispatch a message. Returns True if the message was dispatched."""
        if not hasattr(self, 'local'):
            self.local = connection.Local()
        self.local.connection = connection
        self.local.message = message
        self.local.response = (None, None)
        mtype = message.get_type()
        member = message.get_member()
        if mtype == _tdbus.DBUS_MESSAGE_TYPE_METHOD_CALL:
            if member not in methods:
                return False
            handler = methods[member]
            if handler.interface and handler.interface != message.get_interface():
                return False
            if (not ignore_path and
                handler.path and not fnmatch.fnmatch(message.get_path(), handler.path)):
                return False
            try:
                self.logger.info("calling method for '%s'", member)
                handler(self, message)
            except Exception as e:
                self.logger.error('Uncaught exception in method call: %s', e)
                self.logger.exception(e)
                connection.send_error(message, 'net.tdbus.UncaughtException.' + e.__class__.__name__,
                                           format="s", args=[str(e)])
            else:
                fmt, args = self.local.response
                connection.send_method_return(message, fmt, args)
        elif mtype == _tdbus.DBUS_MESSAGE_TYPE_SIGNAL:
            if member not in signal_handlers:
                return False
            handler = signal_handlers[member]
            if handler.interface and handler.interface != message.get_interface():
                return False
            if handler.path and not fnmatch.fnmatch(message.get_path(), handler.path):
                return False
            try:
                self.logger.info("calling signal handler for '%s'", member)
                handler(self, message)
            except Exception as e:
                self.logger.error('Uncaught exception in signal handler:')
                self.logger.exception(e)
        else:
            return False

    cls.signal_handlers = signal_handlers
    cls.set_response = _set_response
    cls.dispatch = dispatch
    cls.connection = property(_connection)
    cls.message = property(_message)
    cls.logger = logging.getLogger('tdbus')

class DBusHandler(object):
    """Handler for method calls and signals."""

    def __init__(self):
        _init_handlers(type(self))


text:
package chatty.bot.badges.Interfaces;

import java.util.Set;

import chatty.bot.badges.BadgeChecker.PlayerBadges;
import chatty.bot.badges.Interfaces.Utils.BadgeException;
import chatty.bot.badges.Interfaces.Utils.MappedSet;

public interface IPlayerBadges {

	public MappedSet<PlayerBadges> getAllPlayerBadges();
	public PlayerBadges getBadges(String user) throws BadgeException;
	public MappedSet<PlayerBadges> getBadges(Set<String> users);
}


text:
package org.yeastrc.proxl.import_xml_to_db.dto;

import org.yeastrc.proxl.import_xml_to_db.constants.DatabaseAutoIncIdFieldForRecordNotInsertedYetConstants;

/**
 * table protein_sequence_version
 *
 */
public class ProteinSequenceVersionDTO {

	private int id = DatabaseAutoIncIdFieldForRecordNotInsertedYetConstants.DB_AUTO_INC_FIELD_INITIAL_VALUE_FOR_NOT_INSERTED_YET;
	private int proteinSequenceId;
	private int isotopeLabelId;

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public int getProteinSequenceId() {
		return proteinSequenceId;
	}
	public void setProteinSequenceId(int proteinSequenceId) {
		this.proteinSequenceId = proteinSequenceId;
	}
	public int getIsotopeLabelId() {
		return isotopeLabelId;
	}
	public void setIsotopeLabelId(int isotopeLabelId) {
		this.isotopeLabelId = isotopeLabelId;
	}

}


text:
package com.ibm.domino.services;

import java.security.AccessController;
import java.security.PrivilegedAction;

/** Resource handler class
 * @ibm-not-published
 * **/

public class ResourceHandler {
    private static ExtLibResourceHandlerImpl s_impl;
    private static ExtLibResourceHandlerImpl impl(){
        if (s_impl == null) {
            s_impl = AccessController.doPrivileged(new PrivilegedAction<ExtLibResourceHandlerImpl>() {
                public ExtLibResourceHandlerImpl run() {
                    // privileged code goes here:
                    return new ExtLibResourceHandlerImpl(ResourceHandler.class,
                            "messages", //$NON-NLS-1$
                            "services", //$NON-NLS-1$
                            "specialAudience"); //$NON-NLS-1$
                }
            });
        }
        return s_impl;
    }
    public static String getLoggingString(String key) {
        return impl().getLoggingString(key);
    }
    public static String getString(String key) {
        return impl().getString(key);
    }
    public static String getSpecialAudienceString(String key) {
        return impl().getSpecialAudienceString(key);
    }
}


text:
namespace Microsoft.PythonTools.Hpc {
    enum  ScheduleProcessPer {
        Core,
        Socket,
        Node
    }
}


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

namespace Hokanson.JottoHelper
{
	public class GuessInfo
	{
		public GuessInfo(string word, int score)
		{
			_word = word;
			_score = score;
		}

		private readonly string _word;
		private readonly int _score;

		public Tuple<string, int> GetRemaining(string knownIn, string knownOut)
		{
			char[] remainingChars = _word.ToArray();
			int remainingScore = _score;
			foreach (var pos in HandleKnown(knownIn, true))
			{
				remainingChars[pos] = '-';
				remainingScore--;
			}
			foreach (var pos in HandleKnown(knownOut))
			{
				remainingChars[pos] = '-';
			}
			return new Tuple<string, int>(new string(remainingChars.Where(c => c != '-').ToArray()), remainingScore);
		}

		private IEnumerable<int> HandleKnown(string known, bool forIn = false)
		{
			char[] knownChars = known.ToArray();
			var knownPositions = new HashSet<int>();
			char[] wordChars = _word.ToArray();
			for (int i = 0; i < 5; i++)
			{
				for (int j = 0; j < knownChars.Length; j++)
				{
					if (wordChars[i] == knownChars[j] && !knownPositions.Contains(i))
					{
						knownPositions.Add(i);
						if (forIn) knownChars[j] = '-';    // to prevent double-processing
					}
				}
			}
			return knownPositions;
		}
	}

	public class JottoGameHelper
	{
		private readonly Dictionary<string, int> _guesses = new Dictionary<string, int>();
		private readonly Dictionary<char, int> _knownIn = new Dictionary<char, int>();
		private readonly List<char> _knownOut = new List<char>();
		private Dictionary<string, int> _clues;

        public IReadOnlyDictionary<char, int> KnownIn => _knownIn;
        public IReadOnlyCollection<char> KnownOut => _knownOut;
        public IReadOnlyDictionary<string, int> Clues => _clues;

        public void HandleGuess(string word, int score)
		{
			if (string.IsNullOrEmpty(word) || word.Length != 5) throw new ArgumentException("word must be five letters long");
			// normalize before proceeding
			word = word.ToLower();
			if (word.ToArray().Any(c => !char.IsLetter(c))) throw new ArgumentException("word must contain only letters");
			if (score < 0 || score > 5) throw new ArgumentException("score must be 0-5");
			if (_guesses.ContainsKey(word)) throw new ArgumentException("that word has already been guessed");

			_guesses[word] = score;

			SetClues();
		}

		public void AddKnownIn(char c)
		{
			if (_knownOut.Contains(c)) throw new ArgumentException("already exists in KnownOut--cannot add to KnownIn");

			if (_knownIn.ContainsKey(c)) _knownIn[c]++;
			else _knownIn[c] = 1;

			SetClues();
		}

		public void AddKnownOut(char c)
		{
			if (_knownIn.ContainsKey(c)) throw new ArgumentException("already exists in KnownIn--cannot add to KnownOut");

			if (!_knownOut.Contains(c)) _knownOut.Add(c);

			SetClues();
		}

		public void RemoveKnownIn(char c)
		{
			if (_knownIn.ContainsKey(c))
			{
				if (_knownIn[c] > 1) _knownIn[c]--;
				else _knownIn.Remove(c);
			}

			SetClues();
		}

		public void RemoveKnownOut(char c)
		{
			if (_knownOut.Contains(c)) _knownOut.Remove(c);

			SetClues();
		}

		public void Reset()
		{
			_knownIn.Clear();
			_knownOut.Clear();
			SetClues();
			SetClues();	// ensure clues take into account KnownIn/KnownOut--hack until I can figure out how to do this within one call to SetClues
		}

		public override string ToString()
		{
			var sb = new StringBuilder();

			IEnumerable<char> unknownCharList = "abcdefghijklmnopqrstuvwxyz".Except(KnownInStr.ToArray()).Except(_knownOut);
			sb.Append($"Known in:  {new string(KnownInStr.ToArray().OrderBy(c => c).ToArray())}\r\n");
			sb.Append($"Known out: {new string(_knownOut.OrderBy(c => c).ToArray())}\r\n");
			sb.Append($"Unknown:   {new string(unknownCharList.ToArray())}\r\n");
			sb.Append("Clues:\r\n");
			foreach (var clue in Clues.Keys)
			{
				sb.Append($"\t{clue}: {Clues[clue]}\r\n");
			}

			return sb.ToString();
		}

		private void SetClues()
		{
			bool done;
			Dictionary<string, int> clues;
			do
			{
				done = true;
				clues = new Dictionary<string, int>();

				foreach (var pair in _guesses)
				{
					var info = new GuessInfo(pair.Key, pair.Value);
					Tuple<string, int> remaining = info.GetRemaining(KnownInStr, KnownOutStr);

					if (remaining.Item2 == 0 && remaining.Item1.Length > 0)
					{
						if (remaining.Item1.Length == 1 && _knownIn.ContainsKey(remaining.Item1[0]))
						{
							// Hmmm....this seems like a special case (see TestGame9), but I'm not sure what
							// the general rule is.

							// don't need to do anything with clues or known in/out
						}
						else
						{
                            done &= !AddRemainingToKnownOut(remaining.Item1);
						}
					}
					else if (remaining.Item2 > 0 && remaining.Item1.Length == remaining.Item2)
					{
						AddRemainingToKnownIn(remaining.Item1);
						done = false;
					}
                    else if (remaining.Item2 > 0 && AllTheSameLetter(remaining.Item1))
                    {
                        AddRemainingToKnownIn(new string(remaining.Item1[0], remaining.Item2));
                        done = false;
                    }
					else if (remaining.Item1.Length > 0)
					{
						var clue = new string(remaining.Item1.ToArray().OrderBy(c => c).ToArray());
						if (clues.ContainsKey(clue))
						{
							if (clues[clue] != remaining.Item2)
							{
								//throw new Exception("programming error: somehow wound up with same clue but different score");
							}
						}
						else
						{
							clues[clue] = remaining.Item2;
						}
					}
				}

			} while (!done);
			_clues = clues;
		}

        private bool AllTheSameLetter(string s)
        {
            return s.GroupBy(c => c).Count() == 1;
        }

        private void AddRemainingToKnownIn(string s)
		{
			foreach (var c in s)
			{
				if (_knownIn.ContainsKey(c)) _knownIn[c]++;
				else _knownIn[c] = 1;
			}
		}

		private bool AddRemainingToKnownOut(string s)
		{
			bool changed = false;
			// note: it may be that there were duplicate letters in the guess that aren't in the jotto word,
			// so we have to make sure we don't remove it from knownIn if it's already there
			foreach (var c in s)
			{
				if (!_knownIn.ContainsKey(c) && !_knownOut.Contains(c))
				{
					_knownOut.Add(c);
					changed = true;
				}
			}
			return changed;
		}

		private string KnownInStr
		{
			get
			{
				var builder = new StringBuilder();

				foreach (var pair in _knownIn)
				{
					for (int i = 0; i < pair.Value; i++) builder.Append(pair.Key);
				}

				return builder.ToString();
			}
		}

        private string KnownOutStr => new string(_knownOut.ToArray());
    }
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json.Serialization;

namespace MaxMind.MinFraud.Request
{
    /// <summary>
    /// The email information for the transaction being sent to the
    /// web service.
    /// </summary>
    public sealed class Email
    {
        private static readonly IdnMapping _idn = new();
        private static readonly IReadOnlyDictionary<string, string> _typoDomains = new Dictionary<string, string>
        {
            // gmail.com
            {"35gmai.com", "gmail.com"},
            {"636gmail.com", "gmail.com"},
            {"gamil.com", "gmail.com"},
            {"gmail.comu", "gmail.com"},
            {"gmial.com", "gmail.com"},
            {"gmil.com", "gmail.com"},
            {"yahoogmail.com", "gmail.com"},
            // outlook.com
            {"putlook.com", "outlook.com"},
        };

        private string? _address;
        private string? _domain;

        /// <summary>
        /// Constructor.
        /// </summary>
        /// <param name="address">The user's email address. This will be
        /// converted into an MD5 before being sent to the web service.
        /// </param>
        /// <param name="domain">The domain of the email address used in the
        /// transaction. If <c>address</c> is passed to the constructor
        /// and <c>domain</c> is not, the domain will be automatically
        /// set from the address.</param>
        /// <param name="hashAddress">By default, the <c>address</c> will
        /// be sent in plain text. If <c>hashAddress</c> is set to true,
        /// the address will instead be sent as an MD5 hash.</param>
        public Email(
            string? address = null,
            string? domain = null,
            bool hashAddress = false
        )
        {
            Address = address;
            Domain = domain;
            HashAddress = hashAddress;
        }

        /// <summary>
        /// The MD5 generated from the email address.
        /// </summary>
        [JsonIgnore]
        public string? AddressMD5
        {
            get
            {
                if (Address == null)
                    return null;

                using var md5Generator = MD5.Create();
                var bytes = Encoding.UTF8.GetBytes(CleanAddress(Address));
                var md5 = md5Generator.ComputeHash(bytes);
                return BitConverter.ToString(md5)
                    .Replace("-", string.Empty)
                    .ToLower();
            }
        }

        /// <summary>
        /// The email address used in the transaction.
        /// </summary>
        [JsonIgnore]
        public string? Address
        {
            get => _address;
            init
            {
                if (value == null)
                {
                    return;
                }
                var parts = value.Split('@');
                if (parts.Length < 2)
                {
                    throw new ArgumentException($"The email address {value} is invalid");
                }

                if (_domain == null)
                {
                    _domain = parts.Last();
                }
                _address = value;
            }
        }

        /// <summary>
        ///     The address value that will be sent in the request.
        /// </summary>
        [JsonPropertyName("address")]
        public string? RequestAddress => HashAddress ? AddressMD5 : Address;

        /// <summary>
        /// The domain of the email address.
        /// </summary>
        [JsonPropertyName("domain")]
        public string? Domain
        {
            get => _domain;
            init
            {
                if (value == null)
                {
                    return;
                }
                if (Uri.CheckHostName(value) == UriHostNameType.Unknown)
                {
                    throw new ArgumentException($"The email domain {value} is not valid.");
                }
                _domain = value;
            }
        }

        /// <summary>
        /// By default, the <c>address</c> will  be sent in plain text. If
        /// this is set to true, the address will instead be sent as an MD5
        /// hash.
        /// </summary>
        [JsonIgnore]
        public bool HashAddress { get; init; } = false;

        /// <summary>
        /// Returns a string that represents the current object.
        /// </summary>
        /// <returns>A string that represents the current object.</returns>
        public override string ToString()
        {
            return $"Address: {Address}, Domain: {Domain}";
        }

        private static string CleanAddress(string address)
        {
            address = address.Trim().ToLower();

            var domainIndex = address.LastIndexOf('@');
            if (domainIndex == -1 || domainIndex + 1 == address.Length)
            {
                return address;
            }

            var localPart = address.Substring(0, domainIndex);
            var domain = address.Substring(domainIndex + 1);

            domain = CleanDomain(domain);

            var divider = domain == "yahoo.com" ? '-' : '+';

            var dividerIdx = localPart.IndexOf(divider);
            if (dividerIdx > 0)
            {
                localPart = localPart.Substring(0, dividerIdx);
            }

            return $"{localPart}@{domain}";
        }

        private static string CleanDomain(string domain)
        {
            domain = domain.Trim();

            if (domain.EndsWith("."))
            {
                domain = domain.Substring(0, domain.Length - 1);
            }

            domain = _idn.GetAscii(domain);

            if (_typoDomains.ContainsKey(domain))
            {
                domain = _typoDomains[domain];
            }

            return domain;
        }
    }
}


text: apt_package node['unifi']['package']


text:
import React from 'react-native';
import AppText from './AppText';
import timeUtils from '../lib/time-utils';

const msPerSec = 1000;
const msPerMin = msPerSec * 60;
const msPerHour = msPerMin * 60;

export default class Time extends React.Component {
	componentWillMount() {
		const now = Date.now();

		this.setState({
			now
		});

		this._setTimer(now);
	}

	componentWillUnmount() {
		if (this._timer) {
			clearTimeout(this._timer);
		}
	}

	setNativeProps(nativeProps) {
		this._root.setNativeProps(nativeProps);
	}

	_setTimer = time => {
		const diff = time - this.props.time;

		let interval;

		if (diff < msPerMin) {
			interval = msPerSec * 10;
		} else if (diff < msPerHour) {
			interval = msPerMin;
		}

		if (interval) {
			this._timer = setTimeout(() => {
				const now = Date.now();

				this.setState({
					now
				});

				this._setTimer(now);
			}, interval);
		}
	};

	render() {
		const {
			type,
			time
		} = this.props;

		return (
			<AppText ref={c => this._root = c} {...this.props}>
				{type === 'short' ? timeUtils.short(time, this.state.now) : timeUtils.long(time, this.state.now)}
			</AppText>
		);
	}
}

Time.propTypes = {
	type: React.PropTypes.oneOf([ 'short', 'long' ]).isRequired,
	time: React.PropTypes.number.isRequired
};