text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Threading;
using System.Threading.Tasks;
using Azure.Messaging.EventHubs.Producer;
using Azure.Messaging.EventHubs.Tests;
using Moq;
using NUnit.Framework;

namespace Azure.Messaging.EventHubs.Experimental.Tests
{
    /// <summary>
    ///   The suite of tests for the <see cref="IdempotentProducer" />
    ///   class.
    /// </summary>
    ///
    [TestFixture]
    public class IdempotentProducerTests
    {
        /// <summary>
        ///   Verifies functionality of the <see cref="IdempotentProducer.GetPartitionPublishingPropertiesAsync" />
        ///   method.
        /// </summary>
        ///
        [Test]
        public async Task GetPartitionPublishingPropertiesAsyncReturnsProperties()
        {
            // Disable idempotent partitions to avoid a live service call.  This will
            // still allow the pass-through invocation to be validated.

            var producer = new IdempotentProducer(Mock.Of<EventHubConnection>(), new IdempotentProducerOptions
            {
                EnableIdempotentPartitions = false
            });

            using var cancellationSource = new CancellationTokenSource();
            cancellationSource.CancelAfter(EventHubsTestEnvironment.Instance.TestExecutionTimeLimit);

            var readProperties = await producer.GetPartitionPublishingPropertiesAsync("0", cancellationSource.Token);
            Assert.That(readProperties, Is.Not.Null, "The read properties should have been created.");
        }
    }
}


text:
import os
import numpy as np
from astropy.table import Table
from scipy.io import readsav

DATA_PATH = "/data/gaia-eso/arc/rave-data-files/"
DATA_PATH = "/Users/arc/research/rave/"

def get_rave_kordopatis_dr4():
    return Table.read(os.path.join(DATA_PATH, "RAVE-DR4.fits"))

def get_kordopatis_comparisons():
    data = readsav(os.path.join(DATA_PATH, "RAVE_DR5_calibration_data.save"))

    return Table(data={
        "TEFF": data["calibration_data"]["TEFF"][0],
        "LOGG": data["calibration_data"]["LOGG"][0],
        "FEH": data["calibration_data"]["FEH"][0],
        "REF": data["calibration_data"]["REF"][0],
        "Name": [each.strip() for each in data["calibration_data"]["DR5_OBS_ID"][0]]
        })

def get_cannon_dr1(filename=None):

    filename = filename or os.path.join(DATA_PATH, "RAVE-on-v1.0.fits")

    rave_cannon_dr1 = Table.read(os.path.join(DATA_PATH, filename))

    # Just so I don't have to rewrite a bunch of code.
    rave_cannon_dr1['Name'] = rave_cannon_dr1["RAVE_OBS_ID"]
    rave_cannon_dr1['snr'] = rave_cannon_dr1["SNR"]
    rave_cannon_dr1['r_chi_sq'] = rave_cannon_dr1["R_CHI_SQ"]

    return rave_cannon_dr1

def get_ges_idr4():

    ges_idr4 = Table.read(os.path.join(DATA_PATH, "literature-ges-idr4-xm.fits"))
    ges_idr4["Name"] = [each.strip() for each in ges_idr4["Name"]]
    return ges_idr4

def get_literature_pastel():
    return Table.read(os.path.join(DATA_PATH, "literature-pastel-database-xm.fits"))

def get_literature_bensby():
    data = Table.read(os.path.join(DATA_PATH, "literature-bensby-2014.fits"))
    data["Name"] = [each.strip() for each in data["Name"]]
    return data

def get_literature_valenti_2005():
    data = Table.read(os.path.join(DATA_PATH, "literature-valenti-2005.fits"))
    data["Name"] = [each.strip() for each in data["Name"]]
    return data

def get_literature_reddy_2003():
    data = Table.read(os.path.join(DATA_PATH, "literature-reddy-2003.fits"))
    data["Name"] = [each.strip() for each in data["Name"]]
    return data

def get_literature_reddy_2006():
    data = Table.read(os.path.join(DATA_PATH, "literature-reddy-2006.fits"))
    data["Name"] = [each.strip() for each in data["Name"]]
    return data

def get_training_sets():

    ms_training_set = Table.read(os.path.join(DATA_PATH, "rave-ms-labelled-set.fits"))
    ms_training_set["TEFF"] = ms_training_set["EPIC_TEFF"]
    ms_training_set["LOGG"] = ms_training_set["EPIC_LOGG"]
    ms_training_set["FE_H"] = ms_training_set["EPIC_FEH"]

    giant_training_set = Table.read(os.path.join(DATA_PATH, "rave-giant-labelled-set.fits"))

    joint_training_set = Table.read(os.path.join(DATA_PATH, "rave-joint-labelled-set.fits"))

    return (ms_training_set, giant_training_set, joint_training_set)

redpajama_set_name: RedPajamaGithub


text:
initdb () {
    sleep 80s;
    POD_NAME=$(kubectl get po | grep mariadb | awk '{ print $1 }');
    kubectl exec -i $POD_NAME -- mysql -u root -ptest -e 'CREATE DATABASE entityone_test';
    kubectl exec -i $POD_NAME -- mysql -u root -ptest -e 'CREATE DATABASE playwithsql';
}

removeService () {
    kubectl delete -f ./infra/databases/kubernetes/mariadb/kube-solo.yml
}

runService () {
    removeService;
    kubectl create -f ./infra/databases/kubernetes/mariadb/kube-solo.yml;
    while [ $(kubectl get po | grep Running | grep mariadb | awk '{ print $3 }' | wc -l) -lt 1 ] ;do
        sleep 1s;
    done;
    initdb;
}

runService;


text:
package org.commonjava.indy.promote.model;

import java.util.Collections;
import java.util.Map;

import static org.commonjava.indy.promote.model.CallbackTarget.CallbackMethod.POST;

/**
 * Created by ruhan on 12/6/18.
 */
public class CallbackTarget
{
    public enum CallbackMethod
    {
        POST, PUT;
    }

    private String url;

    private CallbackMethod method;

    private Map<String, String> headers; // e.g., put( "Authorization", "Bearer ..." )

    public CallbackTarget()
    {
    }

    public CallbackTarget( String url, CallbackMethod method, Map<String, String> headers )
    {
        this.url = url;
        this.method = method;
        this.headers = headers;
    }

    public CallbackTarget( String url, Map<String, String> headers )
    {
        this( url, POST, headers );
    }

    public CallbackTarget( String url )
    {
        this( url, POST, Collections.emptyMap() );
    }

    public void setUrl( String url )
    {
        this.url = url;
    }

    public void setMethod( CallbackMethod method )
    {
        this.method = method;
    }

    public void setHeaders( Map<String, String> headers )
    {
        this.headers = headers;
    }

    public String getUrl()
    {
        return url;
    }

    public CallbackMethod getMethod()
    {
        return method;
    }

    public Map<String, String> getHeaders()
    {
        return headers;
    }

    @Override
    public String toString()
    {
        return "CallbackTarget{" + "url='" + url + '\'' + ", method=" + method + '}';
    }
}


text:
'use strict';

/**
 * Linux specific update configuration.
 *
 */
class LinuxProperties {
  /**
   * Create a LinuxProperties.
   * @member {string} [includedPackageClassifications] Update classifications
   * included in the software update configuration. Possible values include:
   * 'Unclassified', 'Critical', 'Security', 'Other'
   * @member {array} [excludedPackageNameMasks] packages excluded from the
   * software update configuration.
   * @member {array} [includedPackageNameMasks] packages included from the
   * software update configuration.
   * @member {string} [rebootSetting] Reboot setting for the software update
   * configuration.
   */
  constructor() {
  }

  /**
   * Defines the metadata of LinuxProperties
   *
   * @returns {object} metadata of LinuxProperties
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'LinuxProperties',
      type: {
        name: 'Composite',
        className: 'LinuxProperties',
        modelProperties: {
          includedPackageClassifications: {
            required: false,
            serializedName: 'includedPackageClassifications',
            type: {
              name: 'String'
            }
          },
          excludedPackageNameMasks: {
            required: false,
            serializedName: 'excludedPackageNameMasks',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          includedPackageNameMasks: {
            required: false,
            serializedName: 'includedPackageNameMasks',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'StringElementType',
                  type: {
                    name: 'String'
                  }
              }
            }
          },
          rebootSetting: {
            required: false,
            serializedName: 'rebootSetting',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = LinuxProperties;


text:
/* DriveComboBoxTest.cs --
 * Ars Magna project, http://arsmagna.ru
 * -------------------------------------------------------
 * Status: poor
 */

#region Using directives

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

using AM;
using AM.Windows.Forms;

using CodeJam;

using IrbisUI;

using JetBrains.Annotations;

using ManagedIrbis;

using MoonSharp.Interpreter;

using Newtonsoft.Json;

#endregion

namespace UITests
{
    public sealed class DriveComboBoxTest
        : IUITest
    {
        #region IUITest members

        public void Run
            (
                IWin32Window ownerWindow
            )
        {
            using (Form form = new Form())
            {
                form.Size = new Size(800, 600);

                DriveComboBox comboBox = new DriveComboBox()
                {
                    Location = new Point(10, 10)
                };
                form.Controls.Add(comboBox);

                form.ShowDialog(ownerWindow);
            }
        }

        #endregion
    }
}


text:
package com.wso2.gsoc.vihanga.studentlan;

/**
 * Created by vihanga on 3/9/17.
 */

import com.intellij.openapi.fileTypes.LanguageFileType;
import org.jetbrains.annotations.*;

import javax.swing.*;

public class StudentFileType extends LanguageFileType {
    public static final StudentFileType INSTANCE = new StudentFileType();

