ronantakizawa/codereview-bench huggingface dataset:
Repository: Azure/azure-sdk-for-net
File: sdk/provisioning/Azure.Provisioning/src/Primitives/BicepMetadata.cs (C#)

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

namespace Azure.Provisioning.Primitives;

/// <summary>
/// Represents Bicep metadata and annotations that can be applied to resources.
/// These control how resources are rendered in Bicep but are not part of the
/// Azure resource definition itself.
/// </summary>
public class BicepMetadata
{
    /// <summary>
    /// Optional description for the resource that appears as a @description decorator.
    /// </summary>
    public string? Description { get; set; }

    /// <summary>
    /// Optional condition string for conditional resource deployment.
    /// If set, the resource will be wrapped in an 'if (condition)' statement.
    /// The condition is used as-is without validation.
    /// </summary>
    public string? Condition { get; set; }

    /// <summary>
    /// Optional batch size for resource deployment.
    /// If set, adds a @batchSize(n) decorator to control parallel deployment batching.
    /// </summary>
    public uint? BatchSize { get; set; }

    /// <summary>
    /// If true, adds a @onlyIfNotExists() decorator to the resource.
    /// This prevents recreation of the resource if it already exists.
    /// </summary>
    public bool OnlyIfNotExists { get; set; }
}


Review comment (suggestion):
First of all I am not sure if this feature would be implemented in this way - this is not following the pattern for the existing part of this like `existing` which is implemented by static method generated in all resources `FromExisting`.

But this `Condition` should have a type of `BicepValue<bool>` which would support a literal value of `true` and an expression.

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

namespace Azure.Provisioning.Primitives;

/// <summary>
/// Represents Bicep metadata and annotations that can be applied to resources.
/// These control how resources are rendered in Bicep but are not part of the
/// Azure resource definition itself.
/// </summary>
public sealed class BicepMetadata
{
    /// <summary>
    /// Optional description for the resource that appears as a @description decorator.
    /// </summary>
    public string? Description { get; set; }

    /// <summary>
    /// Optional batch size for resource deployment.
    /// If set, adds a @batchSize(n) decorator to control parallel deployment batching.
    /// </summary>
    public uint? BatchSize { get; set; }

    /// <summary>
    /// If true, adds a @onlyIfNotExists() decorator to the resource.
    /// This prevents recreation of the resource if it already exists.
    /// </summary>
    public bool OnlyIfNotExists { get; set; }
}
Repository: Azure/azure-sdk-for-net
File: eng/packages/http-client-csharp-mgmt/generator/TestProjects/Local/Mgmt-TypeSpec/src/Generated/Models/SafeFlattenModel.cs (C#)

Code before:
namespace Azure.Generator.MgmtTypeSpec.Tests.Models
{
    /// <summary> The SafeFlattenModel. </summary>
    internal partial class SafeFlattenModel
    {
        /// <summary> Keeps track of any properties unknown to the library. </summary>
        private protected readonly IDictionary<string, BinaryData> _additionalBinaryDataProperties;

        /// <summary> Initializes a new instance of <see cref="SafeFlattenModel"/>. </summary>
        public SafeFlattenModel()
        {
            FlattenedProperty = new ChangeTrackingList<string>();
        }

        /// <summary> Initializes a new instance of <see cref="SafeFlattenModel"/>. </summary>
        /// <param name="flattenedProperty"></param>
        /// <param name="additionalBinaryDataProperties"> Keeps track of any properties unknown to the library. </param>
        internal SafeFlattenModel(IList<string> flattenedProperty, IDictionary<string, BinaryData> additionalBinaryDataProperties)
        {
            FlattenedProperty = flattenedProperty;
            _additionalBinaryDataProperties = additionalBinaryDataProperties;
        }

        /// <summary> Gets the FlattenedProperty. </summary>
        [WirePath("flattenedProperty")]
        public IList<string> FlattenedProperty { get; } = new ChangeTrackingList<string>();
    }
}


Review comment (suggestion):
I think this is not a required change for the issue we want to solve right now - because the initialization ctor will always assign this property with the same value.
The changes in `BarSettingsResourceData.cs` solve the issue nicely.

Code after:
namespace Azure.Generator.MgmtTypeSpec.Tests.Models
{
    /// <summary> The SafeFlattenModel. </summary>
    internal partial class SafeFlattenModel
    {
        /// <summary> Keeps track of any properties unknown to the library. </summary>
        private protected readonly IDictionary<string, BinaryData> _additionalBinaryDataProperties;

        /// <summary> Initializes a new instance of <see cref="SafeFlattenModel"/>. </summary>
        public SafeFlattenModel()
        {
            FlattenedProperty = new ChangeTrackingList<string>();
        }

        /// <summary> Initializes a new instance of <see cref="SafeFlattenModel"/>. </summary>
        /// <param name="flattenedProperty"></param>
        /// <param name="additionalBinaryDataProperties"> Keeps track of any properties unknown to the library. </param>
        internal SafeFlattenModel(IList<string> flattenedProperty, IDictionary<string, BinaryData> additionalBinaryDataProperties)
        {
            FlattenedProperty = flattenedProperty;
            _additionalBinaryDataProperties = additionalBinaryDataProperties;
        }

        /// <summary> Gets the FlattenedProperty. </summary>
        [WirePath("flattenedProperty")]
        public IList<string> FlattenedProperty { get; }
    }
}
Repository: BLAKE3-team/BLAKE3
File: b3sum/tests/test.rs (Rust)

Code before:
fn test_derive_key() {
    let context = "BLAKE3 2019-12-28 10:28:41 example context";
    let f = tempfile::NamedTempFile::new().unwrap();
    f.as_file().write_all(b"key material").unwrap();
    f.as_file().flush().unwrap();
    let mut derive_key_out = [0; blake3::OUT_LEN];
    blake3::derive_key(context, b"key material", &mut derive_key_out);
    let expected = hex::encode(&derive_key_out);
    let output = cmd!(b3sum_exe(), "--derive-key", context, "--no-names", f.path())
        .read()
        .unwrap();
    assert_eq!(&*expected, &*output);
}

#[test]
fn test_length_without_value_is_an_error() {
    let result = cmd!(b3sum_exe(), "--length")
        .stdin_bytes("foo")
        .stderr_capture()
        .run();
    assert!(result.is_err());
}

#[test]
fn test_raw_with_multi_files_is_an_error() {
    let result = cmd!(b3sum_exe(), "--raw", "file1", "file2")
        .stderr_capture()
        .run();
    assert!(result.is_err());
}


Review comment (bug):
I think this test could fail to test what it looks like, because the fact that `file1` and `file2` don't exist will lead to another type of error. Could you create a couple temporary files (with `NamedTempFile` as in other tests) to prevent this error from happening? You should be able to confirm that if you comment out the `len() > 1` check in main, that this test no longer gets the non-zero error code it wants and starts failing.

Code after:
fn test_derive_key() {
    let context = "BLAKE3 2019-12-28 10:28:41 example context";
    let f = tempfile::NamedTempFile::new().unwrap();
    f.as_file().write_all(b"key material").unwrap();
    f.as_file().flush().unwrap();
    let mut derive_key_out = [0; blake3::OUT_LEN];
    blake3::derive_key(context, b"key material", &mut derive_key_out);
    let expected = hex::encode(&derive_key_out);
    let output = cmd!(b3sum_exe(), "--derive-key", context, "--no-names", f.path())
        .read()
        .unwrap();
    assert_eq!(&*expected, &*output);
}

#[test]
fn test_length_without_value_is_an_error() {
    let result = cmd!(b3sum_exe(), "--length")
        .stdin_bytes("foo")
        .stderr_capture()
        .run();
    assert!(result.is_err());
}

#[test]
fn test_raw_with_multi_files_is_an_error() {
    let f1 = tempfile::NamedTempFile::new().unwrap();
    let f2 = tempfile::NamedTempFile::new().unwrap();

    // Make sure it doesn't error with just one file
    let result = cmd!(b3sum_exe(), "--raw", f1.path()).stdout_capture().run();
    assert!(result.is_ok());

    // Make sure it errors when both file are passed
    let result = cmd!(b3sum_exe(), "--raw", f1.path(), f2.path())
        .stderr_capture()
        .run();
    assert!(result.is_err());
}
Repository: BLAKE3-team/BLAKE3
File: b3sum/tests/test.rs (Rust)

Code before:
use duct::cmd;
use std::fs;
use std::io::prelude::*;
use std::path::PathBuf;

pub fn b3sum_exe() -> PathBuf {
    assert_cmd::cargo::cargo_bin("b3sum")
}

#[test]
fn test_hash_one() {
    let expected = blake3::hash(b"foo").to_hex();
    let output = cmd!(b3sum_exe()).stdin_bytes("foo").read().unwrap();
    assert_eq!(&*expected, output);
}

#[test]
fn test_hash_one_raw() {
    let expected = blake3::hash(b"foo").as_bytes().to_owned();
    let mut stdout = Vec::new();
    let mut output_reader = cmd!(b3sum_exe(), "--raw")
        .stdin_bytes("foo")
        .reader()
        .unwrap();
    output_reader.read_to_end(&mut stdout).unwrap();
    assert_eq!(expected, stdout.as_slice());
}

#[test]
fn test_hash_many() {
    let dir = tempfile::tempdir().unwrap();
    let file1 = dir.path().join("file1");
    fs::write(&file1, b"foo").unwrap();
    let file2 = dir.path().join("file2");
    fs::write(&file2, b"bar").unwrap();

    let output = cmd!(b3sum_exe(), &file1, &file2).read().unwrap();
    let foo_hash = blake3::hash(b"foo");
    let bar_hash = blake3::hash(b"bar");
    let expected = format!(
        "{}  {}\n{}  {}",
        foo_hash.to_hex(),
        file1.to_string_lossy(),
        bar_hash.to_hex(),
        file2.to_string_lossy(),
    );

Review comment (suggestion):
You could also use `stdout_capture` here, if you wanted to save yourself the `read_to_end` call. Either way.

Code after:
use duct::cmd;
use std::fs;
use std::io::prelude::*;
use std::path::PathBuf;

pub fn b3sum_exe() -> PathBuf {
    assert_cmd::cargo::cargo_bin("b3sum")
}

#[test]
fn test_hash_one() {
    let expected = blake3::hash(b"foo").to_hex();
    let output = cmd!(b3sum_exe()).stdin_bytes("foo").read().unwrap();
    assert_eq!(&*expected, output);
}

#[test]
fn test_hash_one_raw() {
    let expected = blake3::hash(b"foo").as_bytes().to_owned();
    let output = cmd!(b3sum_exe(), "--raw")
        .stdin_bytes("foo")
        .stdout_capture()
        .run()
        .unwrap()
        .stdout;
    assert_eq!(expected, output.as_slice());
}

#[test]
fn test_hash_many() {
    let dir = tempfile::tempdir().unwrap();
    let file1 = dir.path().join("file1");
    fs::write(&file1, b"foo").unwrap();
    let file2 = dir.path().join("file2");
    fs::write(&file2, b"bar").unwrap();

    let output = cmd!(b3sum_exe(), &file1, &file2).read().unwrap();
    let foo_hash = blake3::hash(b"foo");
    let bar_hash = blake3::hash(b"bar");
    let expected = format!(
        "{}  {}\n{}  {}",
        foo_hash.to_hex(),
        file1.to_string_lossy(),
        bar_hash.to_hex(),
        file2.to_string_lossy(),
    );
Repository: BLAKE3-team/BLAKE3
File: c/blake3_dispatch.c (C)

Code before:
                       : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3])
                       : "a"(id), "c"(sid));
#endif
}

