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

namespace  UnitTestCreator
{
	public class  CsNunitTestCreator
	{
		/// <summary>
		/// Anaylyses the code file.
		/// </summary>
		/// <returns>The file.</returns>
		/// <param name="filecontent">Filecontent.</param>
		private List<string> anaylyseFile (string[] filecontent)
		{
			bool isNamespace = false;
			bool isclass = false;
			string class_name = "";

			List<string> temp = new List<string> ();
			if (!filecontent [0].Contains ("Generated Nunit test file, please adjust to your need.")) {
				temp.Add ("//Generated unit test file, please adjust to your need.");
				temp.Add ("//Copyright Roelof Anne Schoenmaker");
				temp.Add ("");

				//loop through the content to analyse
				foreach (String line in filecontent) {
					if (line.Contains ("Namespace")) {
						temp.Add (line);
						temp.Add ("{");
						temp.Add (" Using NUnit.Framework;");
						isNamespace = true;
					} else if (line.Contains ("Class")) {
						temp.Add (" [TestFixture]");
						class_name = line.Replace ("Private", "Protected").Replace ("Protected", "Public").Replace ("Public Class", "");
						temp.Add (line.Replace ("Private", "Protected").Replace ("Protected", "Public") + "Test");
						temp.Add (" {");
						temp.Add ("");
						temp.Add ("  [SetUp]");
						temp.Add ("  Protected void SetUp()");
						temp.Add ("  {");
						temp.Add ("   //This sub can be used to setup variables used in Nunit tests");
						temp.Add ("  }");
						temp.Add ("");
						temp.Add ("  [TearDown]");
						temp.Add ("  Protected void TearDown()");
						temp.Add ("  {");
						temp.Add ("   //This sub can be used to TearDown the setuped variables used in Nunit tests");
						temp.Add ("  }");
						isclass = true;
					} else if (line.Replace ("Private", "Protected").Replace ("Protected", "Public").Contains ("Public void")) {
						temp.Add ("");
						temp.Add ("  //Maybe you can think of a test for this void method?");
						temp.Add ("  [Test]");
						string sub_name = line.Substring (0, line.IndexOf ("("));
						sub_name = sub_name.Substring (sub_name.LastIndexOf (" "));
						temp.Add ("  Public void " + sub_name + "Test()");
						temp.Add ("  {");
						temp.Add ("    ////A few lines of help follow");
						temp.Add ("    //// Classic syntax");
						temp.Add ("    //Assert.IsTrue(2 + 2 = 4);");
						temp.Add ("    //// Helper syntax");
						temp.Add ("    //Assert.That(2 + 2 = 4, [Is].True);");
						temp.Add ("    //Assert.That(2 + 2 = 4);");
						temp.Add ("    ////Inherited syntax");
						temp.Add ("    //Expect(2 + 2 = 4, True);");
						temp.Add ("    //Expect(2 + 2 = 4);");

						temp.Add ("");
						temp.Add ("    //To indicate that this test is not yet valid");
						temp.Add ("    Assert.IsTrue(False);");
						temp.Add ("    //Actual parameters of mentioned void are: " + line.Replace (line.Substring (0, line.IndexOf ("(")), "").Replace (")", ""));
						temp.Add ("  }");
					} else if (line.Replace ("Private", "Protected").Replace ("Protected", "Public").Contains ("Public")) {
						temp.Add ("");
						temp.Add ("  [Test]");
						string function_name = line.Substring (0, line.IndexOf ("("));
						function_name = function_name.Substring (function_name.LastIndexOf (" "));
						temp.Add ("  Public void " + function_name + "Test");
						temp.Add ("  {");
						temp.Add ("   //You might want to use the class object to access the methods");
						temp.Add ("   " + class_name + " test" + class_name + " = new " + class_name + "();");

						// If there are parameters, then add them
						string parameters = "";
						if (!line.Contains ("()")) {
							char[] splitchar = { ',', ')' };
							var list_of_parameters = line.Replace (line.Substring (0, line.IndexOf ("(") + 1), "").Split (splitchar);
							foreach (string parameter in list_of_parameters) {
								string param = parameter.Trim ();
								if (!param.StartsWith ("As")) {

									// Set default expected
									if (param.TrimStart ().StartsWith ("String")) {
										temp.Add ("  String " + param.Replace ("ByVal", "").Replace ("ByRef", "") + " = \"\";");//ToDo: fix correct to cs paramtypes
									} else if (param.TrimStart ().StartsWith ("Bool")) {
										temp.Add ("  Bool " + param.Replace ("ByVal", "").Replace ("ByRef", "") + " = False;");//ToDo: fix correct to cs paramtypes
									}// Other types may be extended later
									else {
										temp.Add ("  Object " + param.Replace ("ByVal", "").Replace ("ByRef", "") + " = Null;");//ToDo: fix correct to cs paramtypes
									}

									parameters = parameters + "," + param.Substring (0, param.IndexOf (" As")).Replace ("ByVal", "").Replace ("ByRef", "");
								}
							}
							if (parameters.Length > 0) {
								parameters = parameters.Substring (1);
							}
						}

						// Set default expected
						if (line.TrimStart ().StartsWith ("String")) {
							temp.Add ("  String expected = \"\";");
						} else if (line.TrimStart ().StartsWith ("Bool")) {
							temp.Add ("  Bool expected = False;");
						}// Other types may be extended later
						else {
							temp.Add ("  var expected = Null;");
						}

						temp.Add ("  Assert.AreEqual(expected, test" + class_name + "." + function_name + "(" + parameters + "));");

						temp.Add ("  }");
					}
				}

				if (isclass) {
					temp.Add (" }");
				}
				if (isNamespace) {
					temp.Add ("}");
				}
			}
			return temp;
		}

		/// <summary>
		/// Check how much of the original and test map differ from each other
		/// </summary>
		/// <returns>The part that is equal between the original and test map</returns>
		/// <param name="dir">Dir.</param>
		/// <param name="test_map">Test map.</param>
		private string samePart (string dir, string test_map)
		{
			string samefromstart = "";
			int locator = 0;
			if (dir.Length < test_map.Length) {
				int length = dir.Length - 1;
				while (dir[locator]==test_map[locator] && locator < length) {
					locator++;
				}
				if (locator > 0) {
					samefromstart = dir.Substring (0, locator);
				}
			} else {
				int length = test_map.Length - 1;
				while (dir[locator]==test_map[locator] && locator < length) {
					locator++;
				}
				if (locator > 0) {
					samefromstart = test_map.Substring (0, locator);
				}
			}

			return samefromstart;
		}

		/// <summary>
		/// Creates the test file from the file in filepath and creates a testfile in the testmap.
		/// </summary>
		/// <param name="filepath">Filepath.</param>
		/// <param name="testmap">Testmap.</param>
		public void createTestFileFrom (string filepath, string testmap)
		{
			var file_content = System.IO.File.ReadAllLines (filepath);

			String samepath = samePart (filepath, testmap);
			String stripped_filename_and_special_path = filepath.Replace (samepath, "");
			String test_file_location = testmap + stripped_filename_and_special_path.Replace (".cs", "Test.cs");

			if (test_file_location.Contains ("/")) {
				if (!System.IO.Directory.Exists (test_file_location.Substring (0, test_file_location.LastIndexOf ("/")))) {
					System.IO.Directory.CreateDirectory (test_file_location.Substring (0, test_file_location.LastIndexOf ("/")));
				}
			} else {
				if (!System.IO.Directory.Exists (test_file_location.Substring (0, test_file_location.LastIndexOf ("\\")))) {
					System.IO.Directory.CreateDirectory (test_file_location.Substring (0, test_file_location.LastIndexOf ("\\")));
				}
			}

			// Only once a testfile is made, because of user changes
			if (!System.IO.File.Exists (test_file_location)) {
				System.IO.File.AppendAllLines (test_file_location, anaylyseFile (file_content));
			}

		}

	}
}


text:
# ----------------------------------------------------------------------------------
#
# Copyright Microsoft Corporation
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------------

<#
.SYNOPSIS
Test StorageAccount
.DESCRIPTION
SmokeTest
#>
function Test-StorageBlobContainer
{
    # Setup
    $rgname = Get-StorageManagementTestResourceName;

    try
    {
        # Test
        $stoname = 'sto' + $rgname;
        $stotype = 'Standard_GRS';
        $loc = Get-ProviderLocation ResourceManagement;
        $kind = 'StorageV2'
		$containerName = "container"+ $rgname

        Write-Verbose "RGName: $rgname | Loc: $loc"
        New-AzureRmResourceGroup -Name $rgname -Location $loc;

        $loc = Get-ProviderLocation_Stage;
        New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype -Kind $kind
        $stos = Get-AzureRmStorageAccount -ResourceGroupName $rgname;

		New-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $rgname $container.ResourceGroupName
		Assert-AreEqual $stoname $container.StorageAccountName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual $false $container.HasLegalHold
		Assert-AreEqual $false $container.HasImmutabilityPolicy
		Assert-AreEqual none $container.PublicAccess

        $publicAccess = 'blob'
		$metadata = @{tag0="value0";tag1="value1";tag2="value2"}

		Update-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName -PublicAccess $publicAccess -Metadata $metadata
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $rgname $container.ResourceGroupName
		Assert-AreEqual $stoname $container.StorageAccountName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual $false $container.HasLegalHold
		Assert-AreEqual $false $container.HasImmutabilityPolicy
		Assert-AreEqual $publicAccess $container.PublicAccess
		Assert-AreEqual $metadata.Count $container.Metadata.Count

        $publicAccess = 'container'
		$metadata = @{tag0="value0";tag1="value1"}
		$containerName2 = "container2"+ $rgname
		New-AzureRmStorageContainer -StorageAccount $stos -Name $containerName2 -PublicAccess $publicAccess -Metadata $metadata
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName2
		Assert-AreEqual $rgname $container.ResourceGroupName
		Assert-AreEqual $stoname $container.StorageAccountName
		Assert-AreEqual $containerName2 $container.Name
		Assert-AreEqual $false $container.HasLegalHold
		Assert-AreEqual $false $container.HasImmutabilityPolicy
		Assert-AreEqual $publicAccess $container.PublicAccess
		Assert-AreEqual $metadata.Count $container.Metadata.Count

		$containers = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname
		Assert-AreEqual 2 $containers.Count
		Assert-AreEqual $containerName  $containers[1].Name
		Assert-AreEqual $containerName2  $containers[0].Name

		Remove-AzureRmStorageContainer -Force -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		$containers = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname
		Assert-AreEqual 1 $containers.Count
		Assert-AreEqual $containerName2  $containers[0].Name

		Remove-AzureRmStorageContainer -Force -StorageAccount $stos -Name $containerName2
		$containers = Get-AzureRmStorageContainer -StorageAccount $stos
		Assert-AreEqual 0 $containers.Count

        Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname;
    }
    finally
    {
        # Cleanup
        Clean-ResourceGroup $rgname
    }
}