    private StudentFileType() {
        super(StudentLanguage.INSTANCE);
    }

    @NotNull
    @Override
    public String getName() {
        return "Student file";
    }

    @NotNull
    @Override
    public String getDescription() {
        return "Student language file";
    }

    @NotNull
    @Override
    public String getDefaultExtension() {
        return "Student";
    }

    @Nullable
    @Override
    public Icon getIcon() {
        return StudentIcons.FILE;
    }
}


text:
namespace Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition
{
    /// <summary>
    /// The stage of the definition which allows to specify country or execute the query.
    /// </summary>
    public interface IWithExecuteAndCountry  :
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecute
    {

        /// <param name="country">The country for available providers list.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecuteAndState WithCountry(string country);
    }

    /// <summary>
    /// The stage of the definition which allows to specify state or execute the query.
    /// </summary>
    public interface IWithExecuteAndState  :
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecute
    {

        /// <param name="state">The state for available providers list.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecuteAndCity WithState(string state);
    }

    /// <summary>
    /// The first stage of available providers parameters definition.
    /// </summary>
    public interface IWithAzureLocations
    {

        /// <summary>
        /// Sets Azure region name. Note: this method has additive effect.
        /// </summary>
        /// <param name="azureLocation">Region name.</param>
        /// <return>The AvailableProviders object itself.</return>
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecuteAndCountry WithAzureLocation(string azureLocation);

        /// <summary>
        /// Set the list of Azure regions. Note: this will overwrite locations if already set.
        /// </summary>
        /// <param name="azureLocations">Locations list.</param>
        /// <return>The AvailableProviders object itself.</return>
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecute WithAzureLocations(params string[] azureLocations);
    }

    /// <summary>
    /// The stage of the definition which contains all the minimum required inputs for execution, but also allows
    /// for any other optional settings to be specified.
    /// </summary>
    public interface IWithExecute  :
        Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions.IExecutable<Microsoft.Azure.Management.Network.Fluent.IAvailableProviders>,
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithAzureLocations
    {

    }

    /// <summary>
    /// The entirety of available providers parameters definition.
    /// </summary>
    public interface IDefinition  :
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecuteAndCountry,
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecuteAndState,
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecuteAndCity
    {

    }

    /// <summary>
    /// The stage of the definition which allows to specify city or execute the query.
    /// </summary>
    public interface IWithExecuteAndCity  :
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecute
    {

        /// <param name="city">The city or town for available providers list.</param>
        /// <return>The next stage of the definition.</return>
        Microsoft.Azure.Management.Network.Fluent.AvailableProviders.Definition.IWithExecute WithCity(string city);
    }
}


text:
package ondrej.mejzlik.suntrail.activities;

import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import ondrej.mejzlik.suntrail.R;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withParent;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class QrScannerTest {

    @Rule
    public ActivityTestRule<MainMenuActivity> mActivityTestRule = new ActivityTestRule<>(MainMenuActivity.class);

    private static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }

    @Test
    public void qrScannerTest() {
        ViewInteraction button = onView(
                allOf(withId(R.id.main_menu_button_scan), withText("Scan"),
                        withParent(allOf(withId(R.id.linearLayout3),
                                withParent(withId(R.id.main_menu_activity_relative_layout)))),
                        isDisplayed()));
        button.perform(click());

        ViewInteraction view = onView(
                allOf(childAtPosition(
                        childAtPosition(
                                withId(R.id.scanner_fragment_container),
                                0),
                        0),
                        isDisplayed()));
        view.check(matches(isDisplayed()));

    }
}


text:
using MasterDevs.ChromeDevTools;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;

namespace MasterDevs.ChromeDevTools.Protocol.Chrome.Database
{
	/// <summary>
	/// Disables database tracking, prevents database events from being sent to the client.
	/// </summary>
	[Command(ProtocolName.Database.Disable)]
	[SupportedBy("Chrome")]
	public class DisableCommand: ICommand<DisableCommandResponse>
	{
	}
}


text:
package com.microsoft.azure.management.recoveryservices.siterecovery.v2018_01_10;

import org.joda.time.DateTime;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;

/**
 * InMageAzureV2 provider specific settings.
 */
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "instanceType")
@JsonTypeName("InMageAzureV2")
public class InMageAzureV2ReplicationDetails extends ReplicationProviderSpecificSettings {
    /**
     * The infrastructure VM Id.
     */
    @JsonProperty(value = "infrastructureVmId")
    private String infrastructureVmId;

    /**
     * The vCenter infrastructure Id.
     */
    @JsonProperty(value = "vCenterInfrastructureId")
    private String vCenterInfrastructureId;

    /**
     * The protection stage.
     */
    @JsonProperty(value = "protectionStage")
    private String protectionStage;

    /**
     * The virtual machine Id.
     */
    @JsonProperty(value = "vmId")
    private String vmId;

    /**
     * The protection state for the vm.
     */
    @JsonProperty(value = "vmProtectionState")
    private String vmProtectionState;

    /**
     * The protection state description for the vm.
     */
    @JsonProperty(value = "vmProtectionStateDescription")
    private String vmProtectionStateDescription;

    /**
     * The resync progress percentage.
     */
    @JsonProperty(value = "resyncProgressPercentage")
    private Integer resyncProgressPercentage;

    /**
     * The RPO in seconds.
     */
    @JsonProperty(value = "rpoInSeconds")
    private Long rpoInSeconds;

    /**
     * The compressed data change rate in MB.
     */
    @JsonProperty(value = "compressedDataRateInMB")
    private Double compressedDataRateInMB;

    /**
     * The uncompressed data change rate in MB.
     */
    @JsonProperty(value = "uncompressedDataRateInMB")
    private Double uncompressedDataRateInMB;

    /**
     * The source IP address.
     */
    @JsonProperty(value = "ipAddress")
    private String ipAddress;

    /**
     * The agent version.
     */
    @JsonProperty(value = "agentVersion")
    private String agentVersion;

    /**
     * Agent expiry date.
     */
    @JsonProperty(value = "agentExpiryDate")
    private DateTime agentExpiryDate;

    /**
     * A value indicating whether installed agent needs to be updated.
     */
    @JsonProperty(value = "isAgentUpdateRequired")
    private String isAgentUpdateRequired;

    /**
     * A value indicating whether the source server requires a restart after
     * update.
     */
    @JsonProperty(value = "isRebootAfterUpdateRequired")
    private String isRebootAfterUpdateRequired;

    /**
     * The last heartbeat received from the source server.
     */
    @JsonProperty(value = "lastHeartbeat")
    private DateTime lastHeartbeat;

    /**
     * The process server Id.
     */
    @JsonProperty(value = "processServerId")
    private String processServerId;

    /**
     * The multi vm group Id.
     */
    @JsonProperty(value = "multiVmGroupId")
    private String multiVmGroupId;

    /**
     * The multi vm group name.
     */
    @JsonProperty(value = "multiVmGroupName")
    private String multiVmGroupName;

    /**
     * A value indicating whether multi vm sync is enabled or disabled.
     */
    @JsonProperty(value = "multiVmSyncStatus")
    private String multiVmSyncStatus;

    /**
     * The list of protected disks.
     */
    @JsonProperty(value = "protectedDisks")
    private List<InMageAzureV2ProtectedDiskDetails> protectedDisks;

    /**
     * A value indicating whether any disk is resized for this VM.
     */
    @JsonProperty(value = "diskResized")
    private String diskResized;

    /**
     * The master target Id.
     */
    @JsonProperty(value = "masterTargetId")
    private String masterTargetId;

    /**
     * The CPU count of the VM on the primary side.
     */
    @JsonProperty(value = "sourceVmCpuCount")
    private Integer sourceVmCpuCount;

    /**
     * The RAM size of the VM on the primary side.
     */
    @JsonProperty(value = "sourceVmRamSizeInMB")
    private Integer sourceVmRamSizeInMB;

    /**
     * The type of the OS on the VM.
     */
    @JsonProperty(value = "osType")
    private String osType;

    /**
     * The OS disk VHD name.
     */
    @JsonProperty(value = "vhdName")
    private String vhdName;

