ronantakizawa/codereview-bench huggingface dataset:
Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/wasmJs/test/PropagateExceptionFinalResortTest.kt (Kotlin)

Code before:
package kotlinx.coroutines

import kotlinx.coroutines.testing.TestBase
import kotlin.test.*

class PropagateExceptionFinalResortTest : TestBase() {
    /*
     * Test that `propagateExceptionFinalResort` re-throws the exception on Wasm/JS.
     *
     * It is checked by setting up an exception handler within Wasm/JS.
     */
    @Test
    fun testThrows() = runTest {
        addUncaughtExceptionHandler()
        val job = GlobalScope.launch {
            throw IllegalStateException("My ISE")
        }
        job.join()
        delay(1)  // Let the exception be re-thrown and handled.
        assertTrue(exceptionCaught())
    }
}

private fun addUncaughtExceptionHandler() {
    js("""
        globalThis.exceptionCaught = false;
        process.on('uncaughtException', function(e) {
            globalThis.exceptionCaught = true;
        });
    """)
}

private fun exceptionCaught(): Boolean = js("globalThis.exceptionCaught")


Review comment (suggestion):
I wonder if we want to remove it afterward. Given that it doesn't seem like uncaught exceptions do *anything* on Wasm/JS by default, maybe it doesn't matter. Still, avoiding test cross-contamination is worth it so that this doesn't bite us when we forget about this test completely.

Code after:
package kotlinx.coroutines

import kotlinx.coroutines.testing.TestBase
import kotlin.test.*

class PropagateExceptionFinalResortTest : TestBase() {
    @BeforeTest
    private fun addUncaughtExceptionHandler() {
        addUncaughtExceptionHandlerHelper()
    }

    @AfterTest
    private fun removeHandler() {
        removeHandlerHelper()
    }

    /*
     * Test that `propagateExceptionFinalResort` re-throws the exception on Wasm/JS.
     *
     * It is checked by setting up an exception handler within Wasm/JS.
     */
    @Test
    fun testPropagateExceptionFinalResortReThrowsOnWasmJS() = runTest {
        val job = GlobalScope.launch {
            throw IllegalStateException("My ISE")
        }
        job.join()
        delay(1) // Let the exception be re-thrown and handled.
        assertTrue(exceptionCaught())
    }
}

