ronantakizawa/codereview-bench huggingface dataset:
Repository: TabbyML/tabby
File: ee/tabby-webserver/src/path.rs (Rust)

Code before:
use std::path::PathBuf;

use tabby_common::path::tabby_root;

pub fn tabby_ee_root() -> PathBuf {
    tabby_root().join("ee")
}

pub fn db_file() -> PathBuf {
    if cfg!(feature = "prod") {
        tabby_ee_root().join("db.sqlite")
    } else {
        tabby_ee_root().join("dev-db.sqlite")
    }
}

pub fn background_jobs_dir() -> PathBuf {
    if cfg!(feature = "prod") {
        tabby_ee_root().join("background-jobs")
    } else {
        tabby_ee_root().join("dev-background-jobs")
    }
}


Review comment (suggestion):
```suggestion
      tabby_ee_root().join("background-jobs")
```

Code after:
use std::path::PathBuf;

use tabby_common::path::tabby_root;

pub fn tabby_ee_root() -> PathBuf {
    tabby_root().join("ee")
}

pub fn db_file() -> PathBuf {
    if cfg!(feature = "prod") {
        tabby_ee_root().join("db.sqlite")
    } else {
        tabby_ee_root().join("dev-db.sqlite")
    }
}

pub fn background_jobs_dir() -> PathBuf {
    tabby_ee_root().join("background-jobs")
}
Repository: TabbyML/tabby
File: clients/vscode/src/chat/webview.ts (TypeScript)

Code before:

        const repositories = this.gitProvider.getRepositories();
        if (!repositories) {
          return [];
        }

        const getRepoChanges = async (
          repos: Repository[],
          staged: boolean,
          tokenLimit: number,
        ): Promise<ChangeItem[]> => {
          if (tokenLimit <= 0) {
            return [];
          }

          const res: ChangeItem[] = [];
          let currentTokenCount = 0;

          for (const repo of repos) {
            const diffs = await this.gitProvider.getDiff(repo, staged);
            if (!diffs) {
              continue;
            }

            for (const diff of diffs) {
              const diffTokens = Math.ceil(diff.length / 4);

              if (currentTokenCount + diffTokens > tokenLimit) {
                break;
              }

              res.push({
                content: diff,
                staged: staged,
              } as ChangeItem);

              currentTokenCount += diffTokens;
            }

            if (currentTokenCount >= tokenLimit) {
              break;
            }
          }

          return res;
        };

        const stagedChanges: ChangeItem[] = await getRepoChanges(repositories, true, remainingTokens);

        const stagedTokenCount = stagedChanges.reduce((count, item) => count + Math.ceil(item.content.length / 4), 0);
        remainingTokens = tokenLimit - stagedTokenCount;

Review comment (suggestion):
Use `maxChars` to limit the result content. The approximate token counts should not be handled on the client side.

Code after:
        let remainingChars = maxChars;

        const repositories = this.gitProvider.getRepositories();
        if (!repositories) {
          return [];
        }

        const getRepoChanges = async (
          repos: Repository[],
          staged: boolean,
          charLimit?: number,
        ): Promise<ChangeItem[]> => {
          if (charLimit !== undefined && charLimit <= 0) {
            return [];
          }

          const res: ChangeItem[] = [];
          let currentCharCount = 0;

          for (const repo of repos) {
            const diffs = await this.gitProvider.getDiff(repo, staged);
            if (!diffs) {
              continue;
            }

            for (const diff of diffs) {
              const diffChars = diff.length;

              if (charLimit !== undefined && currentCharCount + diffChars > charLimit) {
                break;
              }

              res.push({
                content: diff,
                staged: staged,
              } as ChangeItem);

              currentCharCount += diffChars;
            }

            if (charLimit !== undefined && currentCharCount >= charLimit) {
              break;
            }
          }

          return res;
        };

        const stagedChanges: ChangeItem[] = await getRepoChanges(repositories, true, remainingChars);

        const stagedCharCount = stagedChanges.reduce((count, item) => count + item.content.length, 0);
Repository: TabbyML/tabby
File: clients/vscode/src/chat/webview.ts (TypeScript)