    /**
     * The id of the disk containing the OS.
     */
    @JsonProperty(value = "osDiskId")
    private String osDiskId;

    /**
     * Azure VM Disk details.
     */
    @JsonProperty(value = "azureVMDiskDetails")
    private List<AzureVmDiskDetails> azureVMDiskDetails;

    /**
     * Recovery Azure given name.
     */
    @JsonProperty(value = "recoveryAzureVMName")
    private String recoveryAzureVMName;

    /**
     * The Recovery Azure VM size.
     */
    @JsonProperty(value = "recoveryAzureVMSize")
    private String recoveryAzureVMSize;

    /**
     * The recovery Azure storage account.
     */
    @JsonProperty(value = "recoveryAzureStorageAccount")
    private String recoveryAzureStorageAccount;

    /**
     * The ARM id of the log storage account used for replication. This will be
     * set to null if no log storage account was provided during enable
     * protection.
     */
    @JsonProperty(value = "recoveryAzureLogStorageAccountId")
    private String recoveryAzureLogStorageAccountId;

    /**
     * The PE Network details.
     */
    @JsonProperty(value = "vmNics")
    private List<VMNicDetails> vmNics;

    /**
     * The selected recovery azure network Id.
     */
    @JsonProperty(value = "selectedRecoveryAzureNetworkId")
    private String selectedRecoveryAzureNetworkId;

    /**
     * The selected source nic Id which will be used as the primary nic during
     * failover.
     */
    @JsonProperty(value = "selectedSourceNicId")
    private String selectedSourceNicId;

    /**
     * A value indicating the discovery type of the machine. Value can be
     * vCenter or physical.
     */
    @JsonProperty(value = "discoveryType")
    private String discoveryType;

    /**
     * The selected option to enable RDP\SSH on target vm after failover.
     * String value of {SrsDataContract.EnableRDPOnTargetOption} enum.
     */
    @JsonProperty(value = "enableRdpOnTargetOption")
    private String enableRdpOnTargetOption;

    /**
     * The data stores of the on-premise machine. Value can be list of strings
     * that contain data store names.
     */
    @JsonProperty(value = "datastores")
    private List<String> datastores;

    /**
     * The ARM Id of the target Azure VM. This value will be null until the VM
     * is failed over. Only after failure it will be populated with the ARM Id
     * of the Azure VM.
     */
    @JsonProperty(value = "targetVmId")
    private String targetVmId;

    /**
     * The target resource group Id.
     */
    @JsonProperty(value = "recoveryAzureResourceGroupId")
    private String recoveryAzureResourceGroupId;

    /**
     * The recovery availability set Id.
     */
    @JsonProperty(value = "recoveryAvailabilitySetId")
    private String recoveryAvailabilitySetId;

    /**
     * A value indicating whether managed disks should be used during failover.
     */
    @JsonProperty(value = "useManagedDisks")
    private String useManagedDisks;

    /**
     * License Type of the VM to be used.
     */
    @JsonProperty(value = "licenseType")
    private String licenseType;

    /**
     * The validation errors of the on-premise machine Value can be list of
     * validation errors.
     */
    @JsonProperty(value = "validationErrors")
    private List<HealthError> validationErrors;

    /**
     * The last RPO calculated time.
     */
    @JsonProperty(value = "lastRpoCalculatedTime")
    private DateTime lastRpoCalculatedTime;

    /**
     * The last update time received from on-prem components.
     */
    @JsonProperty(value = "lastUpdateReceivedTime")
    private DateTime lastUpdateReceivedTime;

    /**
     * The replica id of the protected item.
     */
    @JsonProperty(value = "replicaId")
    private String replicaId;

    /**
     * The OS Version of the protected item.
     */
    @JsonProperty(value = "osVersion")
    private String osVersion;

    /**
     * Get the infrastructure VM Id.
     *
     * @return the infrastructureVmId value
     */
    public String infrastructureVmId() {
        return this.infrastructureVmId;
    }

    /**
     * Set the infrastructure VM Id.
     *
     * @param infrastructureVmId the infrastructureVmId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withInfrastructureVmId(String infrastructureVmId) {
        this.infrastructureVmId = infrastructureVmId;
        return this;
    }

    /**
     * Get the vCenter infrastructure Id.
     *
     * @return the vCenterInfrastructureId value
     */
    public String vCenterInfrastructureId() {
        return this.vCenterInfrastructureId;
    }

    /**
     * Set the vCenter infrastructure Id.
     *
     * @param vCenterInfrastructureId the vCenterInfrastructureId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withVCenterInfrastructureId(String vCenterInfrastructureId) {
        this.vCenterInfrastructureId = vCenterInfrastructureId;
        return this;
    }

    /**
     * Get the protection stage.
     *
     * @return the protectionStage value
     */
    public String protectionStage() {
        return this.protectionStage;
    }

    /**
     * Set the protection stage.
     *
     * @param protectionStage the protectionStage value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withProtectionStage(String protectionStage) {
        this.protectionStage = protectionStage;
        return this;
    }

    /**
     * Get the virtual machine Id.
     *
     * @return the vmId value
     */
    public String vmId() {
        return this.vmId;
    }

    /**
     * Set the virtual machine Id.
     *
     * @param vmId the vmId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withVmId(String vmId) {
        this.vmId = vmId;
        return this;
    }

    /**
     * Get the protection state for the vm.
     *
     * @return the vmProtectionState value
     */
    public String vmProtectionState() {
        return this.vmProtectionState;
    }

    /**
     * Set the protection state for the vm.
     *
     * @param vmProtectionState the vmProtectionState value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withVmProtectionState(String vmProtectionState) {
        this.vmProtectionState = vmProtectionState;
        return this;
    }

    /**
     * Get the protection state description for the vm.
     *
     * @return the vmProtectionStateDescription value
     */
    public String vmProtectionStateDescription() {
        return this.vmProtectionStateDescription;
    }

    /**
     * Set the protection state description for the vm.
     *
     * @param vmProtectionStateDescription the vmProtectionStateDescription value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withVmProtectionStateDescription(String vmProtectionStateDescription) {
        this.vmProtectionStateDescription = vmProtectionStateDescription;
        return this;
    }

    /**
     * Get the resync progress percentage.
     *
     * @return the resyncProgressPercentage value
     */
    public Integer resyncProgressPercentage() {
        return this.resyncProgressPercentage;
    }

    /**
     * Set the resync progress percentage.
     *
     * @param resyncProgressPercentage the resyncProgressPercentage value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withResyncProgressPercentage(Integer resyncProgressPercentage) {
        this.resyncProgressPercentage = resyncProgressPercentage;
        return this;
    }

    /**
     * Get the RPO in seconds.
     *
     * @return the rpoInSeconds value
     */
    public Long rpoInSeconds() {
        return this.rpoInSeconds;
    }

    /**
     * Set the RPO in seconds.
     *
     * @param rpoInSeconds the rpoInSeconds value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withRpoInSeconds(Long rpoInSeconds) {
        this.rpoInSeconds = rpoInSeconds;
        return this;
    }

    /**
     * Get the compressed data change rate in MB.
     *
     * @return the compressedDataRateInMB value
     */
    public Double compressedDataRateInMB() {
        return this.compressedDataRateInMB;
    }

    /**
     * Set the compressed data change rate in MB.
     *
     * @param compressedDataRateInMB the compressedDataRateInMB value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withCompressedDataRateInMB(Double compressedDataRateInMB) {
        this.compressedDataRateInMB = compressedDataRateInMB;
        return this;
    }

    /**
     * Get the uncompressed data change rate in MB.
     *
     * @return the uncompressedDataRateInMB value
     */
    public Double uncompressedDataRateInMB() {
        return this.uncompressedDataRateInMB;
    }

    /**
     * Set the uncompressed data change rate in MB.
     *
     * @param uncompressedDataRateInMB the uncompressedDataRateInMB value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withUncompressedDataRateInMB(Double uncompressedDataRateInMB) {
        this.uncompressedDataRateInMB = uncompressedDataRateInMB;
        return this;
    }

    /**
     * Get the source IP address.
     *
     * @return the ipAddress value
     */
    public String ipAddress() {
        return this.ipAddress;
    }

    /**
     * Set the source IP address.
     *
     * @param ipAddress the ipAddress value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withIpAddress(String ipAddress) {
        this.ipAddress = ipAddress;
        return this;
    }

    /**
     * Get the agent version.
     *
     * @return the agentVersion value
     */
    public String agentVersion() {
        return this.agentVersion;
    }

    /**
     * Set the agent version.
     *
     * @param agentVersion the agentVersion value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withAgentVersion(String agentVersion) {
        this.agentVersion = agentVersion;
        return this;
    }

    /**
     * Get agent expiry date.
     *
     * @return the agentExpiryDate value
     */
    public DateTime agentExpiryDate() {
        return this.agentExpiryDate;
    }

