ronantakizawa/codereview-bench huggingface dataset:
Repository: HigherOrderCO/Bend
File: tests/golden_tests.rs (Rust)

Code before:
#[test]
fn scott_triggers_unused() {
  run_golden_test_dir(function_name!(), &|code, path| {
    let mut book = do_parse_book_default(code, path)?;
    let opts = CompileOpts::default();
    let diagnostics_cfg =
      DiagnosticsConfig { unused_definition: Severity::Error, ..DiagnosticsConfig::default() };
    let res = compile_book(&mut book, opts, diagnostics_cfg, None)?;
    Ok(format!("{}{}", res.diagnostics, hvm_book_show_pretty(&res.hvm_book)))
  })
}

// TODO: also run the long string file to test the readback
#[test]
fn compile_long() {
  run_golden_test_dir(function_name!(), &|code, path| {
    let mut book = do_parse_book_default(code, path)?;
    let opts = CompileOpts::default().set_all();
    let diagnostics_cfg = DiagnosticsConfig {
      recursion_cycle: Severity::Warning,
      unused_definition: Severity::Allow,
      ..Default::default()
    };

    let res = compile_book(&mut book, opts.clone(), diagnostics_cfg, None)?;
    Ok(format!("{}{}", res.diagnostics, hvm_book_show_pretty(&res.hvm_book)))
  })
}


Review comment (bug):
We don't want to print the book in case of success. This test in specific is made to generate way too large structures.

Since the compile fails it should already be saving the error messages. I think it should work if  you just leave it like it was.

Code after:
#[test]
fn scott_triggers_unused() {
  run_golden_test_dir(function_name!(), &|code, path| {
    let mut book = do_parse_book_default(code, path)?;
    let opts = CompileOpts::default();
    let diagnostics_cfg =
      DiagnosticsConfig { unused_definition: Severity::Error, ..DiagnosticsConfig::default() };
    let res = compile_book(&mut book, opts, diagnostics_cfg, None)?;
    Ok(format!("{}{}", res.diagnostics, hvm_book_show_pretty(&res.hvm_book)))
  })
}

// TODO: also run the long string file to test the readback
#[test]
fn compile_long() {
  run_golden_test_dir(function_name!(), &|code, path| {
    let mut book = do_parse_book_default(code, path)?;
    let opts = CompileOpts::default().set_all();
    let diagnostics_cfg = DiagnosticsConfig {
      recursion_cycle: Severity::Warning,
      unused_definition: Severity::Allow,
      ..Default::default()
    };

    compile_book(&mut book, opts.clone(), diagnostics_cfg, None)?;
    Ok("Compiled".to_string())
  })
}
Repository: HigherOrderCO/Bend
File: src/fun/parser.rs (Rust)