function Test-StorageBlobContainerLegalHold
{
    # Setup
    $rgname = Get-StorageManagementTestResourceName;

    try
    {
        # Test
        $stoname = 'sto' + $rgname;
        $stotype = 'Standard_GRS';
        $loc = Get-ProviderLocation ResourceManagement;
        $kind = 'StorageV2'
		$containerName = "container"+ $rgname

        Write-Verbose "RGName: $rgname | Loc: $loc"
        New-AzureRmResourceGroup -Name $rgname -Location $loc;

        $loc = Get-ProviderLocation_Stage;
        New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype -Kind $kind
        $stos = Get-AzureRmStorageAccount -ResourceGroupName $rgname;

		New-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $rgname $container.ResourceGroupName
		Assert-AreEqual $stoname $container.StorageAccountName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual $false $container.HasLegalHold
		Assert-AreEqual $false $container.HasImmutabilityPolicy
		Assert-AreEqual none $container.PublicAccess

        Add-AzureRmStorageContainerLegalHold -ResourceGroupName $rgname -StorageAccountName $stoname  -Name $containerName -Tag  tag1,tag2,tag3
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual 3 $container.LegalHold.Tags.Count
		Assert-AreEqual "tag1" $container.LegalHold.Tags[0].Tag
		Assert-AreNotEqual $null $container.LegalHold.Tags[0].Timestamp
		Assert-AreNotEqual $null $container.LegalHold.Tags[0].ObjectIdentifier
		Assert-AreEqual "tag2" $container.LegalHold.Tags[1].Tag
		Assert-AreNotEqual $null $container.LegalHold.Tags[1].Timestamp
		Assert-AreNotEqual $null $container.LegalHold.Tags[1].ObjectIdentifier
		Assert-AreEqual "tag3" $container.LegalHold.Tags[2].Tag
		Assert-AreNotEqual $null $container.LegalHold.Tags[2].Timestamp
		Assert-AreNotEqual $null $container.LegalHold.Tags[2].ObjectIdentifier

		Remove-AzureRmStorageContainerLegalHold -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName -Tag tag1,tag2
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual 1 $container.LegalHold.Tags.Count
		Assert-AreEqual "tag3" $container.LegalHold.Tags[0].Tag
		Assert-AreNotEqual $null $container.LegalHold.Tags[0].Timestamp
		Assert-AreNotEqual $null $container.LegalHold.Tags[0].ObjectIdentifier

		Add-AzureRmStorageContainerLegalHold -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName -Tag tag1
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual 2 $container.LegalHold.Tags.Count
		Assert-AreEqual "tag3" $container.LegalHold.Tags[0].Tag
		Assert-AreNotEqual $null $container.LegalHold.Tags[0].Timestamp
		Assert-AreNotEqual $null $container.LegalHold.Tags[0].ObjectIdentifier
		Assert-AreEqual "tag1" $container.LegalHold.Tags[1].Tag
		Assert-AreNotEqual $null $container.LegalHold.Tags[1].Timestamp
		Assert-AreNotEqual $null $container.LegalHold.Tags[1].ObjectIdentifier

		Remove-AzureRmStorageContainerLegalHold -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName -Tag tag1,tag3
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual 0 $container.LegalHold.Tags.Count

		Remove-AzureRmStorageContainer -Force -StorageAccount $stos -Name $containerName
		$containers = Get-AzureRmStorageContainer -StorageAccount $stos
		Assert-AreEqual 0 $containers.Count

        Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname;
    }
    finally
    {
        # Cleanup
        Clean-ResourceGroup $rgname
    }
}

function Test-StorageBlobContainerImmutabilityPolicy
{
    # Setup
    $rgname = Get-StorageManagementTestResourceName;

    try
    {
        # Test
        $stoname = 'sto' + $rgname;
        $stotype = 'Standard_GRS';
        $loc = Get-ProviderLocation ResourceManagement;
        $kind = 'Storage'
		$containerName = "container"+ $rgname

        Write-Verbose "RGName: $rgname | Loc: $loc"
        New-AzureRmResourceGroup -Name $rgname -Location $loc;

        $loc = Get-ProviderLocation_Stage;
        New-AzureRmStorageAccount -ResourceGroupName $rgname -Name $stoname -Location $loc -Type $stotype -Kind $kind
        $stos = Get-AzureRmStorageAccount -ResourceGroupName $rgname;

		New-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $rgname $container.ResourceGroupName
		Assert-AreEqual $stoname $container.StorageAccountName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual $false $container.HasLegalHold
		Assert-AreEqual $false $container.HasImmutabilityPolicy
		Assert-AreEqual none $container.PublicAccess

        $policy = Get-AzureRmStorageContainerImmutabilityPolicy -ResourceGroupName $rgname -StorageAccountName $stoname  -ContainerName $containerName
		Assert-AreEqual 0 $policy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Unlocked $policy.State
		Assert-AreEqual "" $policy.Etag

		$immutabilityPeriod =3
        Set-AzureRmStorageContainerImmutabilityPolicy -ResourceGroupName $rgname -StorageAccountName $stoname  -ContainerName $containerName -ImmutabilityPeriod $immutabilityPeriod
		$policy = Get-AzureRmStorageContainerImmutabilityPolicy -ResourceGroupName $rgname -StorageAccountName $stoname  -ContainerName $containerName
		Assert-AreEqual $immutabilityPeriod $policy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Unlocked $policy.State
		Assert-AreNotEqual $null $policy.Etag
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Unlocked $container.ImmutabilityPolicy.State
		Assert-AreEqual 1 $container.ImmutabilityPolicy.UpdateHistory.Count
		Assert-AreEqual put $container.ImmutabilityPolicy.UpdateHistory[0].Update
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.UpdateHistory[0].ImmutabilityPeriodSinceCreationInDays
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].Timestamp
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].ObjectIdentifier

		$immutabilityPeriod =2
        Set-AzureRmStorageContainerImmutabilityPolicy -inputObject $policy -ImmutabilityPeriod $immutabilityPeriod
		$policy = Get-AzureRmStorageContainerImmutabilityPolicy -ResourceGroupName $rgname -StorageAccountName $stoname  -ContainerName $containerName
		Assert-AreEqual $immutabilityPeriod $policy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Unlocked $policy.State
		Assert-AreNotEqual $null $policy.Etag
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Unlocked $container.ImmutabilityPolicy.State
		Assert-AreEqual 1 $container.ImmutabilityPolicy.UpdateHistory.Count
		Assert-AreEqual put $container.ImmutabilityPolicy.UpdateHistory[0].Update
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.UpdateHistory[0].ImmutabilityPeriodSinceCreationInDays
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].Timestamp
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].ObjectIdentifier

        Remove-AzureRmStorageContainerImmutabilityPolicy -inputObject $policy
		$policy = Get-AzureRmStorageContainerImmutabilityPolicy -ResourceGroupName $rgname -StorageAccountName $stoname  -ContainerName $containerName
		Assert-AreEqual 0 $policy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Unlocked $policy.State
		Assert-AreEqual "" $policy.Etag
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual 0 $container.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Unlocked $container.ImmutabilityPolicy.State
		Assert-AreEqual 0 $container.ImmutabilityPolicy.UpdateHistory.Count

		$immutabilityPeriod =7
        Set-AzureRmStorageContainerImmutabilityPolicy -inputObject $policy -ImmutabilityPeriod $immutabilityPeriod
		$policy = Get-AzureRmStorageContainerImmutabilityPolicy -ResourceGroupName $rgname -StorageAccountName $stoname  -ContainerName $containerName
		Assert-AreEqual $immutabilityPeriod $policy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Unlocked $policy.State
		Assert-AreNotEqual $null $policy.Etag
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Unlocked $container.ImmutabilityPolicy.State
		Assert-AreEqual 1 $container.ImmutabilityPolicy.UpdateHistory.Count
		Assert-AreEqual put $container.ImmutabilityPolicy.UpdateHistory[0].Update
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.UpdateHistory[0].ImmutabilityPeriodSinceCreationInDays
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].Timestamp
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].ObjectIdentifier

        Lock-AzureRmStorageContainerImmutabilityPolicy -inputObject $policy -Force
		$policy = Get-AzureRmStorageContainerImmutabilityPolicy -ResourceGroupName $rgname -StorageAccountName $stoname  -ContainerName $containerName
		Assert-AreEqual $immutabilityPeriod $policy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Locked $policy.State
		Assert-AreNotEqual $null $policy.Etag
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Locked $container.ImmutabilityPolicy.State
		Assert-AreEqual 2 $container.ImmutabilityPolicy.UpdateHistory.Count
		Assert-AreEqual put $container.ImmutabilityPolicy.UpdateHistory[0].Update
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.UpdateHistory[0].ImmutabilityPeriodSinceCreationInDays
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].Timestamp
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].ObjectIdentifier
		Assert-AreEqual lock $container.ImmutabilityPolicy.UpdateHistory[1].Update
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.UpdateHistory[1].ImmutabilityPeriodSinceCreationInDays
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[1].Timestamp
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[1].ObjectIdentifier

		$immutabilityPeriod2 =20
        Set-AzureRmStorageContainerImmutabilityPolicy -inputObject $policy -ExtendPolicy -ImmutabilityPeriod $immutabilityPeriod2
		$policy = Get-AzureRmStorageContainerImmutabilityPolicy -ResourceGroupName $rgname -StorageAccountName $stoname  -ContainerName $containerName
		Assert-AreEqual $immutabilityPeriod2 $policy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Locked $policy.State
		Assert-AreNotEqual $null $policy.Etag
		$container = Get-AzureRmStorageContainer -ResourceGroupName $rgname -StorageAccountName $stoname -Name $containerName
		Assert-AreEqual $containerName $container.Name
		Assert-AreEqual $immutabilityPeriod2 $container.ImmutabilityPolicy.ImmutabilityPeriodSinceCreationInDays
		Assert-AreEqual Locked $container.ImmutabilityPolicy.State
		Assert-AreEqual 3 $container.ImmutabilityPolicy.UpdateHistory.Count
		Assert-AreEqual put $container.ImmutabilityPolicy.UpdateHistory[0].Update
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.UpdateHistory[0].ImmutabilityPeriodSinceCreationInDays
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].Timestamp
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[0].ObjectIdentifier
		Assert-AreEqual lock $container.ImmutabilityPolicy.UpdateHistory[1].Update
		Assert-AreEqual $immutabilityPeriod $container.ImmutabilityPolicy.UpdateHistory[1].ImmutabilityPeriodSinceCreationInDays
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[1].Timestamp
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[1].ObjectIdentifier
		Assert-AreEqual extend $container.ImmutabilityPolicy.UpdateHistory[2].Update
		Assert-AreEqual $immutabilityPeriod2 $container.ImmutabilityPolicy.UpdateHistory[2].ImmutabilityPeriodSinceCreationInDays
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[2].Timestamp
		Assert-AreNotEqual $null $container.ImmutabilityPolicy.UpdateHistory[2].ObjectIdentifier

		Remove-AzureRmStorageContainer -Force -StorageAccount $stos -Name $containerName
		$containers = Get-AzureRmStorageContainer -StorageAccount $stos
		Assert-AreEqual 0 $containers.Count

        Remove-AzureRmStorageAccount -Force -ResourceGroupName $rgname -Name $stoname;
    }
    finally
    {
        # Cleanup
        Clean-ResourceGroup $rgname
    }
}