    /**
     * Set agent expiry date.
     *
     * @param agentExpiryDate the agentExpiryDate value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withAgentExpiryDate(DateTime agentExpiryDate) {
        this.agentExpiryDate = agentExpiryDate;
        return this;
    }

    /**
     * Get a value indicating whether installed agent needs to be updated.
     *
     * @return the isAgentUpdateRequired value
     */
    public String isAgentUpdateRequired() {
        return this.isAgentUpdateRequired;
    }

    /**
     * Set a value indicating whether installed agent needs to be updated.
     *
     * @param isAgentUpdateRequired the isAgentUpdateRequired value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withIsAgentUpdateRequired(String isAgentUpdateRequired) {
        this.isAgentUpdateRequired = isAgentUpdateRequired;
        return this;
    }

    /**
     * Get a value indicating whether the source server requires a restart after update.
     *
     * @return the isRebootAfterUpdateRequired value
     */
    public String isRebootAfterUpdateRequired() {
        return this.isRebootAfterUpdateRequired;
    }

    /**
     * Set a value indicating whether the source server requires a restart after update.
     *
     * @param isRebootAfterUpdateRequired the isRebootAfterUpdateRequired value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withIsRebootAfterUpdateRequired(String isRebootAfterUpdateRequired) {
        this.isRebootAfterUpdateRequired = isRebootAfterUpdateRequired;
        return this;
    }

    /**
     * Get the last heartbeat received from the source server.
     *
     * @return the lastHeartbeat value
     */
    public DateTime lastHeartbeat() {
        return this.lastHeartbeat;
    }

    /**
     * Set the last heartbeat received from the source server.
     *
     * @param lastHeartbeat the lastHeartbeat value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withLastHeartbeat(DateTime lastHeartbeat) {
        this.lastHeartbeat = lastHeartbeat;
        return this;
    }

    /**
     * Get the process server Id.
     *
     * @return the processServerId value
     */
    public String processServerId() {
        return this.processServerId;
    }

    /**
     * Set the process server Id.
     *
     * @param processServerId the processServerId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withProcessServerId(String processServerId) {
        this.processServerId = processServerId;
        return this;
    }

    /**
     * Get the multi vm group Id.
     *
     * @return the multiVmGroupId value
     */
    public String multiVmGroupId() {
        return this.multiVmGroupId;
    }

    /**
     * Set the multi vm group Id.
     *
     * @param multiVmGroupId the multiVmGroupId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withMultiVmGroupId(String multiVmGroupId) {
        this.multiVmGroupId = multiVmGroupId;
        return this;
    }

    /**
     * Get the multi vm group name.
     *
     * @return the multiVmGroupName value
     */
    public String multiVmGroupName() {
        return this.multiVmGroupName;
    }

    /**
     * Set the multi vm group name.
     *
     * @param multiVmGroupName the multiVmGroupName value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withMultiVmGroupName(String multiVmGroupName) {
        this.multiVmGroupName = multiVmGroupName;
        return this;
    }

    /**
     * Get a value indicating whether multi vm sync is enabled or disabled.
     *
     * @return the multiVmSyncStatus value
     */
    public String multiVmSyncStatus() {
        return this.multiVmSyncStatus;
    }

    /**
     * Set a value indicating whether multi vm sync is enabled or disabled.
     *
     * @param multiVmSyncStatus the multiVmSyncStatus value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withMultiVmSyncStatus(String multiVmSyncStatus) {
        this.multiVmSyncStatus = multiVmSyncStatus;
        return this;
    }

    /**
     * Get the list of protected disks.
     *
     * @return the protectedDisks value
     */
    public List<InMageAzureV2ProtectedDiskDetails> protectedDisks() {
        return this.protectedDisks;
    }

    /**
     * Set the list of protected disks.
     *
     * @param protectedDisks the protectedDisks value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withProtectedDisks(List<InMageAzureV2ProtectedDiskDetails> protectedDisks) {
        this.protectedDisks = protectedDisks;
        return this;
    }

    /**
     * Get a value indicating whether any disk is resized for this VM.
     *
     * @return the diskResized value
     */
    public String diskResized() {
        return this.diskResized;
    }

    /**
     * Set a value indicating whether any disk is resized for this VM.
     *
     * @param diskResized the diskResized value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withDiskResized(String diskResized) {
        this.diskResized = diskResized;
        return this;
    }

    /**
     * Get the master target Id.
     *
     * @return the masterTargetId value
     */
    public String masterTargetId() {
        return this.masterTargetId;
    }

    /**
     * Set the master target Id.
     *
     * @param masterTargetId the masterTargetId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withMasterTargetId(String masterTargetId) {
        this.masterTargetId = masterTargetId;
        return this;
    }

    /**
     * Get the CPU count of the VM on the primary side.
     *
     * @return the sourceVmCpuCount value
     */
    public Integer sourceVmCpuCount() {
        return this.sourceVmCpuCount;
    }

    /**
     * Set the CPU count of the VM on the primary side.
     *
     * @param sourceVmCpuCount the sourceVmCpuCount value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withSourceVmCpuCount(Integer sourceVmCpuCount) {
        this.sourceVmCpuCount = sourceVmCpuCount;
        return this;
    }

    /**
     * Get the RAM size of the VM on the primary side.
     *
     * @return the sourceVmRamSizeInMB value
     */
    public Integer sourceVmRamSizeInMB() {
        return this.sourceVmRamSizeInMB;
    }

    /**
     * Set the RAM size of the VM on the primary side.
     *
     * @param sourceVmRamSizeInMB the sourceVmRamSizeInMB value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withSourceVmRamSizeInMB(Integer sourceVmRamSizeInMB) {
        this.sourceVmRamSizeInMB = sourceVmRamSizeInMB;
        return this;
    }

    /**
     * Get the type of the OS on the VM.
     *
     * @return the osType value
     */
    public String osType() {
        return this.osType;
    }

    /**
     * Set the type of the OS on the VM.
     *
     * @param osType the osType value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withOsType(String osType) {
        this.osType = osType;
        return this;
    }

    /**
     * Get the OS disk VHD name.
     *
     * @return the vhdName value
     */
    public String vhdName() {
        return this.vhdName;
    }

    /**
     * Set the OS disk VHD name.
     *
     * @param vhdName the vhdName value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withVhdName(String vhdName) {
        this.vhdName = vhdName;
        return this;
    }

    /**
     * Get the id of the disk containing the OS.
     *
     * @return the osDiskId value
     */
    public String osDiskId() {
        return this.osDiskId;
    }

    /**
     * Set the id of the disk containing the OS.
     *
     * @param osDiskId the osDiskId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withOsDiskId(String osDiskId) {
        this.osDiskId = osDiskId;
        return this;
    }

    /**
     * Get azure VM Disk details.
     *
     * @return the azureVMDiskDetails value
     */
    public List<AzureVmDiskDetails> azureVMDiskDetails() {
        return this.azureVMDiskDetails;
    }

    /**
     * Set azure VM Disk details.
     *
     * @param azureVMDiskDetails the azureVMDiskDetails value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withAzureVMDiskDetails(List<AzureVmDiskDetails> azureVMDiskDetails) {
        this.azureVMDiskDetails = azureVMDiskDetails;
        return this;
    }

    /**
     * Get recovery Azure given name.
     *
     * @return the recoveryAzureVMName value
     */
    public String recoveryAzureVMName() {
        return this.recoveryAzureVMName;
    }

    /**
     * Set recovery Azure given name.
     *
     * @param recoveryAzureVMName the recoveryAzureVMName value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withRecoveryAzureVMName(String recoveryAzureVMName) {
        this.recoveryAzureVMName = recoveryAzureVMName;
        return this;
    }

    /**
     * Get the Recovery Azure VM size.
     *
     * @return the recoveryAzureVMSize value
     */
    public String recoveryAzureVMSize() {
        return this.recoveryAzureVMSize;
    }

    /**
     * Set the Recovery Azure VM size.
     *
     * @param recoveryAzureVMSize the recoveryAzureVMSize value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withRecoveryAzureVMSize(String recoveryAzureVMSize) {
        this.recoveryAzureVMSize = recoveryAzureVMSize;
        return this;
    }

    /**
     * Get the recovery Azure storage account.
     *
     * @return the recoveryAzureStorageAccount value
     */
    public String recoveryAzureStorageAccount() {
        return this.recoveryAzureStorageAccount;
    }

    /**
     * Set the recovery Azure storage account.
     *
     * @param recoveryAzureStorageAccount the recoveryAzureStorageAccount value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withRecoveryAzureStorageAccount(String recoveryAzureStorageAccount) {
        this.recoveryAzureStorageAccount = recoveryAzureStorageAccount;
        return this;
    }

    /**
     * Get the ARM id of the log storage account used for replication. This will be set to null if no log storage account was provided during enable protection.
     *
     * @return the recoveryAzureLogStorageAccountId value
     */
    public String recoveryAzureLogStorageAccountId() {
        return this.recoveryAzureLogStorageAccountId;
    }