Code before:
    let ini_idx = *self.index();
    let sign = if self.try_consume_exactly("+") {
      Some(1)
    } else if self.try_consume_exactly("-") {
      Some(-1)
    } else {
      None
    };
    let radix = match self.peek_many(2) {
      Some("0x") => {
        self.advance_many(2);
        Radix::Hex
      }
      Some("0b") => {
        self.advance_many(2);
        Radix::Bin
      }
      _ => Radix::Dec,
    };
    let num = self.u32_with_radix(radix)?;
    let frac = if let Some('.') = self.peek_one() {
      self.advance_one();
      let ini_idx = *self.index();
      let fra = self.u32_with_radix(radix)?;
      let end_idx = *self.index();
      let fra = fra as f32 / (radix.to_f32()).powi((end_idx - ini_idx) as i32);
      Some(fra)
    } else {
      None
    };

    if let Some(frac) = frac {
      let sign = sign.unwrap_or(1);
      return Ok(Num::F24(sign as f32 * (num as f32 + frac)));
    }

    if let Some(sign) = sign {
      let num = sign * num as i32;
      if !(-0x00800000..=0x007fffff).contains(&num) {
        return self.num_range_err(ini_idx, "I24");
      }
      Ok(Num::I24(num))
    } else {
      if num >= 1 << 24 {
        return self.num_range_err(ini_idx, "U24");
      }
      Ok(Num::U24(num))
    }
  }

  fn num_range_err<T>(&mut self, ini_idx: usize, typ: &str) -> ParseResult<T> {

Review comment (bug):
Won't this be incorrect if there's a `_` in the fractional part? The right way would be to get the log of the number in the radix base I think

Code after:
    let ini_idx = *self.index();
    let sign = if self.try_consume_exactly("+") {
      Some(1)
    } else if self.try_consume_exactly("-") {
      Some(-1)
    } else {
      None
    };
    let radix = match self.peek_many(2) {
      Some("0x") => {
        self.advance_many(2);
        Radix::Hex
      }
      Some("0b") => {
        self.advance_many(2);
        Radix::Bin
      }
      _ => Radix::Dec,
    };
    let num = self.u32_with_radix(radix)?;
    let frac = if let Some('.') = self.peek_one() {
      self.advance_one();
      let fra_str = self.take_while(|c| c.is_digit(radix as u32) || c == '_');
      let fra_str = fra_str.chars().filter(|c| *c != '_').collect::<String>();
      let fra = u32::from_str_radix(&fra_str, radix as u32).map_err(|e| e.to_string())?;
      let fra = fra as f32 / (radix.to_f32()).powi(fra_str.len() as i32);
      Some(fra)
    } else {
      None
    };

    if let Some(frac) = frac {
      let sign = sign.unwrap_or(1);
      return Ok(Num::F24(sign as f32 * (num as f32 + frac)));
    }

    if let Some(sign) = sign {
      let num = sign * num as i32;
      if !(-0x00800000..=0x007fffff).contains(&num) {
        return self.num_range_err(ini_idx, "I24");
      }
      Ok(Num::I24(num))
    } else {
      if num >= 1 << 24 {
        return self.num_range_err(ini_idx, "U24");
      }
      Ok(Num::U24(num))
    }
  }

  fn num_range_err<T>(&mut self, ini_idx: usize, typ: &str) -> ParseResult<T> {
Repository: KRTirtho/spotube
File: lib/main.dart (Dart)

Code before:
  final arguments = parser.parse(rawArgs);

  if (arguments["help"] == true) {
    print(parser.usage);
    exit(0);
  }

  if (arguments["version"] == true) {
    final package = await PackageInfo.fromPlatform();
    print("Spotube v${package.version}");
    exit(0);
  }

  await Supabase.initialize(
    url: Env.supabaseUrl,
    anonKey: Env.supabaseAnonKey,
  );

  final widgetsBinding = WidgetsFlutterBinding.ensureInitialized();

  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  MediaKit.ensureInitialized();

  // force High Refresh Rate on some Android devices (like One Plus)
  await FlutterDisplayMode.setHighRefreshRate();

  await DesktopTools.ensureInitialized(
    DesktopWindowOptions(
      hideTitleBar: true,
      title: "Spotube",
      backgroundColor: Colors.transparent,
      minimumSize: const Size(300, 700),
    ),
  );

  await SystemTheme.accentColor.load();
  MetadataGod.initialize();

  final hiveCacheDir = (await getApplicationSupportDirectory()).path;

  await QueryClient.initialize(
    cachePrefix: "oss.krtirtho.spotube",
    cacheDir: hiveCacheDir,
    connectivity: FlQueryConnectivityPlusAdapter(),
  );
  Hive.registerAdapter(MatchedTrackAdapter());
  Hive.registerAdapter(SkipSegmentAdapter());
  Hive.registerAdapter(SearchModeAdapter());

  // Cache versioning entities with Adapter

Review comment (suggestion):
```suggestion
if (DesktopTools.platform.isAndroid) {
    await FlutterDisplayMode.setHighRefreshRate();
}
```

Need to check android platform to avoid `MissingPlatformImplementation` exception in other platforms

Code after:
  final arguments = parser.parse(rawArgs);

  if (arguments["help"] == true) {
    print(parser.usage);
    exit(0);
  }

  if (arguments["version"] == true) {
    final package = await PackageInfo.fromPlatform();
    print("Spotube v${package.version}");
    exit(0);
  }

  await Supabase.initialize(
    url: Env.supabaseUrl,
    anonKey: Env.supabaseAnonKey,
  );

  final widgetsBinding = WidgetsFlutterBinding.ensureInitialized();

  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);

  MediaKit.ensureInitialized();

  // force High Refresh Rate on some Android devices (like One Plus)
if (DesktopTools.platform.isAndroid) {
    await FlutterDisplayMode.setHighRefreshRate();
}

  await DesktopTools.ensureInitialized(
    DesktopWindowOptions(
      hideTitleBar: true,
      title: "Spotube",
      backgroundColor: Colors.transparent,
      minimumSize: const Size(300, 700),
    ),
  );

  await SystemTheme.accentColor.load();
  MetadataGod.initialize();

  final hiveCacheDir = (await getApplicationSupportDirectory()).path;

  await QueryClient.initialize(
    cachePrefix: "oss.krtirtho.spotube",
    cacheDir: hiveCacheDir,
    connectivity: FlQueryConnectivityPlusAdapter(),
  );
  Hive.registerAdapter(MatchedTrackAdapter());
  Hive.registerAdapter(SkipSegmentAdapter());
  Hive.registerAdapter(SearchModeAdapter());