#endif

enum cpu_feature {
  SSE2 = 1 << 0,
  SSSE3 = 1 << 1,
  SSE41 = 1 << 2,
  AVX = 1 << 3,
  AVX2 = 1 << 4,
  AVX512F = 1 << 5,
  AVX512VL = 1 << 6,
  /* ... */
  UNDEFINED = 1 << 30
};

#if !defined(BLAKE3_TESTING)
static /* Allow the variable to be controlled manually for testing */
#endif
#if defined(_MSC_VER)
LONG
#else
_Atomic int
#endif
    g_cpu_features = UNDEFINED; //

#if !defined(BLAKE3_TESTING)
static
#endif
    enum cpu_feature
    get_cpu_features(void) {

#if defined(_MSC_VER)
  enum cpu_feature features = InterlockedOr(&g_cpu_features, 0);
#else
  enum cpu_feature features = g_cpu_features;
#endif
  if (features != UNDEFINED) {
    return features;
  } else {
#if defined(IS_X86)
    uint32_t regs[4] = {0};
    uint32_t *eax = &regs[0], *ebx = &regs[1], *ecx = &regs[2], *edx = &regs[3];
    (void)edx;
    features = 0;
    cpuid(regs, 0);
    const int max_id = *eax;
    cpuid(regs, 1);

Review comment (suggestion):
MSVC doesn't support `_Atomic` yet when building C code (https://github.com/microsoft/STL/blob/main/stl/inc/stdatomic.h#L15), so the Win32 interlocked APIs have to be used.

Code after:
#if defined(_MSC_VER)
  __cpuid((int *)out, id);
#elif defined(__i386__) || defined(_M_IX86)
  __asm__ __volatile__("movl %%ebx, %1\n"
                       "cpuid\n"
                       "xchgl %1, %%ebx\n"
                       : "=a"(out[0]), "=r"(out[1]), "=c"(out[2]), "=d"(out[3])
                       : "a"(id));
#else
  __asm__ __volatile__("cpuid\n"
                       : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3])
                       : "a"(id));