redpajama_set_name: RedPajamaGithub


text:
export type ApplicationTargetPath = string & { ApplicationTargetPath: never }

export type Version = Version_data & { Version: never }
type Version_data = Readonly<{ major: number; minor: number; patch: number; suffix: string }>

export type ParseVersionResult =
    | Readonly<{ valid: true; value: Version }>
    | Readonly<{ valid: false }>

export type CheckDeployExistsError = CheckDeployExistsRemoteError
export type CheckDeployExistsRemoteError =
    | Readonly<{ type: "server-error" }>
    | Readonly<{ type: "infra-error"; err: string }>


text:
If you're developing kankun-json, please develop on a new feature branch and submit a pull request to `master` when ready for review. Another contributor with at least one prior accepted pull request to `master` should then review the request, and +1 or merge it. Thank you!

## Code of Conduct

A primary goal of Homedash is to be inclusive to the largest number of contributors, with the most varied and diverse backgrounds possible. As such, we are committed to providing a friendly, safe and welcoming environment for all, regardless of gender, sexual orientation, ability, ethnicity, socioeconomic status, and religion (or lack thereof).

All participants and contributors are expected to follow our
[code of conduct](https://github.com/homedash/kankun-json/wiki/Code-of-Conduct).

## Reporting bugs and opening issues

Please report bugs and open issues generously. Don't be afraid that your idea is silly, or you're reporting a duplicate. We're happy to hear from you.

## Code and other contributions

Contributions to Homedash (via pull request or otherwise) *must* be
licensed under the [MIT license](LICENSE.md).


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Microsoft.Win32.SafeHandles;

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using Internals = System.Net.Internals;

internal static partial class Interop
{
    internal static partial class IpHlpApi
    {
        // TODO: #3562 - Replace names with the ones from the Windows SDK.

        [Flags]
        internal enum AdapterFlags
        {
            DnsEnabled = 0x01,
            RegisterAdapterSuffix = 0x02,
            DhcpEnabled = 0x04,
            ReceiveOnly = 0x08,
            NoMulticast = 0x10,
            Ipv6OtherStatefulConfig = 0x20,
            NetBiosOverTcp = 0x40,
            IPv4Enabled = 0x80,
            IPv6Enabled = 0x100,
            IPv6ManagedAddressConfigurationSupported = 0x200,
        }

        [Flags]
        internal enum AdapterAddressFlags
        {
            DnsEligible = 0x1,
            Transient = 0x2
        }

        [Flags]
        internal enum GetAdaptersAddressesFlags
        {
            SkipUnicast = 0x0001,
            SkipAnycast = 0x0002,
            SkipMulticast = 0x0004,
            SkipDnsServer = 0x0008,
            IncludePrefix = 0x0010,
            SkipFriendlyName = 0x0020,
            IncludeWins = 0x0040,
            IncludeGateways = 0x0080,
            IncludeAllInterfaces = 0x0100,
            IncludeAllCompartments = 0x0200,
            IncludeTunnelBindingOrder = 0x0400,
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct IpSocketAddress
        {
            internal IntPtr address;
            internal int addressLength;

            internal IPAddress MarshalIPAddress()
            {
                // Determine the address family used to create the IPAddress.
                AddressFamily family = (addressLength > Internals.SocketAddress.IPv4AddressSize)
                    ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
                Internals.SocketAddress sockAddress = new Internals.SocketAddress(family, addressLength);
                Marshal.Copy(address, sockAddress.Buffer, 0, addressLength);

                return sockAddress.GetIPAddress();
            }
        }

        // IP_ADAPTER_ANYCAST_ADDRESS
        // IP_ADAPTER_MULTICAST_ADDRESS
        // IP_ADAPTER_DNS_SERVER_ADDRESS
        // IP_ADAPTER_WINS_SERVER_ADDRESS
        // IP_ADAPTER_GATEWAY_ADDRESS
        [StructLayout(LayoutKind.Sequential)]
        internal struct IpAdapterAddress
        {
            internal uint length;
            internal AdapterAddressFlags flags;
            internal IntPtr next;
            internal IpSocketAddress address;

            internal static InternalIPAddressCollection MarshalIpAddressCollection(IntPtr ptr)
            {
                InternalIPAddressCollection addressList = new InternalIPAddressCollection();

                while (ptr != IntPtr.Zero)
                {
                    IpAdapterAddress addressStructure = Marshal.PtrToStructure<IpAdapterAddress>(ptr);
                    IPAddress address = addressStructure.address.MarshalIPAddress();
                    addressList.InternalAdd(address);

                    ptr = addressStructure.next;
                }

                return addressList;
            }

            internal static IPAddressInformationCollection MarshalIpAddressInformationCollection(IntPtr ptr)
            {
                IPAddressInformationCollection addressList = new IPAddressInformationCollection();

                while (ptr != IntPtr.Zero)
                {
                    IpAdapterAddress addressStructure = Marshal.PtrToStructure<IpAdapterAddress>(ptr);
                    IPAddress address = addressStructure.address.MarshalIPAddress();
                    addressList.InternalAdd(new SystemIPAddressInformation(address, addressStructure.flags));

                    ptr = addressStructure.next;
                }

                return addressList;
            }
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct IpAdapterUnicastAddress
        {
            internal uint length;
            internal AdapterAddressFlags flags;
            internal IntPtr next;
            internal IpSocketAddress address;
            internal PrefixOrigin prefixOrigin;
            internal SuffixOrigin suffixOrigin;
            internal DuplicateAddressDetectionState dadState;
            internal uint validLifetime;
            internal uint preferredLifetime;
            internal uint leaseLifetime;
            internal byte prefixLength;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct IpAdapterAddresses
        {
            internal const int MAX_ADAPTER_ADDRESS_LENGTH = 8;

            internal uint length;
            internal uint index;
            internal IntPtr next;

            // Needs to be ANSI.
            [MarshalAs(UnmanagedType.LPStr)]
            internal string AdapterName;

            internal IntPtr firstUnicastAddress;
            internal IntPtr firstAnycastAddress;
            internal IntPtr firstMulticastAddress;
            internal IntPtr firstDnsServerAddress;

            internal string dnsSuffix;
            internal string description;
            internal string friendlyName;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_ADAPTER_ADDRESS_LENGTH)]
            internal byte[] address;
            internal uint addressLength;
            internal AdapterFlags flags;
            internal uint mtu;
            internal NetworkInterfaceType type;
            internal OperationalStatus operStatus;
            internal uint ipv6Index;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            internal uint[] zoneIndices;
            internal IntPtr firstPrefix;

            internal ulong transmitLinkSpeed;
            internal ulong receiveLinkSpeed;
            internal IntPtr firstWinsServerAddress;
            internal IntPtr firstGatewayAddress;
            internal uint ipv4Metric;
            internal uint ipv6Metric;
            internal ulong luid;
            internal IpSocketAddress dhcpv4Server;
            internal uint compartmentId;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            internal byte[] networkGuid;
            internal InterfaceConnectionType connectionType;
            internal InterfaceTunnelType tunnelType;
            internal IpSocketAddress dhcpv6Server; // Never available in Windows.
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 130)]
            internal byte[] dhcpv6ClientDuid;
            internal uint dhcpv6ClientDuidLength;
            internal uint dhcpV6Iaid;

            /* Windows 2008 +
                  PIP_ADAPTER_DNS_SUFFIX             FirstDnsSuffix;
             * */
        }

        internal enum InterfaceConnectionType : int
        {
            Dedicated = 1,
            Passive = 2,
            Demand = 3,
            Maximum = 4,
        }

        internal enum InterfaceTunnelType : int
        {
            None = 0,
            Other = 1,
            Direct = 2,
            SixToFour = 11,
            Isatap = 13,
            Teredo = 14,
            IpHttps = 15,
        }

        /// <summary>
        ///   IP_PER_ADAPTER_INFO - per-adapter IP information such as DNS server list.
        /// </summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        internal struct IpPerAdapterInfo
        {
            internal bool autoconfigEnabled;
            internal bool autoconfigActive;
            internal IntPtr currentDnsServer; /* IpAddressList* */
            internal IpAddrString dnsServerList;
        };

        /// <summary>
        ///   Store an IP address with its corresponding subnet mask,
        ///   both as dotted decimal strings.
        /// </summary>
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
        internal struct IpAddrString
        {
            internal IntPtr Next;      /* struct _IpAddressList* */
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
            internal string IpAddress;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 16)]
            internal string IpMask;
            internal uint Context;
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        internal struct MibIfRow2 // MIB_IF_ROW2
        {
            private const int GuidLength = 16;
            private const int IfMaxStringSize = 256;
            private const int IfMaxPhysAddressLength = 32;

            internal ulong interfaceLuid;
            internal uint interfaceIndex;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = GuidLength)]
            internal byte[] interfaceGuid;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxStringSize + 1)]
            internal char[] alias; // Null terminated string.
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxStringSize + 1)]
            internal char[] description; // Null terminated string.
            internal uint physicalAddressLength;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxPhysAddressLength)]
            internal byte[] physicalAddress; // ANSI
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = IfMaxPhysAddressLength)]
            internal byte[] permanentPhysicalAddress; // ANSI
            internal uint mtu;
            internal NetworkInterfaceType type;
            internal InterfaceTunnelType tunnelType;
            internal uint mediaType; // Enum
            internal uint physicalMediumType; // Enum
            internal uint accessType; // Enum
            internal uint directionType; // Enum
            internal byte interfaceAndOperStatusFlags; // Flags Enum
            internal OperationalStatus operStatus;
            internal uint adminStatus; // Enum
            internal uint mediaConnectState; // Enum
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = GuidLength)]
            internal byte[] networkGuid;
            internal InterfaceConnectionType connectionType;
            internal ulong transmitLinkSpeed;
            internal ulong receiveLinkSpeed;
            internal ulong inOctets;
            internal ulong inUcastPkts;
            internal ulong inNUcastPkts;
            internal ulong inDiscards;
            internal ulong inErrors;
            internal ulong inUnknownProtos;
            internal ulong inUcastOctets;
            internal ulong inMulticastOctets;
            internal ulong inBroadcastOctets;
            internal ulong outOctets;
            internal ulong outUcastPkts;
            internal ulong outNUcastPkts;
            internal ulong outDiscards;
            internal ulong outErrors;
            internal ulong outUcastOctets;
            internal ulong outMulticastOctets;
            internal ulong outBroadcastOctets;
            internal ulong outQLen;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibUdpStats
        {
            internal uint datagramsReceived;
            internal uint incomingDatagramsDiscarded;
            internal uint incomingDatagramsWithErrors;
            internal uint datagramsSent;
            internal uint udpListeners;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibTcpStats
        {
            internal uint reTransmissionAlgorithm;
            internal uint minimumRetransmissionTimeOut;
            internal uint maximumRetransmissionTimeOut;
            internal uint maximumConnections;
            internal uint activeOpens;
            internal uint passiveOpens;
            internal uint failedConnectionAttempts;
            internal uint resetConnections;
            internal uint currentConnections;
            internal uint segmentsReceived;
            internal uint segmentsSent;
            internal uint segmentsResent;
            internal uint errorsReceived;
            internal uint segmentsSentWithReset;
            internal uint cumulativeConnections;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibIpStats
        {
            internal bool forwardingEnabled;
            internal uint defaultTtl;
            internal uint packetsReceived;
            internal uint receivedPacketsWithHeaderErrors;
            internal uint receivedPacketsWithAddressErrors;
            internal uint packetsForwarded;
            internal uint receivedPacketsWithUnknownProtocols;
            internal uint receivedPacketsDiscarded;
            internal uint receivedPacketsDelivered;
            internal uint packetOutputRequests;
            internal uint outputPacketRoutingDiscards;
            internal uint outputPacketsDiscarded;
            internal uint outputPacketsWithNoRoute;
            internal uint packetReassemblyTimeout;
            internal uint packetsReassemblyRequired;
            internal uint packetsReassembled;
            internal uint packetsReassemblyFailed;
            internal uint packetsFragmented;
            internal uint packetsFragmentFailed;
            internal uint packetsFragmentCreated;
            internal uint interfaces;
            internal uint ipAddresses;
            internal uint routes;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibIcmpInfo
        {
            internal MibIcmpStats inStats;
            internal MibIcmpStats outStats;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibIcmpStats
        {
            internal uint messages;
            internal uint errors;
            internal uint destinationUnreachables;
            internal uint timeExceeds;
            internal uint parameterProblems;
            internal uint sourceQuenches;
            internal uint redirects;
            internal uint echoRequests;
            internal uint echoReplies;
            internal uint timestampRequests;
            internal uint timestampReplies;
            internal uint addressMaskRequests;
            internal uint addressMaskReplies;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibIcmpInfoEx
        {
            internal MibIcmpStatsEx inStats;
            internal MibIcmpStatsEx outStats;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibIcmpStatsEx
        {
            internal uint dwMsgs;
            internal uint dwErrors;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)]
            internal uint[] rgdwTypeCount;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibTcpTable
        {
            internal uint numberOfEntries;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibTcpRow
        {
            internal TcpState state;
            internal uint localAddr;
            internal byte localPort1;
            internal byte localPort2;
            // Ports are only 16 bit values (in network WORD order, 3,4,1,2).
            // There are reports where the high order bytes have garbage in them.
            internal byte ignoreLocalPort3;
            internal byte ignoreLocalPort4;
            internal uint remoteAddr;
            internal byte remotePort1;
            internal byte remotePort2;
            // Ports are only 16 bit values (in network WORD order, 3,4,1,2).
            // There are reports where the high order bytes have garbage in them.
            internal byte ignoreRemotePort3;
            internal byte ignoreRemotePort4;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibTcp6TableOwnerPid
        {
            internal uint numberOfEntries;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibTcp6RowOwnerPid
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            internal byte[] localAddr;
            internal uint localScopeId;
            internal byte localPort1;
            internal byte localPort2;
            // Ports are only 16 bit values (in network WORD order, 3,4,1,2).
            // There are reports where the high order bytes have garbage in them.
            internal byte ignoreLocalPort3;
            internal byte ignoreLocalPort4;
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            internal byte[] remoteAddr;
            internal uint remoteScopeId;
            internal byte remotePort1;
            internal byte remotePort2;
            // Ports are only 16 bit values (in network WORD order, 3,4,1,2).
            // There are reports where the high order bytes have garbage in them.
            internal byte ignoreRemotePort3;
            internal byte ignoreRemotePort4;
            internal TcpState state;
            internal uint owningPid;
        }

        internal enum TcpTableClass
        {
            TcpTableBasicListener = 0,
            TcpTableBasicConnections = 1,
            TcpTableBasicAll = 2,
            TcpTableOwnerPidListener = 3,
            TcpTableOwnerPidConnections = 4,
            TcpTableOwnerPidAll = 5,
            TcpTableOwnerModuleListener = 6,
            TcpTableOwnerModuleConnections = 7,
            TcpTableOwnerModuleAll = 8
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibUdpTable
        {
            internal uint numberOfEntries;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibUdpRow
        {
            internal uint localAddr;
            internal byte localPort1;
            internal byte localPort2;
            // Ports are only 16 bit values (in network WORD order, 3,4,1,2).
            // There are reports where the high order bytes have garbage in them.
            internal byte ignoreLocalPort3;
            internal byte ignoreLocalPort4;
        }

        internal enum UdpTableClass
        {
            UdpTableBasic = 0,
            UdpTableOwnerPid = 1,
            UdpTableOwnerModule = 2
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibUdp6TableOwnerPid
        {
            internal uint numberOfEntries;
        }

        [StructLayout(LayoutKind.Sequential)]
        internal struct MibUdp6RowOwnerPid
        {
            [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
            internal byte[] localAddr;
            internal uint localScopeId;
            internal byte localPort1;
            internal byte localPort2;
            // Ports are only 16 bit values (in network WORD order, 3,4,1,2).
            // There are reports where the high order bytes have garbage in them.
            internal byte ignoreLocalPort3;
            internal byte ignoreLocalPort4;
            internal uint owningPid;
        }

        internal delegate void StableUnicastIpAddressTableDelegate(IntPtr context, IntPtr table);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetAdaptersAddresses(
            AddressFamily family,
            uint flags,
            IntPtr pReserved,
            SafeLocalAllocHandle adapterAddresses,
            ref uint outBufLen);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetBestInterfaceEx(byte[] ipAddress, out int index);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetIfEntry2(ref MibIfRow2 pIfRow);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetIpStatisticsEx(out MibIpStats statistics, AddressFamily family);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetTcpStatisticsEx(out MibTcpStats statistics, AddressFamily family);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetUdpStatisticsEx(out MibUdpStats statistics, AddressFamily family);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetIcmpStatistics(out MibIcmpInfo statistics);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetIcmpStatisticsEx(out MibIcmpInfoEx statistics, AddressFamily family);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetTcpTable(SafeLocalAllocHandle pTcpTable, ref uint dwOutBufLen, bool order);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetExtendedTcpTable(SafeLocalAllocHandle pTcpTable, ref uint dwOutBufLen, bool order,
                                                        uint IPVersion, TcpTableClass tableClass, uint reserved);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetUdpTable(SafeLocalAllocHandle pUdpTable, ref uint dwOutBufLen, bool order);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetExtendedUdpTable(SafeLocalAllocHandle pUdpTable, ref uint dwOutBufLen, bool order,
                                                        uint IPVersion, UdpTableClass tableClass, uint reserved);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal extern static uint GetPerAdapterInfo(uint IfIndex, SafeLocalAllocHandle pPerAdapterInfo, ref uint pOutBufLen);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal static extern void FreeMibTable(IntPtr handle);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal static extern uint CancelMibChangeNotify2(IntPtr notificationHandle);

        [DllImport(Interop.Libraries.IpHlpApi)]
        internal static extern uint NotifyStableUnicastIpAddressTable(
            [In] AddressFamily addressFamily,
            [Out] out SafeFreeMibTable table,
            [MarshalAs(UnmanagedType.FunctionPtr)][In] StableUnicastIpAddressTableDelegate callback,
            [In] IntPtr context,
            [Out] out SafeCancelMibChangeNotify notificationHandle);

        [DllImport(Interop.Libraries.IpHlpApi, ExactSpelling = true)]
        internal extern static uint GetNetworkParams(SafeLocalAllocHandle pFixedInfo, ref uint pOutBufLen);
    }
}


text:
package com.fxx.library.widget.chart.pie;

/**
 * 数据结构
 * Created by wsl on 17/5/27.
 */

public interface IPieEntry {

    String getLabel();
    int getColor();
    float getValue();
    void setValue(float value);
}


text:
import sys

if sys.version_info >= (3, 3):

    import importlib

    def import_file(module_path='', module=''):
        importlib.invalidate_caches()
        if module in sys.modules:
            del sys.modules[module]
        sys.path.insert(0, module_path)
        loader = importlib.find_loader(module)
        del sys.path[0]
        m = loader.load_module(module)
        return m

elif sys.version_info >= (2, 7):

    def import_file(module_path='', module=''):
        if module in sys.modules:
            del sys.modules[module]
        sys.path.insert(0, module_path)
        m = __import__(module)
        del sys.path[0]
        return m

else:
    raise NotImplementedError('This modules functions are not implemented for python <2.7')

if __name__ == '__main__':
    # test this module with path and module name as arguments
    # will print modules namespace (without __builtins__)

    import pprint

    p, n = sys.argv[1:]
    m = import_file(p, n)
    d = m.__dict__
    del d['__builtins__']
    pprint.pprint(d)


text:
using System;

namespace Hydra.Framework.Specification
{
    /// <summary>
    /// Candidate Specification
    /// </summary>
    /// <typeparam name="TCandidate"></typeparam>
    public class Specification<TCandidate>
        : AbstractSpecification<TCandidate>
    {
        #region Member Variables
        /// <summary>
        /// All Candidate Collection
        /// </summary>
        private static readonly ISpecification<TCandidate> allCandidates = new AllSpecification<TCandidate>();
        #endregion

        #region Properties
        /// <summary>
        /// Gets the and.
        /// </summary>
        /// <value>The and.</value>
        public override ISpecificationBuilder<TCandidate> And
        {
            get
            {
                throw new SpecificationBuilderException("Ands cannot be root specifications");
            }
        }

        /// <summary>
        /// Gets all.
        /// </summary>
        /// <value>All.</value>
        public static ISpecification<TCandidate> All
        {
            get
            {
                return allCandidates;
            }
        }
        #endregion

        #region Overrides
        /// <summary>
        /// Determines whether [is satisfied by] [the specified candidate].
        /// </summary>
        /// <param name="candidate">The candidate.</param>
        /// <returns>
        /// 	<c>true</c> if [is satisfied by] [the specified candidate]; otherwise, <c>false</c>.
        /// </returns>
        public override bool IsSatisfiedBy(TCandidate candidate)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}


text:
package com.google.android.exoplayer2.text.webvtt;

import com.google.android.exoplayer2.text.Cue;
import com.google.android.exoplayer2.text.SimpleSubtitleDecoder;
import com.google.android.exoplayer2.text.SubtitleDecoderException;
import com.google.android.exoplayer2.util.ParsableByteArray;
import com.google.android.exoplayer2.util.Util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * A {@link SimpleSubtitleDecoder} for Webvtt embedded in a Mp4 container file.
 */
public final class Mp4WebvttDecoder extends SimpleSubtitleDecoder {

  private static final int BOX_HEADER_SIZE = 8;

  private static final int TYPE_payl = Util.getIntegerCodeForString("payl");
  private static final int TYPE_sttg = Util.getIntegerCodeForString("sttg");
  private static final int TYPE_vttc = Util.getIntegerCodeForString("vttc");

  private final ParsableByteArray sampleData;
  private final WebvttCue.Builder builder;

  public Mp4WebvttDecoder() {
    super("Mp4WebvttDecoder");
    sampleData = new ParsableByteArray();
    builder = new WebvttCue.Builder();
  }

  @Override
  protected Mp4WebvttSubtitle decode(byte[] bytes, int length, boolean reset)
      throws SubtitleDecoderException {
    // Webvtt in Mp4 samples have boxes inside of them, so we have to do a traditional box parsing:
    // first 4 bytes size and then 4 bytes type.
    sampleData.reset(bytes, length);
    List<Cue> resultingCueList = new ArrayList<>();
    while (sampleData.bytesLeft() > 0) {
      if (sampleData.bytesLeft() < BOX_HEADER_SIZE) {
        throw new SubtitleDecoderException("Incomplete Mp4Webvtt Top Level box header found.");
      }
      int boxSize = sampleData.readInt();
      int boxType = sampleData.readInt();
      if (boxType == TYPE_vttc) {
        resultingCueList.add(parseVttCueBox(sampleData, builder, boxSize - BOX_HEADER_SIZE));
      } else {
        // Peers of the VTTCueBox are still not supported and are skipped.
        sampleData.skipBytes(boxSize - BOX_HEADER_SIZE);
      }
    }
    return new Mp4WebvttSubtitle(resultingCueList);
  }

  private static Cue parseVttCueBox(ParsableByteArray sampleData, WebvttCue.Builder builder,
        int remainingCueBoxBytes) throws SubtitleDecoderException {
    builder.reset();
    while (remainingCueBoxBytes > 0) {
      if (remainingCueBoxBytes < BOX_HEADER_SIZE) {
        throw new SubtitleDecoderException("Incomplete vtt cue box header found.");
      }
      int boxSize = sampleData.readInt();
      int boxType = sampleData.readInt();
      remainingCueBoxBytes -= BOX_HEADER_SIZE;
      int payloadLength = boxSize - BOX_HEADER_SIZE;
      String boxPayload = new String(sampleData.data, sampleData.getPosition(), payloadLength);
      sampleData.skipBytes(payloadLength);
      remainingCueBoxBytes -= payloadLength;
      if (boxType == TYPE_sttg) {
        WebvttCueParser.parseCueSettingsList(boxPayload, builder);
      } else if (boxType == TYPE_payl) {
        WebvttCueParser.parseCueText(null, boxPayload.trim(), builder,
            Collections.<WebvttCssStyle>emptyList());
      } else {
        // Other VTTCueBox children are still not supported and are ignored.
      }
    }
    return builder.build();
  }

}


text:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../test_app/config/environment", __FILE__)
require 'rspec/rails'
require 'database_cleaner'
require 'coveralls'
require 'delorean'
require 'email_spec'
require 'sidekiq/testing'
require 'benchmark'
require 'factory_girl_rails'
require 'mock_redis'

Coveralls.wear_merged!

# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.

Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each { |f| require f }

RSpec.configure do |config|
  config.include Devise::TestHelpers, type: :controller
  config.include FactoryGirl::Syntax::Methods
  config.include(EmailSpec::Helpers)
  config.include(EmailSpec::Matchers)
  config.include(Kernel)

  config.use_transactional_fixtures = false

  config.before(:suite) do
    DatabaseCleaner[:mongoid].strategy       = :truncation
    DatabaseCleaner.clean_with :truncation
  end

  config.before(:each) do
    TrueClass.class_eval do
      def to_b
        true
      end
    end

    FalseClass.class_eval do
      def to_b
        false
      end
    end

    DatabaseCleaner.start

    langrp = LanguagesGroup.create name: 'test'

    en = Language.create name: 'English', languages_group: langrp
    ru = Language.create name: 'Russian', languages_group: langrp

    # Create and set enabled ru and en locales
    FactoryGirl.create :localization, name: 'ru', enable: true, language: en
    FactoryGirl.create :localization, name: 'en', enable: true, language: ru
  end

  config.after(:each) do
    DatabaseCleaner.clean
    ::Mongoid::Sessions.default.drop # DatabaseCleaner.clean not working with mongodb 3.2 and mongoid 4.x. need migrate to mongoid 5
    ActionMailer::Base.deliveries.clear
  end

  # RSpec Rails can automatically mix in different behaviours to your tests
  # based on their file location, for example enabling you to call `get` and
  # `post` in specs under `spec/controllers`.
  #
  # You can disable this behaviour by removing the line below, and instead
  # explicitly tag your specs with their type, e.g.:
  #
  #     RSpec.describe UsersController, :type => :controller do
  #       # ...
  #     end
  #
  # The different available types are documented in the features, such as in
  # https://relishapp.com/rspec/rspec-rails/docs
  config.infer_spec_type_from_file_location!
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000000"
    android:orientation="vertical" >
    <com.cpic.carmarket.view.ZoomImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/zoom_view"
        android:scaleType="matrix"/>

</LinearLayout>


text:
namespace Cofoundry.Domain;

/// <summary>
/// Publishes a page. If the page is already published and
/// a date is specified then the publish date will be updated.
/// </summary>
public class PublishPageCommand : ICommand, ILoggableCommand
{
    /// <summary>
    /// Publishes a page. If the page is already published and
    /// a date is specified then the publish date will be updated.
    /// </summary>
    public PublishPageCommand()
    {
    }

    /// <summary>
    /// Publishes a page. If the page is already published and
    /// a date is specified then the publish date will be updated.
    /// </summary>
    /// <param name="pageId">The database id of the page to publish.</param>
    /// <param name="publishDate">
    /// Optional date-time that the page should be published and made public. If
    /// this is left null then the publish date is set to the current
    /// date and the page is made immediately available.
    /// </param>
    public PublishPageCommand(int pageId, DateTime? publishDate = null)
    {
        PageId = pageId;
        PublishDate = publishDate;
    }

    /// <summary>
    /// The database id of the page to publish.
    /// </summary>
    [PositiveInteger]
    [Required]
    public int PageId { get; set; }

    /// <summary>
    /// Optional time that the page should be published and made public. If
    /// this is left <see langword="null"/> then the publish date is set to the current
    /// date and the page is made immediately available.
    /// </summary>
    public DateTime? PublishDate { get; set; }
}


text:
package models.moneyservicebusiness

import jto.validation._
import jto.validation.forms.UrlFormEncoded
import org.scalatest.MustMatchers
import org.scalatestplus.play.PlaySpec

class BranchesOrAgentsHasCountriesSpec extends PlaySpec with MustMatchers{

  "MsbServices" must {

    val rule = implicitly[Rule[UrlFormEncoded, BranchesOrAgentsHasCountries]]
    val write = implicitly[Write[BranchesOrAgentsHasCountries, UrlFormEncoded]]

    "round trip through forms correctly" in {

      val model: BranchesOrAgentsHasCountries = BranchesOrAgentsHasCountries(true)
      rule.validate(write.writes(model)) mustBe Valid(model)
    }

    "successfully validate when hasCountries is false" in {

      val form: UrlFormEncoded = Map(
        "hasCountries" -> Seq("false")
      )

      val model: BranchesOrAgentsHasCountries = BranchesOrAgentsHasCountries(false)

      rule.validate(form) mustBe Valid(model)
    }

    "fail to validate when hasCountries isn't selected" in {

      val form: UrlFormEncoded = Map.empty

      rule.validate(form) mustBe Invalid(
        Seq((Path \ "hasCountries") -> Seq(ValidationError("error.required.hasCountries.msb.branchesOrAgents")))
      )
    }

    "test" in {
      val form: UrlFormEncoded = Map("hasCountries" -> Seq("true"))
      rule.validate(form) mustBe Valid(BranchesOrAgentsHasCountries(true))
    }
  }
}


text:
package gov.nih.nci.ccts.grid.smoketest.service.globus;

import java.rmi.RemoteException;
import javax.security.auth.Subject;
import javax.xml.namespace.QName;
import javax.xml.rpc.handler.MessageContext;

import org.globus.wsrf.impl.security.authorization.exceptions.AuthorizationException;
import org.globus.wsrf.impl.security.authorization.exceptions.CloseException;
import org.globus.wsrf.impl.security.authorization.exceptions.InitializeException;
import org.globus.wsrf.impl.security.authorization.exceptions.InvalidPolicyException;
import org.globus.wsrf.security.authorization.PDP;
import org.globus.wsrf.security.authorization.PDPConfig;
import org.w3c.dom.Node;

/**
 * DO NOT EDIT:  This class is autogenerated!
 *
 * This is a PDP for use with the globus authorization callout.
 * This class will have a authorize<methodName> method for each method on this grid service.
 * The method is responsibe for making any authorization callouts required to satisfy the
 * authorization requirements placed on each method call.  Each method will either return
 * apon a successful authorization or will throw an exception apon a failed authorization.
 *
 * @created by Introduce Toolkit version 1.2
 *
 */
public class SmokeTestServiceAuthorization implements PDP {

	public static final String SERVICE_NAMESPACE = "http://smoketest.grid.ccts.nci.nih.gov/SmokeTestService";

	public SmokeTestServiceAuthorization() {
	}

	protected String getServiceNamespace(){
		return SERVICE_NAMESPACE;
	}

	public static String getCallerIdentity() {
		String caller = org.globus.wsrf.security.SecurityManager.getManager().getCaller();
		if ((caller == null) || (caller.equals("<anonymous>"))) {
			return null;
		} else {
			return caller;
		}
	}

	public static void authorizeGetMultipleResourceProperties() throws RemoteException {

	}

	public static void authorizeGetResourceProperty() throws RemoteException {

	}

	public static void authorizeQueryResourceProperties() throws RemoteException {

	}

	public static void authorizeGetServiceSecurityMetadata() throws RemoteException {

	}

	public static void authorizePing() throws RemoteException {

	}

	public boolean isPermitted(Subject peerSubject, MessageContext context, QName operation)
		throws AuthorizationException {

		if(!operation.getNamespaceURI().equals(getServiceNamespace())){
		  return false;
		}
		if(operation.getLocalPart().equals("getMultipleResourceProperties")){
			try{
				authorizeGetMultipleResourceProperties();
				return true;
			} catch (Exception e){
				e.printStackTrace();
				return false;
			}
		} else if(operation.getLocalPart().equals("getResourceProperty")){
			try{
				authorizeGetResourceProperty();
				return true;
			} catch (Exception e){
				e.printStackTrace();
				return false;
			}
		} else if(operation.getLocalPart().equals("queryResourceProperties")){
			try{
				authorizeQueryResourceProperties();
				return true;
			} catch (Exception e){
				e.printStackTrace();
				return false;
			}
		} else if(operation.getLocalPart().equals("getServiceSecurityMetadata")){
			try{
				authorizeGetServiceSecurityMetadata();
				return true;
			} catch (Exception e){
				e.printStackTrace();
				return false;
			}
		} else if(operation.getLocalPart().equals("ping")){
			try{
				authorizePing();
				return true;
			} catch (Exception e){
				e.printStackTrace();
				return false;
			}
		}
		return false;
	}

	public Node getPolicy(Node query) throws InvalidPolicyException {
		return null;
	}

	public String[] getPolicyNames() {
		return null;
	}

	public Node setPolicy(Node policy) throws InvalidPolicyException {
		return null;
	}

	public void close() throws CloseException {

	}

	public void initialize(PDPConfig config, String name, String id) throws InitializeException {

	}

}


text:
title: "Hacker Tools: CLI debugging and profiling"
date: 2021-10-19 21:00:00
author: Hao Wei
url: /2021/10/hacker-tools-7
summary: Come learn how to debug and profile various things on Linux, all from the command line.
---

This workshop has ended; here are links to the materials and recording:

- [Slides](https://nushackers.github.io/hackertools-slides/2110ht7/)
- [Recording](https://www.youtube.com/watch?v=maISKQl7rIo)

**Date/Time**: Wednesday, 27 Oct 2021, 19:00–21:00

Come learn how to debug and profile various things on Linux, all from the command line. We'll look at how to figure out what's going wrong with programs you write and the operating system itself.

Please ensure you have access to **real Linux**. If you are on a Linux distribution, you are set; if you use Windows or Mac, consider installing Ubuntu in a virtual machine like VirtualBox. If you are on Windows, you can also use Windows Subsystem for Linux 2. (**WSL 1 is not suitable.**)

- WSL: https://docs.microsoft.com/en-us/windows/wsl/install-win10

Please make sure you have the following programs installed in your Linux system:

- Git, Perl 5, Python 3, gdb, strace, ltrace, Valgrind, GCC, perf (Linux kernel), htop, dstat, iotop, df, du, free, lsof, ss, stress, s-tui
- On Ubuntu, the following packages: gdb strace ltrace valgrind linux-tools htop dstat iotop lsof iproute2 stress s-tui procps build-essential python3 perl git
- On Arch Linux, the following packages: gdb strace ltrace valgrind perf htop dstat iotop lsof iproute2 stress s-tui procps-ng base-devel python perl git

This workshop is largely based on the Missing Semester of Your CS Education lecture series conducted in MIT. This week's topic is based on https://missing.csail.mit.edu/2020/debugging-profiling/.

See you there!


text:
import { Dimensions } from 'react-native'
import theme from '../../common/theme'

const screenWidth = Dimensions.get('window').width

export default {
  container: {
    paddingTop: 20,
    position: 'absolute',
    top: 0,
    height: 65,
    width: screenWidth,
    backgroundColor: theme.main,
    justifyContent: 'center',
    alignItems: 'center'
  },
  text: {
    backgroundColor: 'transparent',
    color: 'white',
    fontFamily: theme.fontHeader,
    // fontStyle: 'italic',
    fontSize: 22
  }
}


text:
package ameba.util;

import java.io.Serializable;
import java.net.URL;
import java.util.Comparator;

/**
 *
UrlExternalFormComparator class.

 *
 * @author icode
 * request
 */
public class UrlExternalFormComparator implements Comparator<URL>, Serializable
{
    /**
     * {@inheritDoc}
     */
    @Override
    public int compare(URL url1, URL url2)
    {
        return url1.toExternalForm().compareTo(url2.toExternalForm());
    }
}


text:
import itertools
import numbers
import numpy
import numpy.linalg
import weakref

class ConstraintLayout:
  def __init__(self, axes_count, length_count=0):
    rect_count = axes_count + 1
    self.coord_count = 4 * rect_count
    length_count += self.coord_count

    coeffs_list = numpy.eye(length_count, length_count+1)
    length_exprs = [LengthExpr(self, coeffs) for coeffs in coeffs_list]

    self.figure = Rectangle(length_exprs[:4])
    self.axes = [Rectangle(length_expr_tuple) for
      length_expr_tuple in iterate_tuple(length_exprs[4:self.coord_count], 4)]
    self.lengths = length_exprs[self.coord_count:]

    self.lhs = numpy.empty((length_count, length_count))
    self.rhs = numpy.empty(length_count)
    self.lhs[:2] = self.rhs[:2] = 0
    self.lhs[0, 0] = self.lhs[1, 1] = 1
    self.curr_constraint = 2

  @staticmethod
  def set_same_size(rects):
    first_rect = rects[0]
    for rect in rects[1:]:
      first_rect.dx.set_equal(rect.dx)
      first_rect.dy.set_equal(rect.dy)

  @staticmethod
  def place_on_grid(rects, nx, ny, sx, sy, include_size=True):
    if nx * ny != len(rects):
      raise ValueError(
        'grid of size ({}, {}) cannot be filled with {} rectangles'
        .format(nx, ny, len(rects)))

    if isinstance(sx, str) or not hasattr(sx, '__iter__'):
      sx = [sx]
    if isinstance(sy, str) or not hasattr(sy, '__iter__'):
      sy = [sy]

    def delayed(iterable):
      yield None
      yield from iterable

    for i, sy_ in zip(range(ny), delayed(itertools.cycle(sy))):
      for j, sx_ in zip(range(nx), delayed(itertools.cycle(sx))):
        rect = rects[i*nx+j]
        if i > 0:
          above_rect = rects[(i-1)*nx+j]
          rect.x1.set_equal(above_rect.x1)
          if include_size:
            rect.y1.set_equal(above_rect.y2 + sy_)
          else:
            rect.y1.set_equal(above_rect.y1 + sy_)
        elif j > 0:
          left_rect = rects[i*nx+(j-1)]
          if include_size:
            rect.x1.set_equal(left_rect.x2 + sx_)
          else:
            rect.x1.set_equal(left_rect.x1 + sx_)
          rect.y1.set_equal(left_rect.y1)

  def add_constraint(self, lhs, rhs):
    if self.curr_constraint >= self.lhs.shape[0]:
      raise ValueError('too many constraints have been specified')

    self.lhs[self.curr_constraint] = lhs
    self.rhs[self.curr_constraint] = rhs
    self.curr_constraint += 1

  def solve(self):
    if self.curr_constraint < self.lhs.shape[0]:
      raise ValueError('{} more constraint(s) must be specified'
        .format(self.lhs.shape[0] - self.curr_constraint))

    try:
      singular_values = numpy.linalg.svd(self.lhs, compute_uv=False)
    except numpy.linalg.LinAlgError:
      raise ValueError('constraints are singular')
    else:
      if min(singular_values) / max(singular_values) < 1e-6:
        raise ValueError('constraints are ill-conditioned')

    try:
      solution = numpy.linalg.solve(self.lhs, self.rhs)
    except numpy.linalg.LinAlgError:
      raise ValueError('constraints are singular')

    self.coords = list(iterate_tuple(solution[:self.coord_count], 4))

    for n ,coords in enumerate(self.coords):
      print('{} | {:7.4f} {:7.4f} {:7.4f} {:7.4f} | {:7.4f} {:7.4f}'.format(
        '{:2d}'.format(n-1) if n > 0 else '  ',
        coords[0], coords[1], coords[2], coords[3],
        coords[2]-coords[0], coords[3]-coords[1]))

  def apply(self, figure=None):
    if not hasattr(self, 'coords'):
      self.solve()

    figure_dx, figure_dy = self.coords[0][2:]
    if figure:
      figure.set_size_inches(figure_dx, figure_dy, forward=True)
    else:
      from matplotlib import pyplot
      figure = pyplot.figure(figsize=(figure_dx, figure_dy))

    for x1, y1, x2, y2 in self.coords[1:]:
      figure.add_axes(
        (x1/figure_dx, 1-y2/figure_dy, (x2-x1)/figure_dx, (y2-y1)/figure_dy))

class Rectangle:
  def __init__(self, length_exprs):
    self.x1, self.y1, self.x2, self.y2 = length_exprs
    self.dx = self.x2 - self.x1
    self.dy = self.y2 - self.y1

class LengthExpr:
  def __init__(self, layout, coeffs):
    if isinstance(layout, weakref.ref):
      self.layout = layout
    else:
      self.layout = weakref.ref(layout)
    self.coeffs = coeffs

  def __pos__(self):
    return LengthExpr(self.layout, numpy.copy(self.coeffs))

  def __neg__(self):
    return LengthExpr(self.layout, -self.coeffs)

  def __add__(self, other):
    if isinstance(other, LengthExpr) and self.layout is other.layout:
      return LengthExpr(self.layout, self.coeffs + other.coeffs)
    elif isinstance(other, numbers.Number):
      coeffs = numpy.copy(self.coeffs)
      coeffs[-1] += other
      return LengthExpr(self.layout, coeffs)
    elif isinstance(other, str):
      return self + parse_length(other)
    return NotImplemented

  def __sub__(self, other):
    if isinstance(other, LengthExpr) and self.layout is other.layout:
      return LengthExpr(self.layout, self.coeffs - other.coeffs)
    elif isinstance(other, numbers.Number):
      coeffs = numpy.copy(self.coeffs)
      coeffs[-1] -= other
      return LengthExpr(self.layout, coeffs)
    elif isinstance(other, str):
      return self - parse_length(other)
    return NotImplemented

  def __mul__(self, other):
    if isinstance(other, numbers.Number):
      return LengthExpr(self.layout, self.coeffs * other)
    return NotImplemented

  def __truediv__(self, other):
    if isinstance(other, numbers.Number):
      return LengthExpr(self.layout, self.coeffs / other)
    return NotImplemented

  def __radd__(self, other):
    if isinstance(other, numbers.Number):
      return self + other
    elif isinstance(other, str):
      return self + parse_length(other)
    return NotImplemented

  def __rsub__(self, other):
    if isinstance(other, numbers.Number):
      return -self + other
    elif isinstance(other, str):
      return -self + parse_length(other)
    return NotImplemented

  def __rmul__(self, other):
    if isinstance(other, numbers.Number):
      return self * other
    return NotImplemented

  def set_equal(self, other):
    if isinstance(other, LengthExpr):
      coeffs = self.coeffs - other.coeffs
      self.layout().add_constraint(coeffs[:-1], -coeffs[-1])
    elif isinstance(other, numbers.Number):
      self.layout().add_constraint(self.coeffs[:-1], other - self.coeffs[-1])
    elif isinstance(other, str):
      return self.set_equal(parse_length(other))
    else:
      raise TypeError("length cannot be set equal to type '{}'"
        .format(type(other).__name__))

def iterate_tuple(iterable, count):
  return itertools.zip_longest(*[iter(iterable)] * count)

def parse_length(string):
  units = {'in': 1, 'cm': 1/2.54, 'pt': 1/72}
  string = string.rstrip()
  for unit, conversion in units.items():
    if string.endswith(unit):
      return float(string[:-len(unit)]) * conversion
  raise ValueError("string '{}' does not represent a length".format(string))


text:
package org.apache.arrow.driver.jdbc.accessor.impl.complex;

import java.util.function.IntSupplier;

import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessor;
import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory;
import org.apache.arrow.vector.ValueVector;
import org.apache.arrow.vector.complex.UnionVector;

/**
 * Accessor for the Arrow type {@link UnionVector}.
 */
public class ArrowFlightJdbcUnionVectorAccessor extends AbstractArrowFlightJdbcUnionVectorAccessor {

  private final UnionVector vector;

  /**
   * Instantiate an accessor for a {@link UnionVector}.
   *
   * @param vector             an instance of a UnionVector.
   * @param currentRowSupplier the supplier to track the rows.
   * @param setCursorWasNull   the consumer to set if value was null.
   */
  public ArrowFlightJdbcUnionVectorAccessor(UnionVector vector, IntSupplier currentRowSupplier,
                                            ArrowFlightJdbcAccessorFactory.WasNullConsumer setCursorWasNull) {
    super(currentRowSupplier, setCursorWasNull);
    this.vector = vector;
  }

  @Override
  protected ArrowFlightJdbcAccessor createAccessorForVector(ValueVector vector) {
    return ArrowFlightJdbcAccessorFactory.createAccessor(vector, this::getCurrentRow,
        (boolean wasNull) -> {
        });
  }

  @Override
  protected byte getCurrentTypeId() {
    int index = getCurrentRow();
    return (byte) this.vector.getTypeValue(index);
  }

  @Override
  protected ValueVector getVectorByTypeId(byte typeId) {
    return this.vector.getVectorByType(typeId);
  }
}


text:
package org.apache.accumulo.core.client.impl;

import java.util.Iterator;
import java.util.Map.Entry;
import java.util.concurrent.TimeUnit;

import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.client.Instance;
import org.apache.accumulo.core.client.Scanner;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.security.Authorizations;
import org.apache.accumulo.core.security.thrift.TCredentials;
import org.apache.accumulo.core.util.ArgumentChecker;
import org.apache.hadoop.io.Text;

/**
 * provides scanner functionality
 *
 * "Clients can iterate over multiple column families, and there are several
 * mechanisms for limiting the rows, columns, and timestamps traversed by a
 * scan. For example, we could restrict [a] scan ... to only produce anchors
 * whose columns match [a] regular expression ..., or to only produce
 * anchors whose timestamps fall within ten days of the current time."
 *
 */
public class ScannerImpl extends ScannerOptions implements Scanner {

  // keep a list of columns over which to scan
  // keep track of the last thing read
  // hopefully, we can track all the state in the scanner on the client
  // and just query for the next highest row from the tablet server

  private Instance instance;
  private TCredentials credentials;
  private Authorizations authorizations;
  private Text table;

  private int size;

  private Range range;
  private boolean isolated = false;

  public ScannerImpl(Instance instance, TCredentials credentials, String table, Authorizations authorizations) {
    ArgumentChecker.notNull(instance, credentials, table, authorizations);
    this.instance = instance;
    this.credentials = credentials;
    this.table = new Text(table);
    this.range = new Range((Key) null, (Key) null);
    this.authorizations = authorizations;

    this.size = Constants.SCAN_BATCH_SIZE;
  }

  @Override
  public synchronized void setRange(Range range) {
    ArgumentChecker.notNull(range);
    this.range = range;
  }

  @Override
  public synchronized Range getRange() {
    return range;
  }

  @Override
  public synchronized void setBatchSize(int size) {
    if (size > 0)
      this.size = size;
    else
      throw new IllegalArgumentException("size must be greater than zero");
  }

  @Override
  public synchronized int getBatchSize() {
    return size;
  }

  /**
   * Returns an iterator over an accumulo table. This iterator uses the options that are currently set on the scanner for its lifetime. So setting options on a
   * Scanner object will have no effect on existing iterators.
   */
  @Override
  public synchronized Iterator<Entry<Key,Value>> iterator() {
    return new ScannerIterator(instance, credentials, table, authorizations, range, size, getTimeOut(), this, isolated);
  }

  @Override
  public synchronized void enableIsolation() {
    this.isolated = true;
  }

  @Override
  public synchronized void disableIsolation() {
    this.isolated = false;
  }

  @Deprecated
  @Override
  public void setTimeOut(int timeOut) {
    if (timeOut == Integer.MAX_VALUE)
      setTimeout(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
    else
      setTimeout(timeOut, TimeUnit.SECONDS);
  }

  @Deprecated
  @Override
  public int getTimeOut() {
    long timeout = getTimeout(TimeUnit.SECONDS);
    if (timeout >= Integer.MAX_VALUE)
      return Integer.MAX_VALUE;
    return (int) timeout;
  }
}


text:
<?php

namespace NCMF\DefaultBundle\Controller;

use NCMF\DefaultBundle\Entity\ObjectField;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

/**
 * Objectfield controller.
 *
 */
class ObjectFieldController extends Controller
{
    /**
     * Lists all objectField entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $objectFields = $em->getRepository('NCMFDefaultBundle:ObjectField')->findAll();

        return $this->render('objectfield/index.html.twig', array(
            'objectFields' => $objectFields,
        ));
    }

    /**
     * Creates a new objectField entity.
     *
     */
    public function newAction(Request $request)
    {
        $objectField = new Objectfield();
        $form = $this->createForm('NCMF\DefaultBundle\Form\ObjectFieldType', $objectField);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($objectField);
            $em->flush($objectField);

            return $this->redirectToRoute('admin_objectfield_show', array('id' => $objectField->getId()));
        }

        return $this->render('objectfield/new.html.twig', array(
            'objectField' => $objectField,
            'form' => $form->createView(),
        ));
    }

    /**
     * Finds and displays a objectField entity.
     *
     */
    public function showAction(ObjectField $objectField)
    {
        $deleteForm = $this->createDeleteForm($objectField);

        return $this->render('objectfield/show.html.twig', array(
            'objectField' => $objectField,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing objectField entity.
     *
     */
    public function editAction(Request $request, ObjectField $objectField)
    {
        $deleteForm = $this->createDeleteForm($objectField);
        $editForm = $this->createForm('NCMF\DefaultBundle\Form\ObjectFieldType', $objectField);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('admin_objectfield_edit', array('id' => $objectField->getId()));
        }

        return $this->render('objectfield/edit.html.twig', array(
            'objectField' => $objectField,
            'edit_form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Deletes a objectField entity.
     *
     */
    public function deleteAction(Request $request, ObjectField $objectField)
    {
        $form = $this->createDeleteForm($objectField);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->remove($objectField);
            $em->flush($objectField);
        }

        return $this->redirectToRoute('admin_objectfield_index');
    }

    /**
     * Creates a form to delete a objectField entity.
     *
     * @param ObjectField $objectField The objectField entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(ObjectField $objectField)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin_objectfield_delete', array('id' => $objectField->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
}


text:
Saturn is a system that allows system administrators to quickly gather information and statistics about their systems.

## Install

All you need to get started is the release package found under Releases. It contains the binary for the cli client, and the license and readme files.

## Build

Run `go get github.com/usi-lfkeitel/saturn/cmd/saturn` or clone the repo to the appropriate place in your $GOPATH and run `make generate && make`. A binary will be created at `./bin/saturn`.

## Configuration

Saturn requires a TOML configuration file to run. This specifies SSH connection parameters, application settings, and hosts. Here's a sample configuration:

```
[core]

[SSH]
Username = "jsmith"
#Password = ""
PrivateKey = "/home/jsmith/.ssh/id_rsa"
UseAgent = true # Use an SSH agent with the environment variable SSH_AUTH_SOCK

[[hosts]]
name = "Localhost"
address = "localhost"

[[hosts]]
name = "Server1"
address = "192.168.1.1"

[[hosts]]
name = "Server2"
address = "192.168.1.2"
```

Please refer to the example configuration file for details on all available settings.

## Running Saturn

So, you have your configuration ready with all your hosts defined. Now let's actually get some data. Here's all the flags that Saturn can use:

- `-c`:  Configuration file to use.
- `-d,-dd`: Enable debug mode
- `-limit host1,host2`:  Comma separated list of hosts to run on. Use this option for quick data grabs without having to disable
all clients in a configuration. Listed clients will be used except those disabled by the config.
- `-list`: List available modules.
- `-m,-module module1, module2`: Comma separated list of modules to run.
- `-o MODE`:  Output mode. One of: json, plain (default)
- `-s`:  Print shorter output. Only affects plain output mode.
- `-v`:  Print version information.

Here's a quick demo:

`./saturn -c config.toml -limit Server1 -m io_stats,cpu_info`

This will run the io\_stats and cpu\_info modules only on Server1 (unless it's disabled in the config). It will then output
information from the modules in a structured, readable format.

## Modules

Saturn is based on a set of modules which are nothing more than shell scripts that output JSON. The modules are embedded into the
binary at build time. Custom modules can be used by placing them in the modules directory set in the configuration file. Module
named are based on their file name so it's recommended to keep them sort and use only alphanumeric characters, underscores, or
hyphens. Other characters are not guaranteed to work. Custom modules cannot override builtin modules.

A module file must output only JSON to stdout. A module may output either a JSON array or object. Please refer to the module
headers section below for details.

Here's a list of first-party modules:

- **arp_cache**:
- **bandwidth**:
- **common_applications**:
- **cpu_info**:
- **cpu_intensive_processes**:
- **cpu_temp**:
- **cpu_utilization**:
- **cron_history**:
- **current_ram**:
- **disk_partitions**:
- **docker_processes**:
- **download_transfer_rate**:
- **enabled_services**:
- **general_info**:
- **io_stats**:
- **listening_ports**:
- **load_avg**:
- **logged_in_users**:
- **memcached**:
- **memory_info**:
- **needs_upgrades**:
- **network_connections**:
- **network_interfaces**:
- **number_of_cpu_cores**:
- **ping**:
- **pm2_stats**:
- **ram_intensive_processes**:
- **recent_account_logins**:
- **redis**:
- **scheduled_crons**:
- **swap**:
- **upload_transfer_rate**:
- **user_accounts**:

### Module Headers

A module file must have a metadata comment on the second line so it can be added to the binary.

There are two forms, a short form and long form. The short form is used to return a simple array or objects or a single object.
The syntax of this line is as follows: `#gen:module [a|o] key1:type1,key2:type2,...`. The first parameter is
either "a" or "o" depending on if the module outputs a JSON [a]rray or [o]bject. The letter must be lower-case.
The key type pairs specify the schema of the JSON. Keys cannot start with a number
or a comma/semicolon. Supported types are `string`, `int`, `bool`, and `float64`. The key names will be transformed as needed to
conform with Go's variable naming syntax.

Here's an example from the cron module: `#gen:module a time:string,user:string,message:string`

The long form is needed when the returned JSON is more complex for example return an object with values that are themselves
objects.

Here's an example of long form:

```
#gen:module2 a
#type address
#  address string
#  broadcast string
#  mask string
#endtype
#key interface string
#key mac_address string
#key ipv4 []address
#key ipv6 []address
#!gen:module2
```

The pound sign at the beginning of each line is required as the modules must be valid scripts.

The metadata block is defined between `#gen:module2 [a|o]` and `#!gen:module2`. The a|o have the same
meaning as the simple form. Whether the module will return an array of objects with the defined keys,
or a single object with the keys.

Each complex type is defined with a type/endtype block. The identifier after `type` is the name of that type.
Key names and types are separated by newlines until endtype. A type cannot be defined inside another type but
a type can be used in another type. All types must be defined. A key can also be an array of TYPE like `ipv4`
above is an array of the type `address`.


text:
namespace aura {

ScopedWindowTargeter::ScopedWindowTargeter(
    Window* window,
    scoped_ptr<ui::EventTargeter> new_targeter)
    : window_(window),
      old_targeter_(window->SetEventTargeter(std::move(new_targeter))) {
  window_->AddObserver(this);
}

ScopedWindowTargeter::~ScopedWindowTargeter() {
  if (window_) {
    window_->RemoveObserver(this);
    window_->SetEventTargeter(std::move(old_targeter_));
  }
}

void ScopedWindowTargeter::OnWindowDestroyed(Window* window) {
  CHECK_EQ(window_, window);
  window_ = NULL;
  old_targeter_.reset();
}

}  // namespace aura


text:
import os.path

from .tree_construction import TreeConstructionFile
from .tokenizer import TokenizerFile
from .sanitizer import SanitizerFile

_dir = os.path.abspath(os.path.dirname(__file__))
_testdata = os.path.join(_dir, "testdata")
_tree_construction = os.path.join(_testdata, "tree-construction")
_tokenizer = os.path.join(_testdata, "tokenizer")
_sanitizer_testdata = os.path.join(_dir, "sanitizer-testdata")

def pytest_collectstart():
    """check to see if the git submodule has been init'd"""
    pass

def pytest_collect_file(path, parent):
    dir = os.path.abspath(path.dirname)
    if dir == _tree_construction:
        if path.basename == "template.dat":
            return
        if path.ext == ".dat":
            return TreeConstructionFile(path, parent)
    elif dir == _tokenizer:
        if path.ext == ".test":
            return TokenizerFile(path, parent)
    elif dir == _sanitizer_testdata:
        if path.ext == ".dat":
            return SanitizerFile(path, parent)


text:
var bcrypt = require('bcrypt');

/**
 * Passport Model
 *
 * The Passport model handles associating authenticators with users. An authen-
 * ticator can be either local (password) or third-party (provider). A single
 * user can have multiple passports, allowing them to connect and use several
 * third-party strategies in optional conjunction with a password.
 *
 * Since an application will only need to authenticate a user once per session,
 * it makes sense to encapsulate the data specific to the authentication process
 * in a model of its own. This allows us to keep the session itself as light-
 * weight as possible as the application only needs to serialize and deserialize
 * the user, but not the authentication data, to and from the session.
 */
var Passport = {

  attributes: {

    // Required field: Protocol
    //
    // Defines the protocol to use for the passport. When employing the local
    // strategy, the protocol will be set to 'local'. When using a third-party
    // strategy, the protocol will be set to the standard used by the third-
    // party service (e.g. 'oauth', 'oauth2', 'openid').
    protocol: { type: 'string', required: true },

    // Local field: Password
    //
    // When the local strategy is employed, a password will be used as the
    // means of authentication along with either a username or an email.
    password: { type: 'string', minLength: 8 },

    // Provider fields: Provider, identifer and tokens
    //
    // "provider" is the name of the third-party auth service in all lowercase
    // (e.g. 'github', 'facebook') whereas "identifier" is a provider-specific
    // key, typically an ID. These two fields are used as the main means of
    // identifying a passport and tying it to a local user.
    //
    // The "tokens" field is a JSON object used in the case of the OAuth stan-
    // dards. When using OAuth 1.0, a `token` as well as a `tokenSecret` will
    // be issued by the provider. In the case of OAuth 2.0, an `accessToken`
    // and a `refreshToken` will be issued.
    provider   : { type: 'string' },
    identifier : { type: 'string' },
    tokens     : { type: 'json' },

    // Associations
    //
    // Associate every passport with one, and only one, user. This requires an
    // adapter compatible with associations.
    //
    // For more information on associations in Waterline, check out:
    // https://github.com/balderdashy/waterline
    user: { model: 'User' },

    /**
     * Validate password used by the local strategy.
     *
     * @param {string}   password The password to validate
     * @param {Function} next
     */
    validatePassword: function (password, next) {
      bcrypt.compare(password, this.password, next);
      console.log('password ,this ',password,this.password)

    }

  },

  /**
   * Callback to be run before creating a Passport.
   *
   * @param {Object}   passport The soon-to-be-created Passport
   * @param {Function} next
   */
  beforeCreate: function (passport, next) {
    if (passport.hasOwnProperty('password')) {
      bcrypt.hash(passport.password, 10, function (err, hash) {
        passport.password = hash;
          console.log('password1 ,this ',password,this.password)
          next(err, passport);
      });
    } else {
      next(null, passport);
    }
  },

  /**
   * Callback to be run before updating a Passport.
   *
   * @param {Object}   passport Values to be updated
   * @param {Function} next
   */
  beforeUpdate: function (passport, next) {
    if (passport.hasOwnProperty('password')) {
      bcrypt.hash(passport.password, 10, function (err, hash) {
        passport.password = hash;
          console.log('password2 ,this ',password,this.password)
          next(err, passport);
      });
    } else {
      next(null, passport);
    }
  }
};

module.exports = Passport;


text:
---
title: spring中BeanWrapper对象的理解
tags: [spring]
---

参考:https://blog.csdn.net/zhiweianran/article/details/7919129

1)BeanWrapper的介绍

BeanWrapper大部分情况下是在spring-ioc内部进行使用,通过BeanWrapper,spring-ioc容器可以用统一的方式来访问bean的属性。用户很少需要直接使用BeanWrapper进行编程。

BeanWrapper是对Bean的包装,其接口中所定义的功能很简单包括设置获取被包装的对象,获取被包装bean的属性描述器,由于BeanWrapper接口是PropertyAccessor的子接口,因此其也可以设置以及访问被包装对象的属性值。

2)BeanWrapperImpl类

BeanWrapperImpl类是对BeanWrapper接口的默认实现,它包装了一个bean对象,缓存了bean的内省结果,并可以访问bean的属性、设置bean的属性值。

BeanWrapperImpl类的内部结构信息

```
/** The wrapped object */
private Object object;//封装的实体对象

private String nestedPath = "";//嵌套路径

private Object rootObject;//根对象

private AccessControlContext acc;

/**
 * Cached introspections results for this object, to prevent encountering
 * the cost of JavaBeans introspection every time.
   缓存类的内省信息
 */
private CachedIntrospectionResults cachedIntrospectionResults;

/**
 * Map with cached nested BeanWrappers: nested path -> BeanWrapper instance.
 */
private Map<String, BeanWrapperImpl> nestedBeanWrappers;

private boolean autoGrowNestedPaths = false;

private int autoGrowCollectionLimit = Integer.MAX_VALUE;
```

3)查看BeanWrapperImpl的使用

AbstractAutowireCapableBeanFactory类的instantiateBean方法返回BeanWrapper实例,内部使用BeanWrapperImpl作为其实现类。

```
beanInstance=...//实例化对象后
//使用BeanWrapperImpl包装对象
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
```

查看构造函数

```
public BeanWrapperImpl(Object object) {
    registerDefaultEditors();//内部设置属性defaultEditorsActive值为true
    setWrappedInstance(object);
}
```