Repository: KRTirtho/spotube
File: lib/l10n/l10n.dart (Dart)

Code before:
/// credits:
///
/// Kingkor Roy Tirtho => English, Bengali
/// ChatGPT (GPT 3.5) XD => Hindi, French
/// maboroshin@github => Japanese
/// iceyear@github => Simplified Chinese
import 'package:flutter/material.dart';

class L10n {
  static final all = [
    const Locale('en'),
    const Locale('bn', 'BD'),
    const Locale('de', 'GE'),
    const Locale('ca', 'CA'),
    const Locale('es', 'ES'),
    const Locale('fr', 'FR'),
    const Locale('hi', 'IN'),
    const Locale('ja', 'JP'),
    const Locale('zh', 'CN'),
  ];
}


Review comment (suggestion):
CA is for Canada's country code thus not working. I guess it's the native language of the country Andorra? In that case country code should be `AD` I guess
Also France (FR) and Italy (IT) are also valid

Code after:
/// credits:
///
/// Kingkor Roy Tirtho => English, Bengali
/// ChatGPT (GPT 3.5) XD => Hindi, French
/// maboroshin@github => Japanese
/// iceyear@github => Simplified Chinese
import 'package:flutter/material.dart';

class L10n {
  static final all = [
    const Locale('en'),
    const Locale('bn', 'BD'),
    const Locale('de', 'GE'),
    const Locale('ca', 'AD'),
    const Locale('es', 'ES'),
    const Locale('fr', 'FR'),
    const Locale('hi', 'IN'),
    const Locale('ja', 'JP'),
    const Locale('zh', 'CN'),
  ];
}
Repository: KRTirtho/spotube
File: lib/l10n/l10n.dart (Dart)

Code before:
/// credits:
///
/// Kingkor Roy Tirtho => English, Bengali
/// ChatGPT (GPT 3.5) XD => Hindi, French
/// maboroshin@github => Japanese
/// iceyear@github => Simplified Chinese
/// TexturedPolak@github => Polish
/// yuri-val@github => Ukrainian
/// energywave@github, ncvescera@github, OpenCode@github => Italian
/// mikropsoft@github => Turkish
/// Stephan-P@github, SecularSteve@github => Dutch
/// doannc2212@github => Vietnamese
/// sappho192@github => Korean
/// watchakorn-18k@github => Thai
library;
import 'package:flutter/material.dart';