    /**
     * Set the ARM id of the log storage account used for replication. This will be set to null if no log storage account was provided during enable protection.
     *
     * @param recoveryAzureLogStorageAccountId the recoveryAzureLogStorageAccountId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withRecoveryAzureLogStorageAccountId(String recoveryAzureLogStorageAccountId) {
        this.recoveryAzureLogStorageAccountId = recoveryAzureLogStorageAccountId;
        return this;
    }

    /**
     * Get the PE Network details.
     *
     * @return the vmNics value
     */
    public List<VMNicDetails> vmNics() {
        return this.vmNics;
    }

    /**
     * Set the PE Network details.
     *
     * @param vmNics the vmNics value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withVmNics(List<VMNicDetails> vmNics) {
        this.vmNics = vmNics;
        return this;
    }

    /**
     * Get the selected recovery azure network Id.
     *
     * @return the selectedRecoveryAzureNetworkId value
     */
    public String selectedRecoveryAzureNetworkId() {
        return this.selectedRecoveryAzureNetworkId;
    }

    /**
     * Set the selected recovery azure network Id.
     *
     * @param selectedRecoveryAzureNetworkId the selectedRecoveryAzureNetworkId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withSelectedRecoveryAzureNetworkId(String selectedRecoveryAzureNetworkId) {
        this.selectedRecoveryAzureNetworkId = selectedRecoveryAzureNetworkId;
        return this;
    }

    /**
     * Get the selected source nic Id which will be used as the primary nic during failover.
     *
     * @return the selectedSourceNicId value
     */
    public String selectedSourceNicId() {
        return this.selectedSourceNicId;
    }

    /**
     * Set the selected source nic Id which will be used as the primary nic during failover.
     *
     * @param selectedSourceNicId the selectedSourceNicId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withSelectedSourceNicId(String selectedSourceNicId) {
        this.selectedSourceNicId = selectedSourceNicId;
        return this;
    }

    /**
     * Get a value indicating the discovery type of the machine. Value can be vCenter or physical.
     *
     * @return the discoveryType value
     */
    public String discoveryType() {
        return this.discoveryType;
    }

    /**
     * Set a value indicating the discovery type of the machine. Value can be vCenter or physical.
     *
     * @param discoveryType the discoveryType value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withDiscoveryType(String discoveryType) {
        this.discoveryType = discoveryType;
        return this;
    }

    /**
     * Get the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum.
     *
     * @return the enableRdpOnTargetOption value
     */
    public String enableRdpOnTargetOption() {
        return this.enableRdpOnTargetOption;
    }

    /**
     * Set the selected option to enable RDP\SSH on target vm after failover. String value of {SrsDataContract.EnableRDPOnTargetOption} enum.
     *
     * @param enableRdpOnTargetOption the enableRdpOnTargetOption value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withEnableRdpOnTargetOption(String enableRdpOnTargetOption) {
        this.enableRdpOnTargetOption = enableRdpOnTargetOption;
        return this;
    }

    /**
     * Get the data stores of the on-premise machine. Value can be list of strings that contain data store names.
     *
     * @return the datastores value
     */
    public List<String> datastores() {
        return this.datastores;
    }

    /**
     * Set the data stores of the on-premise machine. Value can be list of strings that contain data store names.
     *
     * @param datastores the datastores value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withDatastores(List<String> datastores) {
        this.datastores = datastores;
        return this;
    }

    /**
     * Get the ARM Id of the target Azure VM. This value will be null until the VM is failed over. Only after failure it will be populated with the ARM Id of the Azure VM.
     *
     * @return the targetVmId value
     */
    public String targetVmId() {
        return this.targetVmId;
    }

    /**
     * Set the ARM Id of the target Azure VM. This value will be null until the VM is failed over. Only after failure it will be populated with the ARM Id of the Azure VM.
     *
     * @param targetVmId the targetVmId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withTargetVmId(String targetVmId) {
        this.targetVmId = targetVmId;
        return this;
    }

    /**
     * Get the target resource group Id.
     *
     * @return the recoveryAzureResourceGroupId value
     */
    public String recoveryAzureResourceGroupId() {
        return this.recoveryAzureResourceGroupId;
    }

    /**
     * Set the target resource group Id.
     *
     * @param recoveryAzureResourceGroupId the recoveryAzureResourceGroupId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withRecoveryAzureResourceGroupId(String recoveryAzureResourceGroupId) {
        this.recoveryAzureResourceGroupId = recoveryAzureResourceGroupId;
        return this;
    }

    /**
     * Get the recovery availability set Id.
     *
     * @return the recoveryAvailabilitySetId value
     */
    public String recoveryAvailabilitySetId() {
        return this.recoveryAvailabilitySetId;
    }

    /**
     * Set the recovery availability set Id.
     *
     * @param recoveryAvailabilitySetId the recoveryAvailabilitySetId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withRecoveryAvailabilitySetId(String recoveryAvailabilitySetId) {
        this.recoveryAvailabilitySetId = recoveryAvailabilitySetId;
        return this;
    }

    /**
     * Get a value indicating whether managed disks should be used during failover.
     *
     * @return the useManagedDisks value
     */
    public String useManagedDisks() {
        return this.useManagedDisks;
    }

    /**
     * Set a value indicating whether managed disks should be used during failover.
     *
     * @param useManagedDisks the useManagedDisks value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withUseManagedDisks(String useManagedDisks) {
        this.useManagedDisks = useManagedDisks;
        return this;
    }

    /**
     * Get license Type of the VM to be used.
     *
     * @return the licenseType value
     */
    public String licenseType() {
        return this.licenseType;
    }

    /**
     * Set license Type of the VM to be used.
     *
     * @param licenseType the licenseType value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withLicenseType(String licenseType) {
        this.licenseType = licenseType;
        return this;
    }

    /**
     * Get the validation errors of the on-premise machine Value can be list of validation errors.
     *
     * @return the validationErrors value
     */
    public List<HealthError> validationErrors() {
        return this.validationErrors;
    }

    /**
     * Set the validation errors of the on-premise machine Value can be list of validation errors.
     *
     * @param validationErrors the validationErrors value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withValidationErrors(List<HealthError> validationErrors) {
        this.validationErrors = validationErrors;
        return this;
    }

    /**
     * Get the last RPO calculated time.
     *
     * @return the lastRpoCalculatedTime value
     */
    public DateTime lastRpoCalculatedTime() {
        return this.lastRpoCalculatedTime;
    }

    /**
     * Set the last RPO calculated time.
     *
     * @param lastRpoCalculatedTime the lastRpoCalculatedTime value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withLastRpoCalculatedTime(DateTime lastRpoCalculatedTime) {
        this.lastRpoCalculatedTime = lastRpoCalculatedTime;
        return this;
    }

    /**
     * Get the last update time received from on-prem components.
     *
     * @return the lastUpdateReceivedTime value
     */
    public DateTime lastUpdateReceivedTime() {
        return this.lastUpdateReceivedTime;
    }

    /**
     * Set the last update time received from on-prem components.
     *
     * @param lastUpdateReceivedTime the lastUpdateReceivedTime value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withLastUpdateReceivedTime(DateTime lastUpdateReceivedTime) {
        this.lastUpdateReceivedTime = lastUpdateReceivedTime;
        return this;
    }

    /**
     * Get the replica id of the protected item.
     *
     * @return the replicaId value
     */
    public String replicaId() {
        return this.replicaId;
    }

    /**
     * Set the replica id of the protected item.
     *
     * @param replicaId the replicaId value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withReplicaId(String replicaId) {
        this.replicaId = replicaId;
        return this;
    }

    /**
     * Get the OS Version of the protected item.
     *
     * @return the osVersion value
     */
    public String osVersion() {
        return this.osVersion;
    }

    /**
     * Set the OS Version of the protected item.
     *
     * @param osVersion the osVersion value to set
     * @return the InMageAzureV2ReplicationDetails object itself.
     */
    public InMageAzureV2ReplicationDetails withOsVersion(String osVersion) {
        this.osVersion = osVersion;
        return this;
    }

}


text:
/**
 * navigation.js
 *
 * Handles toggling the navigation menu for small screens and enables tab
 * support for dropdown menus.
 */