#endif
}

static void cpuidex(uint32_t out[4], uint32_t id, uint32_t sid) {
#if defined(_MSC_VER)
  __cpuidex((int *)out, id, sid);
#elif defined(__i386__) || defined(_M_IX86)
  __asm__ __volatile__("movl %%ebx, %1\n"
                       "cpuid\n"
                       "xchgl %1, %%ebx\n"
                       : "=a"(out[0]), "=r"(out[1]), "=c"(out[2]), "=d"(out[3])
                       : "a"(id), "c"(sid));
#else
  __asm__ __volatile__("cpuid\n"
                       : "=a"(out[0]), "=b"(out[1]), "=c"(out[2]), "=d"(out[3])
                       : "a"(id), "c"(sid));
#endif
}

#endif

enum cpu_feature {
  SSE2 = 1 << 0,
  SSSE3 = 1 << 1,
  SSE41 = 1 << 2,
  AVX = 1 << 3,
  AVX2 = 1 << 4,
  AVX512F = 1 << 5,
  AVX512VL = 1 << 6,
  /* ... */
  UNDEFINED = 1 << 30
};

#if !defined(BLAKE3_TESTING)
static /* Allow the variable to be controlled manually for testing */
#endif
    ATOMIC_INT g_cpu_features = UNDEFINED;