class L10n {
  static final all = [
    const Locale('en'),
    const Locale('ar', 'SA'),
    const Locale('bn', 'BD'),
    const Locale('ca', 'AD'),
    const Locale('de', 'GE'),
    const Locale('es', 'ES'),
    const Locale('fa', 'IR'),
    const Locale('fr', 'FR'),
    const Locale('ne', 'NP'),
    const Locale('hi', 'IN'),
    const Locale('it', 'IT'),
    const Locale('ja', 'JP'),
    const Locale('ko', 'KR'),
    const Locale('nl', 'NL'),
    const Locale('pl', 'PL'),
    const Locale('pt', 'PT'),

Review comment (suggestion):
```suggestion
/// mdksec@github, mikropsoft@github => Turkish
```

You can't remove the previous contributor but you can add your name next to his/her name

Code after:
/// credits:
///
/// Kingkor Roy Tirtho => English, Bengali
/// ChatGPT (GPT 3.5) XD => Hindi, French
/// maboroshin@github => Japanese
/// iceyear@github => Simplified Chinese
/// TexturedPolak@github => Polish
/// yuri-val@github => Ukrainian
/// energywave@github, ncvescera@github, OpenCode@github => Italian
/// mdksec@github, mikropsoft@github => Turkish
/// Stephan-P@github, SecularSteve@github => Dutch
/// doannc2212@github => Vietnamese
/// sappho192@github => Korean
/// watchakorn-18k@github => Thai

import 'package:flutter/material.dart';

class L10n {
  static final all = [
    const Locale('en'),
    const Locale('ar', 'SA'),
    const Locale('bn', 'BD'),
    const Locale('ca', 'AD'),
    const Locale('de', 'GE'),
    const Locale('es', 'ES'),
    const Locale('fa', 'IR'),
    const Locale('fr', 'FR'),
    const Locale('ne', 'NP'),
    const Locale('hi', 'IN'),
    const Locale('it', 'IT'),
    const Locale('ja', 'JP'),
    const Locale('ko', 'KR'),
    const Locale('nl', 'NL'),
    const Locale('pl', 'PL'),
    const Locale('pt', 'PT'),
Repository: Kindelia/HVM
File: bench/test.sh (Shell)

Code before:
#!/bin/sh

mkdir "~test"

failed=

for dir in *; do

  p="${dir}/test.txt"
  if [ -d "${dir}" ] && [ -f "${p}" ]; then
    echo "Testing '${dir}'"

    bin_path="~test/${dir}"

    hvm compile "${dir}/main.hvm"
    clang -O2 "./${dir}/main.c" -o "${bin_path}" -lpthread

    while read -r line; do
      IFS=' ' read -ra arr <<< "$line"
      output="${arr[0]}"
      input=("${arr[@]:1}")
      printf "testing input: %s ... " "${input[*]}"
      # printf "(expected output: %s) " "${output}" # DEBUG

      result="$("${bin_path}" "${input[@]}" 2>/dev/null)"
      # printf "<<%s>> " "$result" # DEBUG

Review comment (suggestion):
I don't think it's a good idea to use `sh` instead of `bash` for the shebang here since this script uses bashisms and isn't POSIX compliant.

Code after:
#!/bin/bash

mkdir "~test"

failed=

for dir in *; do

  p="${dir}/test.txt"
  if [ -d "${dir}" ] && [ -f "${p}" ]; then
    echo "Testing '${dir}'"

    bin_path="~test/${dir}"

    hvm compile "${dir}/main.hvm"
    clang -O2 "./${dir}/main.c" -o "${bin_path}" -lpthread

    while read -r line; do
      IFS=' ' read -ra arr <<< "$line"
      output="${arr[0]}"
      input=("${arr[@]:1}")
      printf "testing input: %s ... " "${input[*]}"
      # printf "(expected output: %s) " "${output}" # DEBUG

      result="$("${bin_path}" "${input[@]}" 2>/dev/null)"
      # printf "<<%s>> " "$result" # DEBUG
Repository: Kindelia/HVM
File: src/ast.rs (Rust)

Code before:
  /// that is, if definition `A` requires `B`, `B: A` is in the return map.
  /// This is used to propagate unsafe definitions to others that depend on them.
  /// 
  /// This solution has linear complexity on the number of definitions in the
  /// book and the number of direct references in each definition, but it also
  /// traverses each definition's trees entirely once.
  ///
  /// Complexity: O(d*t + r)
  /// - `d` is the number of definitions in the book
  /// - `r` is the number of direct references in each definition
  /// - `t` is the number of nodes in each tree
  fn direct_dependencies_reversed<'name>(&'name self) -> BTreeMap<&'name str, BTreeSet<&'name str>> {
    let mut result = BTreeMap::new();
    for (name, _) in self.defs.iter() {
      result.insert(name.as_str(), BTreeSet::new());
    }

    let mut process = |tree: &'name Tree, name: &'name str| {
      for dependency in tree.direct_dependencies() {
        match result.entry(dependency) {
          Entry::Vacant(_) => panic!("global definition depends on undeclared reference"),
          Entry::Occupied(mut entry) => {
            // dependency => name
            entry.get_mut().insert(name);
          },
        }
      }
    };

    for (name, net) in self.defs.iter() {
      process(&net.root, name);
      for (_, r1, r2) in net.rbag.iter() {
        process(r1, name);
        process(r2, name);
      }
    }
    result
  }
}


Review comment (suggestion):
```suggestion
        result
          .get_mut()
          .expect("global definition depends on undeclared reference")
          .insert(name);
```

Code after:
      }
    }
  }

  /// Calculates the dependents of each definition, that is, if definition `A`
  /// requires `B`, `B: A` is in the return map. This is used to propagate unsafe
  /// definitions to others that depend on them.
  /// 
  /// This solution has linear complexity on the number of definitions in the
  /// book and the number of direct references in each definition, but it also
  /// traverses each definition's trees entirely once.
  ///
  /// Complexity: O(d*t + r)
  /// - `d` is the number of definitions in the book
  /// - `r` is the number of direct references in each definition
  /// - `t` is the number of nodes in each tree
  fn direct_dependents<'name>(&'name self) -> BTreeMap<&'name str, BTreeSet<&'name str>> {
    let mut result = BTreeMap::new();
    for (name, _) in self.defs.iter() {
      result.insert(name.as_str(), BTreeSet::new());
    }

    let mut process = |tree: &'name Tree, name: &'name str| {
      for dependency in tree.direct_dependencies() {
        result
          .get_mut(dependency)
          .expect("global definition depends on undeclared reference")
          .insert(name);
      }
    };

    for (name, net) in self.defs.iter() {
      process(&net.root, name);
      for (_, r1, r2) in net.rbag.iter() {
        process(r1, name);
        process(r2, name);
      }
    }
    result
  }
}
Repository: Megvii-BaseDetection/YOLOX
File: yolox/models/build.py (Python)