( function() {
	var container, button, menu, links, subMenus;

	container = document.getElementById( 'site-navigation' );
	if ( ! container ) {
		return;
	}

	button = container.querySelector('.menu-toggle');
	if ( 'undefined' === typeof button ) {
		return;
	}

	menu = container.getElementsByTagName( 'ul' )[0];

	// Hide menu toggle button if menu is empty and return early.
	if ( 'undefined' === typeof menu ) {
		button.style.display = 'none';
		return;
	}

	menu.setAttribute( 'aria-expanded', 'false' );
	if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
		menu.className += ' nav-menu';
	}

	button.onclick = function() {
		if ( -1 !== container.className.indexOf( 'toggled' ) ) {
			container.className = container.className.replace( ' toggled', '' );
			button.setAttribute( 'aria-expanded', 'false' );
			menu.setAttribute( 'aria-expanded', 'false' );
		} else {
			container.className += ' toggled';
			button.setAttribute( 'aria-expanded', 'true' );
			menu.setAttribute( 'aria-expanded', 'true' );
		}
	};

	// Get all the link elements within the menu.
	links    = menu.getElementsByTagName( 'a' );
	subMenus = menu.getElementsByTagName( 'ul' );

	// Set menu items with submenus to aria-haspopup="true".
	for ( var i = 0, len = subMenus.length; i < len; i++ ) {
		subMenus[i].parentNode.setAttribute( 'aria-haspopup', 'true' );
	}

	// Each time a menu link is focused or blurred, toggle focus.
	for ( i = 0, len = links.length; i < len; i++ ) {
		links[i].addEventListener( 'focus', toggleFocus, true );
		links[i].addEventListener( 'blur', toggleFocus, true );
	}

	/**
	 * Sets or removes .focus class on an element.
	 */
	function toggleFocus() {
		var self = this;

		// Move up through the ancestors of the current link until we hit .nav-menu.
		while ( -1 === self.className.indexOf( 'nav-menu' ) ) {

			// On li elements toggle the class .focus.
			if ( 'li' === self.tagName.toLowerCase() ) {
				if ( -1 !== self.className.indexOf( 'focus' ) ) {
					self.className = self.className.replace( ' focus', '' );
				} else {
					self.className += ' focus';
				}
			}

			self = self.parentElement;
		}
	}
} )();

jQuery(window).load(function($) {

	var resizeTimer, sf, mobile;
    sf = jQuery('ul.sf-menu');
	mobile = jQuery( '.menu-toggle' );

	// Build a function that disables and enables superfish when needed
	function generateResizeNavigation() {
        if( ! mobile.is( ':visible' ) && !sf.hasClass('sf-js-enabled') ) {
			if (typeof jQuery.fn.superfish !== 'undefined' && jQuery.isFunction(jQuery.fn.superfish)) {
				// you only want SuperFish to be re-enabled once (sf.hasClass)
				sf.superfish({
					delay:       500,                            // one second delay on mouseout
					animation:   {opacity:'show',height:'show'},  // fade-in and slide-down animation
					speed:       'fast',                          // faster animation speed
					cssArrows:   false
				});
			}
        } else if ( mobile.is( ':visible' ) ) {
			if (typeof jQuery.fn.superfish !== 'undefined' && jQuery.isFunction(jQuery.fn.superfish)) {
				// smaller screen, disable SuperFish
				sf.superfish('destroy');
			}
        }
    };

	// Add dropdown toggle that display child menu items.
	jQuery( '.main-navigation .page_item_has_children > a, .main-navigation .menu-item-has-children > a' ).after( '' );

	// When we resize the browser, check to see which dropdown type we should use
    jQuery(window).resize(function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(generateResizeNavigation, 250);
    });

	// Check to see which dropdown type we should use
	if ( mobile.is( ':visible' ) ) {
		generateResizeNavigation();
	}

	// Build the mobile button that displays the dropdown menu
	jQuery( '.dropdown-toggle' ).click( function( e ) {
		var _this = jQuery( this );
		e.preventDefault();
		_this.toggleClass( 'toggle-on' );
		_this.next( '.children, .sub-menu' ).toggleClass( 'toggled-on' );
		_this.attr( 'aria-expanded', _this.attr( 'aria-expanded' ) === 'false' ? 'true' : 'false' );
		_this.html( _this.html() === '' ? '' : '' );
			return false;
	} );
});


text:
function [upsilonap, upsilon] = lfmapComputeUpsilonVector(gamma, sigma2, t1)

% LFMAPCOMPUTEUPSILONVECTOR Upsilon vector for acce. pos. with t1 limit
% FORMAT
% DESC computes a portion of the LFMAP kernel.
% ARG gamma : Gamma value for system.
% ARG sigma2 : length scale of latent process.
% ARG t1 : first time input (number of time points x 1).
% RETURN upsilon : result of this subcomponent of the kernel for the given
% values.
%
% COPYRIGHT : Mauricio Alvarez, 2010
%
% SEEALSO : lfmapComputeUpsilonMatrix.m

% GPMAT

sigma = sqrt(sigma2);

if nargout > 1
    upsilon = lfmComputeUpsilonVector(gamma, sigma2, t1);
    upsilonap = gamma^2*upsilon - (2/(sqrt(pi)*sigma))*exp(-(t1.^2)/sigma2).*(gamma + 2*t1/sigma2);
else
    upsilonap = gamma^2*lfmComputeUpsilonVector(gamma, sigma2, t1) ...
        - (2/(sqrt(pi)*sigma))*exp(-(t1.^2)/sigma2).*(gamma + 2*t1/sigma2);
end


text:
magestack
=========

Magento server configs and setup scripts


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<TITLE
>auth_delay</TITLE
><META
NAME="GENERATOR"
CONTENT="Modular DocBook HTML Stylesheet Version 1.79"><LINK
REV="MADE"
HREF="mailto:pgsql-docs@postgresql.org"><LINK
REL="HOME"
TITLE="PostgreSQL 9.6.2 Documentation"
HREF="index.html"><LINK
REL="UP"
TITLE="Additional Supplied Modules"
HREF="contrib.html"><LINK
REL="PREVIOUS"
TITLE="adminpack"
HREF="adminpack.html"><LINK
REL="NEXT"
TITLE="auto_explain"
HREF="auto-explain.html"><LINK
REL="STYLESHEET"
TYPE="text/css"
HREF="stylesheet.css"><META
HTTP-EQUIV="Content-Type"
CONTENT="text/html; charset=ISO-8859-1"><META
NAME="creation"
CONTENT="2017-02-06T21:56:32">

PostgreSQL 9.6.2 Documentation

Prev	Up	Appendix F. Additional Supplied Modules	Next

F.2. auth_delay

  <TT
CLASS="FILENAME"
>auth_delay</TT
> causes the server to pause briefly before
  reporting authentication failure, to make brute-force attacks on database
  passwords more difficult.  Note that it does nothing to prevent
  denial-of-service attacks, and may even exacerbate them, since processes
  that are waiting before reporting authentication failure will still consume
  connection slots.

  In order to function, this module must be loaded via
  shared_preload_libraries in <TT
CLASS="FILENAME"
>postgresql.conf</TT
>.

F.2.1. Configuration Parameters

<TT
CLASS="VARNAME"
>auth_delay.milliseconds</TT
> (<TT
CLASS="TYPE"
>int</TT
>)

      The number of milliseconds to wait before reporting an authentication
      failure.  The default is 0.

   These parameters must be set in <TT
CLASS="FILENAME"
>postgresql.conf</TT
>.
   Typical usage might be:

# postgresql.conf
shared_preload_libraries = 'auth_delay'

auth_delay.milliseconds = '500'

F.2.2. Author

   KaiGai Kohei <kaigai@ak.jp.nec.com>

Prev	Home	Next

adminpack	Up	auto_explain


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Pragma" content="no-cache" />
<meta name="robots" content="noindex, nofollow" />

<title>Sitengine - <?=$this->html($this->translate('formtextviewPageTitle'));?></title>

<link rel="stylesheet" type="text/css" href="<?=$this->_controller->getEnv()->getMediaRequestDir();?>/Frontend/Styles/Global.css" />
<link rel="stylesheet" type="text/css" href="<?=$this->_controller->getEnv()->getMediaRequestDir();?>/Frontend/Styles/Forms.css" />

<?require 'Sitengine/Env/_Templates/BreadcrumbsSection.html';?>
<?require 'Sitengine/Env/_Templates/AbstractSection.html';?>
<?require 'Sitengine/Env/_Templates/StatusSection.html';?>

<?
	$mp3 = preg_replace('/&/', '&', $this->SECTIONS->POST->file1OriginalUri);
	$escapedProjectDir = preg_replace('/\//', '\/', $this->_controller->getEnv()->getMyProjectDir());
	$escapedProjectDir = preg_replace('/\./', '\.', $escapedProjectDir);
	$xsendPath  = $this->_controller->getEnv()->getMyProjectRequestDir();
	$xsendPath .= '/'.preg_replace('/'.$escapedProjectDir.'\//', '', $this->SECTIONS->POST->file1OriginalPath);
?>

<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,47,0" width="30" height="30" id="wimpy_button_45225" name="wimpy_button_45225" >
<param name="movie" value="<?=$this->_controller->getEnv()->getContribRequestDir();?>/Wimpy/Button/wimpy_button.swf?theFile=<?=$xsendPath;?>" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<embed src="<?=$this->_controller->getEnv()->getContribRequestDir();?>/Wimpy/Button/wimpy_button.swf?theFile=<?=$xsendPath;?>" width="30" height="30" quality="high" bgcolor="#ffffff" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"  name="wimpy_button_45225" /></object>

<?=$this->SECTIONS->POST->markup;?>