#if !defined(BLAKE3_TESTING)
Repository: Chia-Network/chia-blockchain
File: chia/_tests/util/coin_store.py (Python)

Code before:
            "INSERT INTO coin_record VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
            (
                (
                    record.coin.name(),
                    record.confirmed_block_index,
                    record.spent_block_index,
                    int(record.coinbase),
                    record.coin.puzzle_hash,
                    record.coin.parent_coin_info,
                    record.coin.amount.stream_to_bytes(),
                    record.timestamp,
                )
                for record in records
            ),
        )


@pytest.mark.anyio
async def test_add_coin_records_to_db() -> None:
    async with DBConnection(2) as db_wrapper:
        coin_store = await CoinStore.create(db_wrapper)
        test_records: list[CoinRecord] = []
        test_height = uint32(1)
        test_spent_index = uint32(0)
        for i in range(5):
            coin = Coin(bytes32([0] * 32), bytes32([0] * 32), uint64(i))
            record = CoinRecord(
                coin=coin,
                confirmed_block_index=test_height,
                spent_block_index=test_spent_index,
                coinbase=i % 2 == 0,
                timestamp=uint64(i),
            )
            test_records.append(record)
        await add_coin_records_to_db(db_wrapper, test_records)
        # Verify all records got inserted correctly
        for record in test_records:
            resulting_record = await coin_store.get_coin_record(record.coin.name())
            assert resulting_record is not None
            assert resulting_record == record


Review comment (suggestion):
```suggestion
            coin = Coin(bytes32([i*2] * 32), bytes32([i*2+1] * 32), uint64(i))
```

Code after:
from __future__ import annotations

from chia.types.coin_record import CoinRecord
from chia.util.db_wrapper import DBWrapper2


async def add_coin_records_to_db(db_wrapper: DBWrapper2, records: list[CoinRecord]) -> None:
    if len(records) == 0:
        return
    async with db_wrapper.writer_maybe_transaction() as conn:
        await conn.executemany(
            "INSERT INTO coin_record VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
            (
                (
                    record.coin.name(),
                    record.confirmed_block_index,
                    record.spent_block_index,
                    int(record.coinbase),
                    record.coin.puzzle_hash,
                    record.coin.parent_coin_info,
                    record.coin.amount.stream_to_bytes(),
                    record.timestamp,
                )
                for record in records
            ),
        )
Repository: Chia-Network/chia-blockchain
File: chia/consensus/coin_store_protocol.py (Python)