Code before:
        }
      },
      getChanges: async (params: GetChangesParams): Promise<ChangeItem[]> => {
        if (!this.gitProvider.isApiAvailable()) {
          return [];
        }

        const maxChars = params.maxChars || 4096;
        let remainingChars = maxChars;

        const repositories = this.gitProvider.getRepositories();
        if (!repositories) {
          return [];
        }

        const getRepoChanges = async (
          repos: Repository[],
          staged: boolean,
          charLimit: number,
        ): Promise<ChangeItem[]> => {
          if (charLimit <= 0) {
            return [];
          }

          const res: ChangeItem[] = [];
          let currentTokenCount = 0;

          for (const repo of repos) {
            const diffs = await this.gitProvider.getDiff(repo, staged);
            if (!diffs) {
              continue;
            }

            for (const diff of diffs) {
              const diffChars = diff.length;

              if (currentTokenCount + diffChars > charLimit) {
                break;
              }

              res.push({
                content: diff,
                staged: staged,
              } as ChangeItem);

              currentTokenCount += diffChars;
            }

            if (currentTokenCount >= maxChars) {
              break;
            }

Review comment (suggestion):
```suggestion
          let currentCharCount = 0;
```

Code after:
        }
      },

      getChanges: async (params: GetChangesParams): Promise<ChangeItem[]> => {
        if (!this.gitProvider.isApiAvailable()) {
          return [];
        }

        const maxChars = params.maxChars ?? undefined;
        let remainingChars = maxChars;

        const repositories = this.gitProvider.getRepositories();
        if (!repositories) {
          return [];
        }

        const getRepoChanges = async (
          repos: Repository[],
          staged: boolean,
          charLimit?: number,
        ): Promise<ChangeItem[]> => {
          if (charLimit !== undefined && charLimit <= 0) {
            return [];
          }

          const res: ChangeItem[] = [];
          let currentCharCount = 0;

          for (const repo of repos) {
            const diffs = await this.gitProvider.getDiff(repo, staged);
            if (!diffs) {
              continue;
            }

            for (const diff of diffs) {
              const diffChars = diff.length;

              if (charLimit !== undefined && currentCharCount + diffChars > charLimit) {
                break;
              }

              res.push({
                content: diff,
                staged: staged,
              } as ChangeItem);

              currentCharCount += diffChars;
            }

            if (charLimit !== undefined && currentCharCount >= charLimit) {
              break;
Repository: Tencent/MMKV
File: Core/MMKV_IO.cpp (C++)

Code before:
}

void MMKV::clearAll() {
    MMKVInfo("cleaning all key-values from [%s]", m_mmapID.c_str());
    SCOPED_LOCK(m_lock);
    SCOPED_LOCK(m_exclusiveProcessLock);

    checkLoadData();

    if (m_file->getFileSize() == DEFAULT_MMAP_SIZE && m_actualSize == 0) {
        MMKVInfo("nothing to clear for [%s]", m_mmapID.c_str());
        return;
    }
    m_file->truncate(DEFAULT_MMAP_SIZE);

#ifndef MMKV_DISABLE_CRYPT
    uint8_t newIV[AES_KEY_LEN];
    AESCrypt::fillRandomIV(newIV);
    if (m_crypter) {
        m_crypter->resetIV(newIV, sizeof(newIV));
    }
    writeActualSize(0, 0, newIV, IncreaseSequence);
#else
    writeActualSize(0, 0, nullptr, IncreaseSequence);
#endif
    m_metaFile->msync(MMKV_SYNC);

    clearMemoryCache();
    loadFromFile();
}

bool MMKV::isFileValid(const string &mmapID, MMKVPath_t *relatePath) {
    MMKVPath_t kvPath = mappedKVPathWithID(mmapID, MMKV_SINGLE_PROCESS, relatePath);
    if (!isFileExist(kvPath)) {
        return true;
    }

    MMKVPath_t crcPath = crcPathWithID(mmapID, MMKV_SINGLE_PROCESS, relatePath);
    if (!isFileExist(crcPath)) {
        return false;
    }

    uint32_t crcFile = 0;
    MMBuffer *data = readWholeFile(crcPath);
    if (data) {
        if (data->getPtr()) {
            MMKVMetaInfo metaInfo;
            metaInfo.read(data->getPtr());
            crcFile = metaInfo.m_crcDigest;
        }
        delete data;

Review comment (suggestion):
 Now a second look at it, this `msync()` call on metafile is a **MUST** for we are `IncreaseSequence`.

Code after:
    SCOPED_LOCK(m_exclusiveProcessLock);

    checkLoadData();

    if (m_file->getFileSize() == DEFAULT_MMAP_SIZE && m_actualSize == 0) {
        MMKVInfo("nothing to clear for [%s]", m_mmapID.c_str());
        return;
    }

    if (!keepSpace) {
        m_file->truncate(DEFAULT_MMAP_SIZE);
    }

#ifndef MMKV_DISABLE_CRYPT
    uint8_t newIV[AES_KEY_LEN];
    AESCrypt::fillRandomIV(newIV);
    if (m_crypter) {
        m_crypter->resetIV(newIV, sizeof(newIV));
    }
    writeActualSize(0, 0, newIV, IncreaseSequence);
#else
    writeActualSize(0, 0, nullptr, IncreaseSequence);
#endif

    if (!keepSpace) {
        m_metaFile->msync(MMKV_SYNC);
    }

    clearMemoryCache(keepSpace);
    loadFromFile();
}

bool MMKV::isFileValid(const string &mmapID, MMKVPath_t *relatePath) {
    MMKVPath_t kvPath = mappedKVPathWithID(mmapID, MMKV_SINGLE_PROCESS, relatePath);
    if (!isFileExist(kvPath)) {
        return true;
    }

    MMKVPath_t crcPath = crcPathWithID(mmapID, MMKV_SINGLE_PROCESS, relatePath);
    if (!isFileExist(crcPath)) {
        return false;
    }

    uint32_t crcFile = 0;
    MMBuffer *data = readWholeFile(crcPath);
    if (data) {
        if (data->getPtr()) {
            MMKVMetaInfo metaInfo;
            metaInfo.read(data->getPtr());
            crcFile = metaInfo.m_crcDigest;
        }
Repository: Tencent/ncnn
File: tests/test_cpu.cpp (C++)

Code before:
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.
#include <stdio.h>

#include "cpu.h"

#if defined __ANDROID__ || defined __linux__ || defined __APPLE__

static int test_cpu_set()
{
    ncnn::CpuSet set;

    if (set.num_enabled() != 0)
    {
        fprintf(stderr, "By default all cpus should be disabled\n");
        return 1;
    }

    set.enable(0);
    if (!set.is_enabled(0))
    {
        fprintf(stderr, "CpuSet enable doesn't work\n");
        return 1;
    }

    if (set.num_enabled() != 1)
    {

Review comment (security):
add empty line between license header and code
```suggestion
// specific language governing permissions and limitations under the License.

```

Code after:
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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.

#include <stdio.h>

#include "cpu.h"

#if defined __ANDROID__ || defined __linux__ || defined __APPLE__

static int test_cpu_set()
{
    ncnn::CpuSet set;

    if (set.num_enabled() != 0)
    {
        fprintf(stderr, "By default all cpus should be disabled\n");
        return 1;
    }

    set.enable(0);
    if (!set.is_enabled(0))
    {
        fprintf(stderr, "CpuSet enable doesn't work\n");
        return 1;
    }

    if (set.num_enabled() != 1)
Repository: Tencent/ncnn
File: tests/test_cpu.cpp (C++)

Code before:
    {
        return 0;
    }
    else
    {
        fprintf(stderr, "Set cpu powersave for `-1 < argument < 2` works incorrectly.\n");
        return 1;
    }
}

#else

#if defined _WIN32
// Check SDK >= Win7
#if _WIN32_WINNT >= _WIN32_WINNT_WIN7 // win7

static int test_cpu_info()
{
    int cpucount = ncnn::get_cpu_count();
    int bigcpucount = ncnn::get_big_cpu_count();
    int littlecpucount = ncnn::get_little_cpu_count();

    fprintf(stderr, "cpucount = %d\n", cpucount);
    fprintf(stderr, "bigcpucount = %d\n", bigcpucount);
    fprintf(stderr, "littlecpucount = %d\n", littlecpucount);

    return 0;
}

#endif
#else

static int test_cpu_info()
{
    return 0;
}

#endif

static int test_cpu_omp()
{
    return 0;
}

static int test_cpu_powersave()
{
    return 0;
}

#endif


Review comment (suggestion):
test bigcpucount + littlecpucount == cpucount
test bigcpucount <= cpucount
test littlecpucount < cpucount

return -1 on error

Code after:
    {
        return 0;
    }
    else
    {
        fprintf(stderr, "Set cpu powersave for `-1 < argument < 2` works incorrectly.\n");
        return 1;
    }
}

#else

#if defined _WIN32
// Check SDK >= Win7
#if _WIN32_WINNT >= _WIN32_WINNT_WIN7 // win7

static int test_cpu_info()
{
    int cpucount = ncnn::get_cpu_count();
    int bigcpucount = ncnn::get_big_cpu_count();
    int littlecpucount = ncnn::get_little_cpu_count();

    fprintf(stderr, "cpucount = %d\n", cpucount);
    fprintf(stderr, "bigcpucount = %d\n", bigcpucount);
    fprintf(stderr, "littlecpucount = %d\n", littlecpucount);

    if ((cpucount != bigcpucount + littlecpucount) || (bigcpucount > cpucount) || (littlecpucount > cpucount))
    {
        fprintf(stderr, "The number of big and little cpus must be less than or equal to the total number of cpus\n");
        return -1;
    }

    return 0;
}

#endif
#else

static int test_cpu_info()
{
    return 0;
}

#endif

static int test_cpu_omp()
{
    return 0;
}

static int test_cpu_powersave()
Repository: Tencent/ncnn
File: src/layer/x86/instancenorm_x86.cpp (C++)

Code before:
        __m512 _va_avx512 = _mm512_set1_ps(a);
        __m512 _vb_avx512 = _mm512_set1_ps(b);
        for (; i + 16 < size; i += 16)
        {
            __m512 _p = _mm512_loadu_ps(ptr);
            _p = _mm512_fmadd_ps(_p, _va_avx512, _vb_avx512);
            _mm512_storeu_ps(ptr, _p);
            ptr += 16;
        }
#endif // __AVX512F__
        __m256 _va_avx = _mm256_set1_ps(a);
        __m256 _vb_vax = _mm256_set1_ps(b);
        for (; i + 7 < size; i += 8)
        {
            __m256 _p = _mm256_loadu_ps(ptr);
            _p = _mm256_comp_fmadd_ps(_p, _va_avx, _vb_vax);
            _mm256_storeu_ps(ptr, _p);
            ptr += 8;
        }
#endif // __AVX__
        __m128 _va = _mm_set1_ps(a);
        __m128 _vb = _mm_set1_ps(b);
        for (; i + 3 < size; i += 4)
        {
            __m128 _p = _mm_loadu_ps(ptr);
            _p = _mm_comp_fmadd_ps(_p, _va, _vb); // Fused Multiply-Add
            _mm_storeu_ps(ptr, _p);
            ptr += 4;
        }
#endif // __SSE2__
        for (; i < size; i++)
        {
            ptr[0] = ptr[0] * a + b;
            ptr++;
        }
    }

    return 0;
}

} // namespace ncnn


Review comment (suggestion):
```suggestion
            _p = _mm_comp_fmadd_ps(_p, _va, _vb);
```

Code after:
        __m512 _va_avx512 = _mm512_set1_ps(a);
        __m512 _vb_avx512 = _mm512_set1_ps(b);
        for (; i + 16 < size; i += 16)
        {
            __m512 _p = _mm512_loadu_ps(ptr);
            _p = _mm512_fmadd_ps(_p, _va_avx512, _vb_avx512);
            _mm512_storeu_ps(ptr, _p);
            ptr += 16;
        }
#endif // __AVX512F__
        __m256 _va_avx = _mm256_set1_ps(a);
        __m256 _vb_vax = _mm256_set1_ps(b);
        for (; i + 7 < size; i += 8)
        {
            __m256 _p = _mm256_loadu_ps(ptr);
            _p = _mm256_comp_fmadd_ps(_p, _va_avx, _vb_vax);
            _mm256_storeu_ps(ptr, _p);
            ptr += 8;
        }
#endif // __AVX__
        __m128 _va = _mm_set1_ps(a);
        __m128 _vb = _mm_set1_ps(b);
        for (; i + 3 < size; i += 4)
        {
            __m128 _p = _mm_loadu_ps(ptr);
            _p = _mm_comp_fmadd_ps(_p, _va, _vb);
            _mm_storeu_ps(ptr, _p);
            ptr += 4;
        }
#endif // __SSE2__
        for (; i < size; i++)
        {
            ptr[0] = ptr[0] * a + b;
            ptr++;
        }
    }

    return 0;
}

} // namespace ncnn
Repository: Tencent/ncnn
File: src/layer/vulkan/sigmoid_vulkan.h (C/C++)

Code before:

#ifndef LAYER_SIGMOID_VULKAN_H
#define LAYER_SIGMOID_VULKAN_H

#include "sigmoid.h"

namespace ncnn {

class Sigmoid_vulkan : public Sigmoid
{
public:
    Sigmoid_vulkan();

    virtual int create_pipeline(const Option& opt);
    virtual int destroy_pipeline(const Option& opt);

    using Sigmoid::forward_inplace;
    virtual int forward_inplace(VkMat& bottom_top_blob, VkCompute& cmd, const Option& opt) const;

public:
    Pipeline* pipeline_sigmoid;
};

} // namespace ncnn

#endif // LAYER_SIGMOID_VULKAN_H

Review comment (suggestion):
```suggestion
#endif // LAYER_SIGMOID_VULKAN_H

```

Code after:

#ifndef LAYER_SIGMOID_VULKAN_H
#define LAYER_SIGMOID_VULKAN_H

#include "sigmoid.h"

namespace ncnn {

class Sigmoid_vulkan : public Sigmoid
{
public:
    Sigmoid_vulkan();

    virtual int create_pipeline(const Option& opt);
    virtual int destroy_pipeline(const Option& opt);

    using Sigmoid::forward_inplace;
    virtual int forward_inplace(VkMat& bottom_top_blob, VkCompute& cmd, const Option& opt) const;

public:
    Pipeline* pipeline_sigmoid;
};

} // namespace ncnn

#endif // LAYER_SIGMOID_VULKAN_H
Repository: TheAlgorithms/C-Plus-Plus
File: dynamic_programming/palindrome_partitioning.cpp (C++)

Code before:
    // calculated output vector by pal_part Function
    std::vector<int> calculated_output(3);

    for (int i = 0; i < 3; i++) {
        calculated_output[i] = dynamic_programming::palindrome_partitioning::pal_part(custom_input[i]);
    }

    // expected output vector
    std::vector<int> expected_output{2, 3, 3};

    // Testing implementation via assert function
    // It will throw error if any of the expected test fails
    // Else it will give nothing
    for (int i = 0; i < 3; i++) {
        assert(expected_output[i] == calculated_output[i]);
    }

    std::cout << "All tests passed successfully!\n";
}

/**
 * @brief Main function
 * @returns 0 on exit
 */
int main() {
    test();
    return 0;
}


Review comment (suggestion):
```suggestion
    test();  // execute the tests
```

Code after:
    std::vector<int> calculated_output(3);

    for (int i = 0; i < 3; i++) {
        calculated_output[i] = dynamic_programming::palindrome_partitioning::pal_part(custom_input[i]);
    }

    // expected output vector
    std::vector<int> expected_output{2, 3, 3};

    // Testing implementation via assert function
    // It will throw error if any of the expected test fails
    // Else it will give nothing
    for (int i = 0; i < 3; i++) {
        assert(expected_output[i] == calculated_output[i]);
    }

    std::cout << "All tests passed successfully!\n";
}