<?foreach($this->SECTIONS->POST as $field => $val):?>
	<?=$field;?> = <?=$val;?>

<?endforeach;?>

Comments

<?if(!sizeof($this->SECTIONS->COMMENTS)):?>

<a href="<?=$this->SECTIONS->COMMENTACTIONS->commentInsert->uri;?>">Be the first to write a comment

<?else:?>

<a href="<?=$this->SECTIONS->COMMENTACTIONS->commentInsert->uri;?>">Post a comment

<?foreach($this->SECTIONS->COMMENTS as $row):?>
<?$id = $this->html($row->id);?>
<?$cdate = $row->cdate;?>
<?$comment = $this->html($this->truncate($row->comment));?>
<?$name = $this->html($row->name);?>
<?$firstname = $this->html($row->firstname);?>
<?$lastname = $this->html($row->lastname);?>

<?=$firstname;?> <?=$lastname;?> @ <?=$cdate;?>

<?=$comment;?>

<?endforeach;?>
<?endif;?>

<?require 'Sitengine/Env/_Templates/FooterSection.html';?>


text:
require 'active_support/core_ext/object/inclusion'

module ActiveRecord::Associations::Builder
  class HasMany < CollectionAssociation #:nodoc:
    self.macro = :has_many

    self.valid_options += [:primary_key, :dependent, :as, :through, :source, :source_type, :inverse_of]

    def build
      reflection = super
      configure_dependency
      reflection
    end

    private

      def configure_dependency
        if options[:dependent]
          unless options[:dependent].in?([:destroy, :delete_all, :nullify, :restrict])
            raise ArgumentError, "The :dependent option expects either :destroy, :delete_all, " \
                                 ":nullify or :restrict (#{options[:dependent].inspect})"
          end

          send("define_#{options[:dependent]}_dependency_method")
          model.before_destroy dependency_method_name
        end
      end

      def define_destroy_dependency_method
        name = self.name
        mixin.redefine_method(dependency_method_name) do
          send(name).each do |o|
            # No point in executing the counter update since we're going to destroy the parent anyway
            counter_method = ('belongs_to_counter_cache_before_destroy_for_' + self.class.name.downcase).to_sym
            if o.respond_to?(counter_method)
              class << o
                self
              end.send(:define_method, counter_method, Proc.new {})
            end
          end

          send(name).delete_all
        end
      end

      def define_delete_all_dependency_method
        name = self.name
        mixin.redefine_method(dependency_method_name) do
          association(name).delete_all_on_destroy
        end
      end

      def define_nullify_dependency_method
        name = self.name
        mixin.redefine_method(dependency_method_name) do
          send(name).delete_all
        end
      end

      def define_restrict_dependency_method
        name = self.name
        mixin.redefine_method(dependency_method_name) do
          raise ActiveRecord::DeleteRestrictionError.new(name) unless send(name).empty?
        end
      end

      def dependency_method_name
        "has_many_dependent_for_#{name}"
      end
  end
end


text:
import os
import sys
import datetime
import math
import tinctest
import re
from time import gmtime, strftime

import unittest2 as unittest
from fnmatch import fnmatch

from tinctest.runner import TINCTextTestResult
from tinctest.lib import run_shell_command, Gpdiff

from mpp.lib.PSQL import PSQL
from mpp.models import SQLTestCase

class BuiltinFunctionTestCase(SQLTestCase):

    def __init__(self, methodName, baseline_result = None, sql_file = None, db_name = None):
        super(BuiltinFunctionTestCase, self).__init__(methodName, baseline_result, sql_file, db_name)
        self.optimizer_mode = 'on'

    def _infer_metadata(self):
        super(BuiltinFunctionTestCase, self)._infer_metadata()
        self.executemode= self._metadata.get('executemode', 'ORCA_PLANNER_DIFF')

    def run_test(self):
        sql_file = self.sql_file
        ans_file = self.ans_file

        source_file = sys.modules[self.__class__.__module__].__file__
        source_dir = os.path.dirname(source_file)
        out_directory = self.get_out_dir()

        if (self.executemode == 'ORCA_PLANNER_DIFF'):
            out_file = os.path.join(self.get_out_dir(), os.path.basename(sql_file).replace('.sql', '.out'))
            new_ans_file = os.path.join(self.get_out_dir(), os.path.basename(ans_file).replace('.ans', '_mod.ans'))
            guc_sql_file = self._add_gucs_to_sql_file(sql_file)
            self.gucs.add('optimizer=off')
            self.gucs.add('optimizer_log=off')
            guc_off_sql_file = self._add_gucs_to_sql_file(sql_file)

            PSQL.run_sql_file(guc_off_sql_file, dbname = self.db_name, out_file = new_ans_file)
            PSQL.run_sql_file(guc_sql_file, dbname = self.db_name, out_file = out_file)

            sedcmd = "sed -i -e 's/transactionid,,,,,[[:digit:]]\+,,,,[[:digit:]]\+,[[:digit:]]\+,ExclusiveLock,t,[[:digit:]]\+,/transactionid,,,,,XXXXX,,,,XXXXX,XXXXX,ExclusiveLock,t,XXXXX,/' " +new_ans_file
            sedcmd2 = "sed -i -e 's/transactionid,,,,,[[:digit:]]\+,,,,[[:digit:]]\+,[[:digit:]]\+,ExclusiveLock,t,[[:digit:]]\+,/transactionid,,,,,XXXXX,,,,XXXXX,XXXXX,ExclusiveLock,t,XXXXX,/' " +out_file
            sedcmd3 = "sed -i -e 's/pg_aoseg_[[:digit:]]\+/pg_aoseg_XXXXX/' " +new_ans_file
            sedcmd4 = "sed -i -e 's/pg_aoseg_[[:digit:]]\+/pg_aoseg_XXXXX/' " +out_file
            run_shell_command(sedcmd, "replace dynamic values in planner output with XXXXX")
            run_shell_command(sedcmd2, "replace dynamic values in ORCA output with XXXXX")
            run_shell_command(sedcmd3, "replace dynamic values in pg_aoseg.pg_aoseg_")
            run_shell_command(sedcmd4, "replace dynamic values in pg_aoseg.pg_aoseg_")

            result = Gpdiff.are_files_equal(out_file, new_ans_file)
            if result == False:
                self.test_artifacts.append(out_file.replace('.out', '.diff'))

            return result
        elif (self.executemode == 'gt1'):
            out_file = os.path.join(self.get_out_dir(), os.path.basename(sql_file).replace('.sql', '.out'))
            guc_sql_file = self._add_gucs_to_sql_file(sql_file)

            PSQL.run_sql_file(guc_sql_file, dbname = self.db_name, out_file = out_file)
            f = open(out_file, 'r')
            content = f.readlines()
            f.close()
            linecount = 0
            for x in content:
                x = x.strip()
                if x == "(1 row)":
                    output = content[linecount - 1].strip()
                linecount += 1

            if int(output) > 1:
                return True
            diff_file = os.path.join(out_directory, os.path.basename(sql_file).replace('.sql', '.diff'))
            f = open(diff_file, 'w')
            f.write("expecting an output which is greater than 1, instead the actual output was " +output)
            f.close()
            return False
        else:
            out_file = os.path.join(self.get_out_dir(), os.path.basename(sql_file).replace('.sql', '.out'))
            guc_sql_file = self._add_gucs_to_sql_file(sql_file)

            PSQL.run_sql_file(guc_sql_file, dbname = self.db_name, out_file = out_file)

            sedcmd1 = "sed -i -e 's/transactionid,,,,,[[:digit:]]\+,,,,[[:digit:]]\+,[[:digit:]]\+,ExclusiveLock,t,[[:digit:]]\+,/transactionid,,,,,XXXXX,,,,XXXXX,XXXXX,ExclusiveLock,t,XXXXX,/' " +out_file
            sedcmd2 = "sed -i -e 's/pg_aoseg_[[:digit:]]\+/pg_aoseg_XXXXX/' " +out_file
            run_shell_command(sedcmd1, "replace dynamic values in ORCA output with XXXXX")
            run_shell_command(sedcmd2, "replace dynamic values in pg_aoseg.pg_aoseg_")

            result = Gpdiff.are_files_equal(out_file, ans_file)
            if result == False:
                self.test_artifacts.append(out_file.replace('.out', '.diff'))
            return result


text:
package in.ashwanik.lib;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by AshwaniK on 9/29/2016.
 */
public class JokeManager {
    private Random random;

    private int randInt(int min, int max) {
        return random.nextInt((max - min) + 1) + min;
    }

    public String getJoke() {
        return jokes.get(randInt(0, jokes.size() - 1));
    }

    private List<String> jokes;
    private static JokeManager ourInstance = new JokeManager();

    public static JokeManager getInstance() {
        return ourInstance;
    }