Code before:
def yolox_nano(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-nano", pretrained, num_classes, device)


def yolox_tiny(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-tiny", pretrained, num_classes, device)


def yolox_s(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-s", pretrained, num_classes, device)


def yolox_m(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-m", pretrained, num_classes, device)


def yolox_l(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-l", pretrained, num_classes, device)


def yolox_x(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-x", pretrained, num_classes, device)


def yolov3(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-tiny", pretrained, num_classes, device)


def yolox_custom(ckpt_path: str = None, exp_path: str = None, device: str = None) -> nn.Module:
    return create_yolox_model("yolox_custom", ckpt_path=ckpt_path, exp_path=exp_path, device=device)


Review comment (bug):
Here is a bug, here, plz also help to fix this. The string here should be `yolov3`

Code after:

def yolox_nano(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-nano", pretrained, num_classes, device)


def yolox_tiny(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-tiny", pretrained, num_classes, device)


def yolox_s(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-s", pretrained, num_classes, device)


def yolox_m(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-m", pretrained, num_classes, device)


def yolox_l(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-l", pretrained, num_classes, device)


def yolox_x(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolox-x", pretrained, num_classes, device)


def yolov3(pretrained: bool = True, num_classes: int = 80, device: str = None) -> nn.Module:
    return create_yolox_model("yolov3", pretrained, num_classes, device)


def yolox_custom(ckpt_path: str = None, exp_path: str = None, device: str = None) -> nn.Module:
    return create_yolox_model("yolox_custom", ckpt_path=ckpt_path, exp_path=exp_path, device=device)
Repository: NationalSecurityAgency/ghidra
File: Ghidra/Features/Base/src/main/java/ghidra/app/plugin/core/symboltree/actions/ConvertToClassAction.java (Java)

Code before:
	@Override
	protected void actionPerformed(SymbolTreeActionContext context) {
		TreePath[] selectionPaths = context.getSelectedSymbolTreePaths();

		Program program = context.getProgram();
		GTreeNode node = (GTreeNode) selectionPaths[0].getLastPathComponent();

		if (node instanceof SymbolNode) {
			Symbol symbol = ((SymbolNode) node).getSymbol();
			Namespace parent = (Namespace) symbol.getObject();
			if (parent != null) {
				convertToClass(program, parent);
				program.flushEvents();
				context.getSymbolTree().startEditing(node, parent.getName());
			}
		}
	}

	private static void convertToClass(Program program, Namespace ns) {
		int id = program.startTransaction("Convert To Class");
		boolean success = false;
		try {
			NamespaceUtils.convertNamespaceToClass(ns);
			success = true;
		} catch (InvalidInputException e) {
			// can't occur, checked in isEnabledForContext
			throw new AssertException(e);
		} finally {
			program.endTransaction(id, success);
		}
	}

}


Review comment (suggestion):
This statement does not seem true.  The `isEnabledForContext()` does not appear to be validating the name.   Maybe this would be better stated by saying that 'should not happen since we are reusing an existing name'


Code after:
			return symbol.getSymbolType() == SymbolType.NAMESPACE;
		}
		return false;
	}

	@Override
	protected void actionPerformed(SymbolTreeActionContext context) {
		TreePath[] selectionPaths = context.getSelectedSymbolTreePaths();

		Program program = context.getProgram();
		GTreeNode node = (GTreeNode) selectionPaths[0].getLastPathComponent();

		Symbol symbol = ((SymbolNode) node).getSymbol();
		Namespace parent = (Namespace) symbol.getObject();
		if (parent != null) {
			convertToClass(program, parent);
			program.flushEvents();
			context.getSymbolTree().startEditing(node, parent.getName());
		}
	}

	private static void convertToClass(Program program, Namespace ns) {
		int id = program.startTransaction(NAME);
		boolean success = false;
		try {
			NamespaceUtils.convertNamespaceToClass(ns);
			success = true;
		} catch (InvalidInputException e) {
			// This is thrown when the provided namespace is a function
			// It was checked in isEnabledForContext and thus cannot occur
			throw new AssertException(e);
		} finally {
			program.endTransaction(id, success);
		}
	}

}