/**
 * @brief Main function
 * @returns 0 on exit
 */
int main() {
    test();  // execute the test
    return 0;
}
Repository: TheAlgorithms/C-Plus-Plus
File: dynamic_programming/palindrome_partitioning.cpp (C++)

Code before:
/**
 * @file
 * @brief palindrome partitioning algorithm gives you the minimum number of partitions you need to make
 * in order to divide a given string into a number of palindromes
 *
 * @details
 * palindrome partitioning uses dynamic programming and goes to all the possible partitions to find the minimum
 * you are given a string and you need to give minimum number of partitions needed to divide it into a number of palindromes
 * [Palindrome Partitioning] (https://www.geeksforgeeks.org/palindrome-partitioning-dp-17/)
 * overall time complexity O(n^2)
 * For example: example 1:-
 * String : "nitik"
 * Output : 2 => "n | iti | k"
 * For example: example 2:-
 * String : "ababbbabbababa"
 * Output : 3 => "aba | b | bbabb | ababa"
 * @author [Sujay Kaushik] (https://github.com/sujaykaushik008)
 * @see related problem at [Leetcode] (https://leetcode.com/problems/palindrome-partitioning-ii/)
 */

#include <iostream>   // for io operations
#include <vector>     // for std::vector
#include <algorithm>  // for std::min
#include <cassert>    // for std::assert
#include <climits>    // for INT_MAX

/**
 * @namespace dynamic_programming

Review comment (suggestion):
```suggestion
 * @brief Implements [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning-ii/) algorithm, giving you the minimum number of partitions you need to make
```

Code after:
/**
 * @file
 * @brief Implements [Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning-ii/) algorithm, giving you the minimum number of partitions you need to make
 *
 * @details
 * palindrome partitioning uses dynamic programming and goes to all the possible partitions to find the minimum
 * you are given a string and you need to give minimum number of partitions needed to divide it into a number of palindromes
 * [Palindrome Partitioning] (https://www.geeksforgeeks.org/palindrome-partitioning-dp-17/)
 * overall time complexity O(n^2)
 * For example: example 1:-
 * String : "nitik"
 * Output : 2 => "n | iti | k"
 * For example: example 2:-
 * String : "ababbbabbababa"
 * Output : 3 => "aba | b | bbabb | ababa"
 * @author [Sujay Kaushik] (https://github.com/sujaykaushik008)
 */

#include <iostream>   // for io operations
#include <vector>     // for std::vector
#include <algorithm>  // for std::min
#include <cassert>    // for std::assert
#include <climits>    // for INT_MAX

/**
 * @namespace dynamic_programming
 * @brief Dynamic Programming algorithms
 */