    private JokeManager() {
        random = new Random();
        jokes = new ArrayList<>();
        jokes.add("Teacher asked the students to tell the most common word used by students in a classroom.\n" +
                "Suddenly a student got up and said "Can't Sir"!\n" +
                "Brilliant! You are right, the teacher said!");
        jokes.add("Johnny asked to Sam what they will do that night.\n" +
                "Sam said "we will flip a coin"\n" +
                "Then Johnny said "If it comes head, we will go for movies. If tails, we will play cards, if it stands on edge, we will study"!");
        jokes.add("Teacher: Which one is closer, Sun or Africa?\n" +
                "Johnny: Sun\n" +
                "Teacher: Why?\n" +
                "Johnny: We can see the sun all the time, but can't see Africa.");
    }
}


text:
import {User} from "./user.model";
export class Subject{

  constructor(){};

  id : number;
  name : string;
  creator : User;

}


text:
module MiqAeServiceTenantQuotaSpec
  describe MiqAeMethodService::MiqAeServiceTenantQuota do
    let(:settings) { {} }
    let(:tenant) { Tenant.create(:name => 'fred', :domain => 'a.b') }
    let(:cpu_quota) { TenantQuota.create(:name => "cpu_allocated", :unit => "int", :value => 2, :tenant => tenant) }
    let(:storage_quota) { TenantQuota.create(:name => "storage_allocated", :unit => "GB", :value => 160, :tenant => tenant) }

    let(:st_cpu_quota) { MiqAeMethodService::MiqAeServiceTenantQuota.find(cpu_quota.id) }
    let(:st_storage_quota) { MiqAeMethodService::MiqAeServiceTenantQuota.find(storage_quota.id) }

    before do
      stub_server_configuration(settings)
    end

    it "check max_cpu quota" do
      expect(st_cpu_quota.name).to eq('cpu_allocated')
      expect(st_cpu_quota.unit).to eq('int')
      expect(st_cpu_quota.value.to_i).to eq(2)
    end

    it "check storage quota" do
      expect(st_storage_quota.name).to eq('storage_allocated')
      expect(st_storage_quota.unit).to eq('GB')
      expect(st_storage_quota.value.to_i).to eq(160)
    end

    it "check tenant from quota" do
      expect(st_storage_quota.tenant.name).to eq('fred')
    end
  end
end


text:
In the course of development, a very important step is to test our code to ensure its quality and integrity. We need to make sure that every function returns the expected result, and that our code performs optimally. We already know that the focus of unit tests is to find logical errors in the design or implementation of programs. They are used to detect and expose problems in code early on so that we can more easily fix them, before they get out of hand. We also know that performance tests are conducted for the purpose of optimizing our code so that it is stable under load, and can maintain a high level of concurrency. In this section, we'll take a look at some commonly asked questions about how unit and performance tests are implemented in Go.

The Go language comes with a lightweight testing framework called `testing`, and we can use the `go test` command to execute unit and performance tests. Go's `testing` framework works similarly to testing frameworks in other languages. You can develop all sorts of test suites with them, which may include tests for unit testes, benchmarking, stress tests, etc. Let's learn about testing in Go, step by step.

## How to write test cases

Since the `go test` command can only be executed in a directory containing all corresponding files, we are going to create a new project directory `gotest` so that all of our code and test code are in the same directory.

Let's go ahead and create two files in the directory called gotest.go and gotest_test.go

1. Gotest.go: This file declares our package name and has a function that performs a division operation:

package gotest

	import (
		"errors"
	)

	func Division(a, b float64) (float64, error) {
		if b == 0 {
			return 0, errors.New("Divisor can not be 0")
		}
		return a / b, nil
	}

2. Gotest_test.go: This is our unit test file. Keep in mind the following principles for test files:

- File names must end in `_test.go` so that `go test` can find and execute the appropriate code
- You have to import the `testing` package
- All test case functions begin with `Test`
- Test cases follow the source code order
- Test functions of the form `TestXxx()` take a `testing.T` argument; we can use this type to record errors or to get the testing status
- In functions of the form `func TestXxx(t * testing.T)`, the `Xxx` section can be any alphanumeric combination, but the first letter cannot be a lowercase letter [az]. For example, `Testintdiv` would be an invalid function name.
- By calling one of the `Error`, `Errorf`, `FailNow`, `Fatal` or `FatalIf` methods of `testing.T` on our testing functions, we can fail the test. In addition, we can call the `Log` method of `testing.T` to record the information in the error log.

Here is our test code:

	package gotest

	import (
		"testing"
	)

	func Test_Division_1(t *testing.T) {
		// try a unit test on function
		if i, e := Division(6, 2); i != 3 || e != nil {
			// If it is not as expected, then the test has failed
			t.Error("division function tests do not pass ")
		} else {
			// record the expected information
			t.Log("first test passed ")
		}
	}

	func Test_Division_2(t *testing.T) {
		t.Error("just does not pass")
	}

When executing `go test` in the project directory, it will display the following information:

	--- FAIL: Test_Division_2 (0.00 seconds)
	gotest_test.go: 16: is not passed
	FAIL
	exit status 1
	FAIL gotest 0.013s

We can see from this result that the second test function does not pass since we wrote in a dead-end using `t.Error`. But what about the performance of our first test function?  By default, executing `go test` does not display test results. We need to supply the verbose argument `-v` like `go test -v` to display the following output:

	=== RUN Test_Division_1
	--- PASS: Test_Division_1 (0.00 seconds)
	gotest_test.go: 11: first test passed
	=== RUN Test_Division_2
	--- FAIL: Test_Division_2 (0.00 seconds)
	gotest_test.go: 16: is not passed
	FAIL
	exit status 1
	FAIL gotest 0.012s

The above output shows in detail the results of our test. We see that the test function 1 `Test_Division_1` passes, and the test function 2 `Test_Division_2` fails, finally concluding that our test suite does not pass. Next, we modify the test function 2 with the following code:

	func Test_Division_2(t *testing.T) {
		// try a unit test on function
		if _, e := Division(6, 0); e == nil {
			// If it is not as expected, then the error
			t.Error("Division did not work as expected.")
		} else {
			// record some of the information you expect to record
			t.Log("one test passed.", e)
		}
	}

We execute `go test-v` once again. The following information should now be displayed -the test suite has passed~:

	=== RUN Test_Division_1
	--- PASS: Test_Division_1 (0.00 seconds)
	gotest_test.go: 11: first test passed
	=== RUN Test_Division_2
	--- PASS: Test_Division_2 (0.00 seconds)
	gotest_test.go: 20: one test passed. divisor can not be 0
	PASS
	ok gotest 0.013s

## How to write stress tests

Stress testing is used to detect function performance, and bears some resemblance to unit testing (which we will not get into here), however we need need to pay attention to the following points:

- Stress tests must follow the following format, where XXX can be any alphanumeric combination and its first letter cannot be a lowercase letter.

	func BenchmarkXXX (b *testing.B){...}

- By default, `Go test` does not perform function stress tests. If you want to perform stress tests, you need to set the flag `-test.bench` with the format: `-test.bench="test_name_regex"`. For instance, to run all stress tests in your suite, you would run `go test -test.bench=".*"`.
- In your stress tests, please remember to use testing.BN any loop bodies, so that the tests can be run properly.
- As before, test file names must end in `_test.go`

Here we create a stress test file called webbench_test.go:

	package gotest

	import (
		"testing"
	)

	func Benchmark_Division(b *testing.B) {
		for i := 0; i < bN; i++ { // use bN for looping
			Division(4, 5)
		}
	}

	func Benchmark_TimeConsumingFunction(b *testing.B) {
		b.StopTimer() // call the function to stop the stress test time count

		// Do some initialization work, such as reading file data, database connections and the like,
		// So that our benchmarks reflect the performance of the function itself

		b.StartTimer() // re-start time
		for i := 0; i < b.N; i++ {
			Division(4, 5)
		}
	}

We then execute the `go test -file webbench_test.go -test.bench =".*"` command, which outputs the following results:

	PASS
	Benchmark_Division 500000000 7.76 ns/ op
	Benchmark_TimeConsumingFunction 500000000 7.80 ns/ op
	ok gotest 9.364s

The above results show that we did not perform any of our `TestXXX` unit test functions, and instead only performed our `BenchmarkXXX` tests (which is exactly as expected). The first `Benchmark_Division` test shows that our `Division()` function executed 500 million times, with an average execution time of 7.76ns. The second `Benchmark_TimeConsumingFunction` shows that our `TmeConsumingFunction` executed 500 million times, with an average execution time of 7.80ns. Finally, it outputs the total execution time of our test suite.

## Summary

From our brief encounter with unit and stress testing in Go, we can see that the `testing` package is very lightweight, yet packed with useful utilities. We saw that writing unit and stress tests can be very simple, and running them can be even easier with Go's built-in `go test` command. Every time we modify our code, we can simply run `go test` to begin regression testing.

## Links

- [Directory](preface.md)
- Previous section: [Debugging using GDB](11.2.md)
- Next section: [Summary](11.4.md)