private fun addUncaughtExceptionHandlerHelper() {
    js("""
            globalThis.exceptionCaught = false;
            globalThis.exceptionHandler = function(e) {
                globalThis.exceptionCaught = true;
            };
            process.on('uncaughtException', globalThis.exceptionHandler);
Repository: Kotlin/kotlinx.coroutines
File: integration-testing/smokeTest/build.gradle.kts (Kotlin)

Code before:
            dependencies {
                implementation(kotlin("test-wasm-js"))
            }
        }
        wasmWasiTest {
            dependencies {
                implementation(kotlin("test-wasm-wasi"))
            }
        }
        jvmTest {
            dependencies {
                implementation(kotlin("test"))
                implementation(kotlin("test-junit"))
            }
        }
    }

    targets.all {
        val kotlinCompilerTaskName = compilations.getByName("main").compileKotlinTaskName
        @Suppress("UNCHECKED_CAST")
        val kotlinCompilerTask = tasks.getByName(kotlinCompilerTaskName) as? HasConfigurableKotlinCompilerOptions<KotlinJvmCompilerOptions>
        kotlinCompilerTask?.compilerOptions {
            jvmTarget.set(JvmTarget.JVM_1_8)
        }
    }
}

Review comment (suggestion):
new line? (to avoid github from complaining, and for the symmetry of the universe, but I understand if that's not the policy here)

Code after:
            dependencies {
                implementation(kotlin("test-wasm-js"))
            }
        }
        wasmWasiTest {
            dependencies {
                implementation(kotlin("test-wasm-wasi"))
            }
        }
        jvmTest {
            dependencies {
                implementation(kotlin("test"))
                implementation(kotlin("test-junit"))
            }
        }
    }

    targets.all {
        val kotlinCompilerTaskName = compilations.getByName("main").compileKotlinTaskName
        @Suppress("UNCHECKED_CAST")
        val kotlinCompilerTask = tasks.getByName(kotlinCompilerTaskName) as? HasConfigurableKotlinCompilerOptions<KotlinJvmCompilerOptions>
        kotlinCompilerTask?.compilerOptions {
            jvmTarget.set(JvmTarget.JVM_1_8)
        }
    }
}
Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/common/test/channels/ChannelIteratorTest.kt (Kotlin)

Code before:
package kotlinx.coroutines.channels

import kotlinx.coroutines.testing.*
import kotlin.test.*

class ChannelIteratorTest : TestBase() {
    @Test
    fun testIteratorClosedHasNextFalse() = runTest {
        TestChannelKind.entries.forEach { kind ->
            val channel = kind.create<Int>()
            val iterator = channel.iterator()
            channel.close()
            assertFalse(iterator.hasNext())
        }
    }

    @Test
    fun testIteratorClosedWithExceptionHasNextThrows() = runTest {
        TestChannelKind.entries.forEach { kind ->
            val channel = kind.create<Int>()
            val iterator = channel.iterator()
            channel.close(TestException())
            assertFailsWith<TestException> { (iterator.hasNext()) }
        }
    }
}


Review comment (bug):
```suggestion
            assertFailsWith<TestException> { iterator.hasNext() }
```

Code after:
package kotlinx.coroutines.channels

import kotlinx.coroutines.testing.*
import kotlin.test.*

class ChannelIteratorTest : TestBase() {
    @Test
    fun testIteratorClosedHasNextFalse() = runTest {
        TestChannelKind.entries.forEach { kind ->
            val channel = kind.create<Int>()
            val iterator = channel.iterator()
            channel.close()
            assertFalse(iterator.hasNext())
        }
    }

    @Test
    fun testIteratorClosedWithExceptionHasNextThrows() = runTest {
        TestChannelKind.entries.forEach { kind ->
            val channel = kind.create<Int>()
            val iterator = channel.iterator()
            channel.close(TestException())
            assertFailsWith<TestException> { iterator.hasNext() }
        }
    }
}
Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/common/test/channels/ChannelPropertiesTest.kt (Kotlin)

Code before:
package kotlinx.coroutines.channels

import kotlinx.coroutines.testing.*
import kotlin.test.*

/**
 * Properties stay the same regardless of whether the channel was closed with or without exception.
 */
class ChannelPropertiesTest : TestBase() {
    @Test
    fun testClosedIsClosedForReceive() = runTest {
        TestChannelKind.entries.forEach { kind ->
            val channel = kind.create<Int>()
            assertFalse(channel.isClosedForReceive)
            channel.close()
            assertTrue(channel.isClosedForReceive)
        }
    }

    @Test
    fun testClosedWithExceptionIsClosedForReceive() = runTest {
        TestChannelKind.entries.forEach { kind ->
            val channel = kind.create<Int>()
            assertFalse(channel.isClosedForReceive)
            channel.close(TestException())
            assertTrue(channel.isClosedForReceive)
        }
    }

    @Test
    fun testClosedIsEmptyFalse() = runTest {
        TestChannelKind.entries.forEach { kind ->
            val channel = kind.create<Int>()
            assertTrue(channel.isEmpty)

Review comment (suggestion):
```suggestion
class ChannelPropertiesAfterClosingTest : TestBase() {
```
This seems to more accurately reflect the focus.

Code after:
package kotlinx.coroutines.channels

import kotlinx.coroutines.testing.*
import kotlin.test.*

/**
 * Properties stay the same regardless of whether the channel was closed with or without exception.
 */
class ChannelPropertiesAfterClosingTest : TestBase() {
    @Test
    fun testClosedIsClosedForReceive() = runTest {
        TestChannelKind.entries.forEach { kind ->
            for (exception in listOf(null, TestException())) {
                val channel = kind.create<Int>()
                assertFalse(channel.isClosedForReceive)
                channel.close(exception)
                assertTrue(channel.isClosedForReceive)
            }
        }
    }

    @Test
    fun testClosedIsEmptyFalse() = runTest {
        TestChannelKind.entries.forEach { kind ->
            for (exception in listOf(null, TestException())) {
                val channel = kind.create<Int>()
                assertTrue(channel.isEmpty)
                assertFalse(channel.isClosedForReceive)
                channel.close(exception)
                // NB! Not obvious.
                assertFalse(channel.isEmpty)
                assertTrue(channel.isClosedForReceive)
            }
        }
Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/common/test/channels/ChannelPropertiesTest.kt (Kotlin)

Code before:
        channel.send(1)
        assertFalse(channel.isEmpty)
        assertFalse(channel.isClosedForReceive)
        channel.close()
        assertFalse(channel.isEmpty)
        assertFalse(channel.isClosedForReceive)
        channel.receive()
        assertFalse(channel.isEmpty)
        assertTrue(channel.isClosedForReceive)
    }

    @Test
    fun testSendClosedWithExceptionReceiveIsEmptyFalse() = runTest {
        val channel = Channel<Int>(1)
        assertTrue(channel.isEmpty)
        assertFalse(channel.isClosedForReceive)
        channel.send(1)
        assertFalse(channel.isEmpty)
        assertFalse(channel.isClosedForReceive)
        channel.close(TestException())
        assertFalse(channel.isEmpty)
        assertFalse(channel.isClosedForReceive)
        channel.receive()
        assertFalse(channel.isEmpty)
        assertTrue(channel.isClosedForReceive)
    }
}


Review comment (refactor):
The tests here come in perfect pairs of channels being closed with/without an exception. This calls for either extracting the test logic into separate parameterized functions or checking both cases in each test (using something like `for (exception in listOf(null, TestException())`).

Code after:
package kotlinx.coroutines.channels

import kotlinx.coroutines.testing.*
import kotlin.test.*

/**
 * Properties stay the same regardless of whether the channel was closed with or without exception.
 */
class ChannelPropertiesAfterClosingTest : TestBase() {
    @Test
    fun testClosedIsClosedForReceive() = runTest {
        TestChannelKind.entries.forEach { kind ->
            for (exception in listOf(null, TestException())) {
                val channel = kind.create<Int>()
                assertFalse(channel.isClosedForReceive)
                channel.close(exception)
                assertTrue(channel.isClosedForReceive)
            }
        }
    }

    @Test
    fun testClosedIsEmptyFalse() = runTest {
        TestChannelKind.entries.forEach { kind ->
            for (exception in listOf(null, TestException())) {
                val channel = kind.create<Int>()
                assertTrue(channel.isEmpty)
                assertFalse(channel.isClosedForReceive)
                channel.close(exception)
                // NB! Not obvious.
                assertFalse(channel.isEmpty)
                assertTrue(channel.isClosedForReceive)
            }
        }
    }

    @Test
    fun testSendClosedReceiveIsEmptyFalse() = runTest {
        for (exception in listOf(null, TestException())) {
            val channel = Channel<Int>(1)
            assertTrue(channel.isEmpty)
            assertFalse(channel.isClosedForReceive)
            channel.send(1)
            assertFalse(channel.isEmpty)
            assertFalse(channel.isClosedForReceive)
            channel.close(exception)
            assertFalse(channel.isEmpty)
            assertFalse(channel.isClosedForReceive)
            channel.receive()
            assertFalse(channel.isEmpty)
            assertTrue(channel.isClosedForReceive)
        }
    }
}
Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/common/src/channels/Channels.common.kt (Kotlin)

Code before:
 * val channel = produce {
 *     var i = 0
 *     while (doContinue.load()) {
 *         send(i++)
 *         delay(10.milliseconds)
 *         if (i == 42) break
 *     }
 * }
 *
 * // Start the consumer
 * launch {
 *     // Read elements until we suddenly decide to stop
 *     // or until the channel is closed.
 *     while (Random.nextInt() % 100 != 42) {
 *         val nextElement = channel.receiveCatching()
 *         if (nextElement.isClosed) return@launch
 *         println("Received ${nextElement.getOrNull()}")
 *     }
 *     doContinue.store(false)
 *     delay(100.milliseconds)
 *     val remainingElements = mutableListOf<Int>()
 *     try {
 *         channel.consumeTo(remainingElements)
 *     } finally {
 *         println("Remaining elements: $remainingElements")
 *     }
 * }
 * ```
 */
public suspend fun <E, C: MutableCollection<E>> ReceiveChannel<E>.consumeTo(collection: C): C =
    consumeEach(collection::add).let { collection }


@PublishedApi
internal fun ReceiveChannel<*>.cancelConsumed(cause: Throwable?) {
    cancel(cause?.let {
        it as? CancellationException ?: CancellationException("Channel was consumed, consumer had failed", it)
    })
}



Review comment (suggestion):
A more closer example would be to have a channel which is can be **closed with a cause**, to separate the usage of this function from just `channel.toList()`

Code after:
 *     var i = 0
 *     while (doContinue.load()) {
 *         send(i++)
 *         delay(10.milliseconds)
 *         if (i == 42) break
 *     }
 * }
 *
 * // Start the consumer
 * launch {
 *     // Read elements until we suddenly decide to stop
 *     // or until the channel is closed.
 *     while (Random.nextInt(100) != 0) {
 *         val nextElement = channel.receiveCatching()
 *         if (nextElement.isClosed) return@launch
 *         println("Received ${nextElement.getOrNull()}")
 *     }
 *     delay(100.milliseconds)
 *     doContinue.store(false)
 *     delay(100.milliseconds)
 *     val remainingElements = mutableListOf<Int>()
 *     try {
 *         channel.consumeTo(remainingElements)
 *     } finally {
 *         println("Remaining elements: $remainingElements")
 *     }
 * }
 * ```
 */
public suspend fun <E, C: MutableCollection<E>> ReceiveChannel<E>.consumeTo(collection: C): C =
    consumeEach(collection::add).let { collection }


@PublishedApi
internal fun ReceiveChannel<*>.cancelConsumed(cause: Throwable?) {
    cancel(cause?.let {
        it as? CancellationException ?: CancellationException("Channel was consumed, consumer had failed", it)
    })
}
Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/common/src/channels/Channels.common.kt (Kotlin)

Code before:
 * and processing them in a single batch.
 *
 * Example:
 * ```
 * val doContinue = AtomicBoolean(true)
 *
 * // Start the sender
 * val channel = produce {
 *     var i = 0
 *     while (doContinue.load()) {
 *         send(i++)
 *         delay(10.milliseconds)
 *         if (i == 42) break
 *     }
 * }
 *
 * // Start the consumer
 * launch {
 *     // Read elements until we suddenly decide to stop
 *     // or until the channel is closed.
 *     while (Random.nextInt() % 100 != 42) {
 *         val nextElement = channel.receiveCatching()
 *         if (nextElement.isClosed) return@launch
 *         println("Received ${nextElement.getOrNull()}")
 *     }
 *     doContinue.store(false)
 *     delay(100.milliseconds)
 *     val remainingElements = mutableListOf<Int>()
 *     try {
 *         channel.consumeTo(remainingElements)
 *     } finally {
 *         println("Remaining elements: $remainingElements")
 *     }
 * }
 * ```
 */
public suspend fun <E, C: MutableCollection<E>> ReceiveChannel<E>.consumeTo(collection: C): C =
    consumeEach(collection::add).let { collection }


@PublishedApi
internal fun ReceiveChannel<*>.cancelConsumed(cause: Throwable?) {
    cancel(cause?.let {
        it as? CancellationException ?: CancellationException("Channel was consumed, consumer had failed", it)
    })
}



Review comment (suggestion):
```suggestion
  *     delay(100.milliseconds)
  *     doContinue.store(false)
```

Code after:
 *
 * Example:
 * ```
 * val doContinue = AtomicBoolean(true)
 *
 * // Start the sender
 * val channel = produce {
 *     var i = 0
 *     while (doContinue.load()) {
 *         send(i++)
 *         delay(10.milliseconds)
 *         if (i == 42) break
 *     }
 * }
 *
 * // Start the consumer
 * launch {
 *     // Read elements until we suddenly decide to stop
 *     // or until the channel is closed.
 *     while (Random.nextInt(100) != 0) {
 *         val nextElement = channel.receiveCatching()
 *         if (nextElement.isClosed) return@launch
 *         println("Received ${nextElement.getOrNull()}")
 *     }
 *     delay(100.milliseconds)
 *     doContinue.store(false)
 *     delay(100.milliseconds)
 *     val remainingElements = mutableListOf<Int>()
 *     try {
 *         channel.consumeTo(remainingElements)
 *     } finally {
 *         println("Remaining elements: $remainingElements")
 *     }
 * }
 * ```
 */
public suspend fun <E, C: MutableCollection<E>> ReceiveChannel<E>.consumeTo(collection: C): C =
    consumeEach(collection::add).let { collection }


@PublishedApi
internal fun ReceiveChannel<*>.cancelConsumed(cause: Throwable?) {
    cancel(cause?.let {
        it as? CancellationException ?: CancellationException("Channel was consumed, consumer had failed", it)
    })
}
Repository: Kotlin/kotlinx.coroutines
File: kotlinx-coroutines-core/jvm/test/exceptions/CoroutineExceptionHandlerJvmTest.kt (Kotlin)

Code before:
package kotlinx.coroutines.exceptions

import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import org.junit.*
import org.junit.Test
import kotlin.test.*

class CoroutineExceptionHandlerJvmTest : TestBase() {

    @Test
    fun testFailingHandler() = runBlocking {
        expect(1)
        val caughtException = catchingUncaughtException {
            GlobalScope.launch(CoroutineExceptionHandler { _, _ -> throw AssertionError() }) {
                expect(2)
                throw TestException()
            }.join()
        }
        assertIs<RuntimeException>(caughtException)
        assertIs<AssertionError>(caughtException.cause)
        assertIs<TestException>(caughtException.suppressed[0])

        finish(3)
    }

    @Test
    fun testLastDitchHandlerContainsContextualInformation() = runBlocking {
        expect(1)
        val caughtException = catchingUncaughtException {
            GlobalScope.launch(CoroutineName("last-ditch")) {
                expect(2)
                throw TestException()
            }.join()
        }
        assertIs<TestException>(caughtException)
        assertContains(caughtException.suppressed[0].toString(), "last-ditch")
        finish(3)
    }


Review comment (suggestion):
Better to use any other type of exception as a second-level test exception, to avoid false connotations with assertions used in test for its true purpose.

Code after:
package kotlinx.coroutines.exceptions

import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import org.junit.*
import org.junit.Test
import kotlin.test.*

class CoroutineExceptionHandlerJvmTest : TestBase() {

    @Test
    fun testThrowingHandler() = runBlocking {
        expect(1)
        val caughtException = catchingUncaughtException {
            GlobalScope.launch(CoroutineExceptionHandler { _, _ -> throw TestException2() }) {
                expect(2)
                throw TestException()
            }.join()
        }
        assertIs<RuntimeException>(caughtException)
        assertIs<TestException2>(caughtException.cause)
        assertIs<TestException>(caughtException.suppressed[0])

        finish(3)
    }

    @Test
    fun testLastResortHandlerContainsContextualInformation() = runBlocking {
        expect(1)
        val caughtException = catchingUncaughtException {
            GlobalScope.launch(CoroutineName("last-resort")) {
                expect(2)
                throw TestException()
            }.join()
        }
        assertIs<TestException>(caughtException)
        assertContains(caughtException.suppressed[0].toString(), "last-resort")
        finish(3)
    }
Repository: Kyome22/RunCat_for_windows
File: RunCat365/GPURepository.cs (C#)

Code before:
                {
                    gpuInfoList.RemoveAt(0);
                }
            }
            catch
            {
                isGpuAvailable = false;
            }
        }

        public GPUInfo Get()
        {
            if (!isGpuAvailable || gpuInfoList.Count == 0)
            {
                return new GPUInfo(0);
            }
            return new GPUInfo(gpuInfoList.Average());
        }

        public void Close()
        {
            gpuCounter?.Close();
        }
    }

    public record struct GPUInfo(float Utilization);

    internal static class GPUInfoExtension
    {
        internal static List<string> GenerateIndicator(this GPUInfo gpuInfo)
        {
            var resultLines = new List<string>
            {
                $"GPU: {gpuInfo.Utilization:f1}%"
            };
            return resultLines;
        }

        internal static string GetDescription(this GPUInfo gpuInfo)
        {
            return $"GPU: {gpuInfo.Utilization:f1}%";
        }
    }
}


Review comment (suggestion):
Please align the structure of GPUInfo with the other Info structures.

```csharp
struct GPUInfo
{
    internal float Total { get; set; }
}
```

Code after:
                    {
                        var counter = new PerformanceCounter("GPU Engine", "Utilization Percentage", instance);
                        _ = counter.NextValue();
                        gpuCounters.Add(counter);
                    }
                }
                else
                {
                    isGpuAvailable = false;
                }
            }
            catch
            {
                isGpuAvailable = false;
            }
        }

        internal void Update()
        {
            if (!isGpuAvailable || gpuCounters.Count == 0) return;
            try
            {
                var values = gpuCounters.Select(counter => counter.NextValue()).ToList();
                var avgValue = values.Count > 0 ? values.Average() : 0f;
                var maxValue = values.Count > 0 ? values.Max() : 0f;
                var gpuInfo = new GPUInfo
                {
                    Average = Math.Min(100, avgValue),
                    Maximum = Math.Min(100, maxValue)
                };
                gpuInfoList.Add(gpuInfo);
                if (GPU_INFO_LIST_LIMIT_SIZE < gpuInfoList.Count)
                {
                    gpuInfoList.RemoveAt(0);
                }
            }
            catch
            {
                isGpuAvailable = false;
            }
        }

        internal GPUInfo Get()
        {
            if (!isGpuAvailable || gpuInfoList.Count == 0)
            {
                return new GPUInfo();
            }
            return new GPUInfo
            {
                Average = gpuInfoList.Average(x => x.Average),