Code before:
        """
        Returns the coins added at a specific height
        """

    async def get_coins_removed_at_height(self, height: uint32) -> list[CoinRecord]:
        """
        Returns the coins removed at a specific height
        """

    async def get_coin_records_by_puzzle_hash(
        self,
        include_spent_coins: bool,
        puzzle_hash: bytes32,
        start_height: uint32 = uint32(0),
        end_height: uint32 = uint32((2**32) - 1),
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a specific puzzle hash
        """

    async def get_coin_records_by_puzzle_hashes(
        self,
        coins: bool,
        puzzle_hashes: list[bytes32],
        start_height: uint32 = uint32(0),
        end_height: uint32 = uint32((2**32) - 1),
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a list of puzzle hashes
        """

    async def get_coin_records_by_names(
        self,
        include_spent_coins: bool,
        names: list[bytes32],
        start_height: uint32 = uint32(0),
        end_height: uint32 = uint32((2**32) - 1),
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a list of coin names
        """

    async def get_coin_states_by_puzzle_hashes(
        self,
        include_spent_coins: bool,
        puzzle_hashes: set[bytes32],
        min_height: uint32 = uint32(0),
        *,
        max_items: int = 50000,
    ) -> set[CoinState]:
        """

Review comment (suggestion):
```suggestion
        start_height: uint32 = ...,
        end_height: uint32 = ...,
```

Code after:
        """
        Returns the coins added at a specific height
        """

    async def get_coins_removed_at_height(self, height: uint32) -> list[CoinRecord]:
        """
        Returns the coins removed at a specific height
        """

    async def get_coin_records_by_puzzle_hash(
        self,
        include_spent_coins: bool,
        puzzle_hash: bytes32,
        start_height: uint32 = ...,
        end_height: uint32 = ...,
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a specific puzzle hash
        """

    async def get_coin_records_by_puzzle_hashes(
        self,
        coins: bool,
        puzzle_hashes: list[bytes32],
        start_height: uint32 = ...,
        end_height: uint32 = ...,
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a list of puzzle hashes
        """

    async def get_coin_records_by_names(
        self,
        include_spent_coins: bool,
        names: list[bytes32],
        start_height: uint32 = ...,
        end_height: uint32 = ...,
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a list of coin names
        """

    async def get_coin_states_by_puzzle_hashes(
        self,
        include_spent_coins: bool,
        puzzle_hashes: set[bytes32],
        min_height: uint32 = uint32(0),
        *,
        max_items: int = ...,
    ) -> set[CoinState]:
        """
Repository: Chia-Network/chia-blockchain
File: chia/consensus/coin_store_protocol.py (Python)

Code before:
        include_spent_coins: bool,
        puzzle_hash: bytes32,
        start_height: uint32 = uint32(0),
        end_height: uint32 = uint32((2**32) - 1),
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a specific puzzle hash
        """

    async def get_coin_records_by_puzzle_hashes(
        self,
        coins: bool,
        puzzle_hashes: list[bytes32],
        start_height: uint32 = uint32(0),
        end_height: uint32 = uint32((2**32) - 1),
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a list of puzzle hashes
        """

    async def get_coin_records_by_names(
        self,
        include_spent_coins: bool,
        names: list[bytes32],
        start_height: uint32 = uint32(0),
        end_height: uint32 = uint32((2**32) - 1),
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a list of coin names
        """

    async def get_coin_states_by_puzzle_hashes(
        self,
        include_spent_coins: bool,
        puzzle_hashes: set[bytes32],
        min_height: uint32 = uint32(0),
        *,
        max_items: int = 50000,
    ) -> set[CoinState]:
        """
        Returns the coin states for a set of puzzle hashes
        """

    async def get_coin_records_by_parent_ids(
        self,
        include_spent_coins: bool,
        parent_ids: list[bytes32],
        start_height: uint32 = uint32(0),
        end_height: uint32 = uint32((2**32) - 1),
    ) -> list[CoinRecord]:
        """

Review comment (suggestion):
```suggestion
        start_height: uint32 = ...,
        end_height: uint32 = ...,
```

Code after:
        include_spent_coins: bool,
        puzzle_hash: bytes32,
        start_height: uint32 = ...,
        end_height: uint32 = ...,
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a specific puzzle hash
        """

    async def get_coin_records_by_puzzle_hashes(
        self,
        coins: bool,
        puzzle_hashes: list[bytes32],
        start_height: uint32 = ...,
        end_height: uint32 = ...,
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a list of puzzle hashes
        """

    async def get_coin_records_by_names(
        self,
        include_spent_coins: bool,
        names: list[bytes32],
        start_height: uint32 = ...,
        end_height: uint32 = ...,
    ) -> list[CoinRecord]:
        """
        Returns the coin records for a list of coin names
        """

    async def get_coin_states_by_puzzle_hashes(
        self,
        include_spent_coins: bool,
        puzzle_hashes: set[bytes32],
        min_height: uint32 = uint32(0),
        *,
        max_items: int = ...,
    ) -> set[CoinState]:
        """
        Returns the coin states for a set of puzzle hashes
        """

    async def get_coin_records_by_parent_ids(
        self,
        include_spent_coins: bool,
        parent_ids: list[bytes32],
        start_height: uint32 = ...,
        end_height: uint32 = ...,
    ) -> list[CoinRecord]:
        """