ronantakizawa/codereview-bench huggingface dataset:
Repository: sm64pc/sm64pc
File: pisetup.sh (Shell)

Code before:
#!/bin/bash
# Super Mario 64 PC on Raspberry Pi
# Find latest updates and code on https://www.github.com/sm64pc/sm64pc
# NOTE: If you clone the repo, source must be copied in ~/src/sm64pi/sm64pc/
# ToDo: Test on more Pi models with fresh Raspbian and allow existing src folders to be updated.
#
clear
echo "This script will assist with compiling Super Mario 64 on Raspbian 10"
echo "Note that accelerated OpenGL (vc4_drm) is required for maximum performance"
echo "Checking Raspberry Pi model..."
lowmem=0
pi=0
pimodel=$(uname -m 2>/dev/null || echo unknown)
pitype=$(tr -d '\0' < /sys/firmware/devicetree/base/model)
repo_url="https://github.com/sm64pc/sm64pc"

if [[ $pimodel =~ "armv6" ]]
then
   echo -e "\nRaspberry Pi Model 1/0(W) detected (LOWMEM)"
   echo "Warning: Additional steps may be required to safely compile and maximize performance"
   pi=1;
   lowmem=1;
   exp=1;
fi

if [[ $pimodel =~ "armv7" ]]
then
   echo -e "\nRaspberry Pi Model 2/3/4 detected (32bit)"
   pi=2;
   lowmem=0;
fi

if [[ $pimodel =~ "aarch64" && $pitype =~ "4" ]]
then
   echo -e "\nRaspberry Pi Model 4 (64 bits) detected"
   echo "Audio errors reported"
   echo "Fixing audio config, reboot after compilation completes to activate"
   sudo sed -i 's/load-module module-udev-detect/load-module module-udev-detect tsched=0/' /etc/pulse/default.pa
	#load-module module-udev-detect tsched=0
   pi=4;

Review comment (suggestion):
```suggestion
repo_url="https://github.com/sm64pc/sm64ex"
```

The repo was renamed a while back, so you should use the updated URL, though the old one does still work.

Code after:
#!/bin/bash
# Super Mario 64 PC on Raspberry Pi
# Find latest updates and code on https://www.github.com/sm64pc/sm64ex
# NOTE: If you clone the repo, source must be copied in ~/src/sm64pc/sm64ex/
# ToDo: Test on more Pi models with fresh Raspbian and allow existing src folders to be updated.
#
clear
echo "This script will assist with compiling Super Mario 64 on Raspbian 10"
echo "Note that accelerated OpenGL (vc4_drm) is required for maximum performance"
echo "Checking Raspberry Pi model..."
lowmem=0
pi=0
pimodel=$(uname -m 2>/dev/null || echo unknown)
pitype=$(tr -d '\0' < /sys/firmware/devicetree/base/model)
repo_url="https://github.com/sm64pc/sm64ex"

if [[ $pimodel =~ "armv6" ]]
then
   echo -e "\nRaspberry Pi Model 1/0(W) detected (LOWMEM)"
   echo "Warning: Additional steps may be required to safely compile and maximize performance"
   pi=1;
   lowmem=1;
   exp=1;
fi

if [[ $pimodel =~ "armv7" ]]
then
   echo -e "\nRaspberry Pi Model 2/3/4 detected (32bit)"
   pi=2;
   lowmem=0;
fi

if [[ $pimodel =~ "aarch64" && $pitype =~ "4" ]]
then
   echo -e "\nRaspberry Pi Model 4 (64 bits) detected"
   echo "Audio errors reported"
   echo "Fixing audio config, reboot after compilation completes to activate"
   sudo sed -i 's/load-module module-udev-detect/load-module module-udev-detect tsched=0/' /etc/pulse/default.pa
	#load-module module-udev-detect tsched=0
   pi=4;
Repository: smol-ai/GodMode
File: providers/oobabooga.js (JavaScript)

Code before:
const Store = require('electron-store');
const store = new Store();

const Provider = require('./provider');

class OobaBooga extends Provider {
	static webviewId = 'webviewOoba';
	static fullName = 'OobaBooga';

	static url = 'http://127.0.0.1:7860/';

  // todo: let user customize their preferred template.
  static templateFn = input => `Common sense questions and answers

  Question: ${input}
  Factual answer:`

	static handleInput(input) {
		this.getWebview().executeJavaScript(`
        function simulateUserInput(element, text) {
          const inputEvent = new Event('input', { bubbles: true });
          element.focus();
          element.value = text;
          element.dispatchEvent(inputEvent);
        }
        try {
          var inputElement = document.querySelector('#main textarea');
          simulateUserInput(inputElement, \`${this.templateFn(input)}\`);
        } catch (err) {
          console.error(err);
          console.error(err.toString());
          console.log(\`${this.templateFn(input)}\`);
          console.error(err);

Review comment (suggestion):
```suggestion
	static fullName = 'Local Models (OobaBooga)';
```

Code after:
const Store = require('electron-store');
const store = new Store();

const Provider = require('./provider');

class OobaBooga extends Provider {
	static webviewId = 'webviewOoba';
	static fullName = 'Local Models (OobaBooga)';

	static url = 'http://127.0.0.1:7860/';

  // todo: let user customize their preferred template.
  static templateFn = input => `Common sense questions and answers

  Question: ${input}
  Factual answer:`

	static handleInput(input) {
		this.getWebview().executeJavaScript(`
        function simulateUserInput(element, text) {
          const inputEvent = new Event('input', { bubbles: true });
          element.focus();
          element.value = text;
          element.dispatchEvent(inputEvent);
        }
        try {
          var inputElement = document.querySelector('#main textarea');
          simulateUserInput(inputElement, \`${this.templateFn(input)}\`);
        } catch (err) {
          console.error(err);
          console.error(err.toString());
          console.log(\`${this.templateFn(input)}\`);
          console.error(err);
Repository: smol-ai/GodMode
File: providers/together.js (JavaScript)

Code before:
const Store = require('electron-store');
const store = new Store();

const Provider = require('./provider');

class Together extends Provider {
	static webviewId = 'webviewTOGETHER';
  static fullName = 'Together (RedPajama, StarCoder, Falcon, etc)';


	static url = 'https://api.together.xyz/playground/chat';

	static handleInput(input) {
		this.getWebview().executeJavaScript(`
    var inputElement = document.querySelector('form textarea[placeholder*="Enter text here"]');
    inputElement.focus();
    inputElement.value = "${input}";
    // try to send keyboard event to trigger the re-enable of the disabled button
    // thanks chatgpt!
    var event = new Event('input', { bubbles: true });
    event.simulated = true;
    var tracker = inputElement._valueTracker;
    if (tracker) {
      tracker.setValue("${input}");
    }
    // Dispatch the event after a short delay to fix the button state
    setTimeout(function() {
      inputElement.dispatchEvent(event);
    }, 100);
    `);
	}

	static handleSubmit() {

Review comment (suggestion):
```suggestion
  static fullName = 'Together (WIP - RedPajama, StarCoder, Falcon, etc)';
```

Code after:
const Store = require('electron-store');
const store = new Store();

const Provider = require('./provider');

class Together extends Provider {
	static webviewId = 'webviewTOGETHER';
	static fullName = 'Together (RedPajama, StarCoder, Falcon, etc)';

	static url = 'https://api.together.xyz/playground/chat';

	static handleInput(input) {
		this.getWebview().executeJavaScript(`
    var inputElement = document.querySelector('form textarea[placeholder*="Enter text here"]');
    var nativeTextAreaValueSetter = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, "value").set;
    nativeTextAreaValueSetter.call(inputElement, "${input}");
    var event = new Event('input', { bubbles: true});
    inputElement.dispatchEvent(event);
    `);
	}

	// inputElement.focus();
	// inputElement.value = "${input}";
	// // try to send keyboard event to trigger the re-enable of the disabled button
	// // thanks chatgpt!
	// var event = new Event('input', { bubbles: true });
	// event.simulated = true;
	// var tracker = inputElement._valueTracker;
	// if (tracker) {
	//   tracker.setValue("${input}");
	// }
	// // Dispatch the event after a short delay to fix the button state
	// setTimeout(function() {
Repository: smol-ai/GodMode
File: interface.js (JavaScript)

Code before:
// Import necessary modules
const log = require('electron-log');
const Store = require('electron-store');
const store = new Store();

// Initialize the providers
const providers = {
	OpenAi: require('./providers/openai'),
	Bard: require('./providers/bard'),
	Bing: require('./providers/bing'),
	Claude: require('./providers/claude'),
	Claude2: require('./providers/claude2'),
	OobaBooga: require('./providers/oobabooga'),
	Smol: require('./providers/smol'),
	HuggingChat: require('./providers/huggingchat'),
	Phind: require('./providers/phind'),
	Perplexity: require('./providers/perplexity'),
};

const {
	drawPanes,
	getEnabledProviders,
	updateSplitSizes,
} = require('./src/panes');

/* ========================================================================== */
/* Create Panes                                                               */
/* ========================================================================== */

const enabledProviders = getEnabledProviders(providers);

drawPanes(enabledProviders);

// Create an array of pane IDs for the enabled providers
const panes = enabledProviders.map((provider) => `#${provider.paneId()}`);
log.info('panes', panes);

// Initialize the Split.js library to create split views with the pane IDs
const splitInstance = Split(panes, {
	direction: 'horizontal',
	minSize: 0,
});

Review comment (suggestion):
```suggestion
	Perplexity: require('./providers/perplexity'),
	Phind: require('./providers/phind'),
	HuggingChat: require('./providers/huggingchat'),
	OobaBooga: require('./providers/oobabooga'),
	Smol: require('./providers/smol'),
```

Code after:
// Import necessary modules
const log = require('electron-log');
const Store = require('electron-store');
const store = new Store();

// Initialize the providers
const providers = {
	OpenAi: require('./providers/openai'),
	Bard: require('./providers/bard'),
	Bing: require('./providers/bing'),
	Claude: require('./providers/claude'),
	Claude2: require('./providers/claude2'),
	Perplexity: require('./providers/perplexity'),
	Phind: require('./providers/phind'),
	HuggingChat: require('./providers/huggingchat'),
	OobaBooga: require('./providers/oobabooga'),
	Smol: require('./providers/smol'),
};

const {
	drawPanes,
	getEnabledProviders,
	updateSplitSizes,
} = require('./src/panes');

/* ========================================================================== */
/* Create Panes                                                               */
/* ========================================================================== */

const enabledProviders = getEnabledProviders(providers);

drawPanes(enabledProviders);

// Create an array of pane IDs for the enabled providers
const panes = enabledProviders.map((provider) => `#${provider.paneId()}`);
log.info('panes', panes);

// Initialize the Split.js library to create split views with the pane IDs
const splitInstance = Split(panes, {
	direction: 'horizontal',
	minSize: 0,
});
Repository: solidjs/solid
File: packages/solid/web/src/server-mock.ts (TypeScript)

Code before:
//@ts-nocheck
export function renderToString<T>(
  fn: () => T,
  options?: {
    nonce?: string;
    renderId?: string;
  }
): string {}
export function renderToStringAsync<T>(
  fn: () => T,
  options?: {
    timeoutMs?: number;
    nonce?: string;
    renderId?: string;
  }
): Promise<string> {}
export function renderToStream<T>(
  fn: () => T,
  options?: {
    nonce?: string;
    renderId?: string;
    onCompleteShell?: () => void;
    onCompleteAll?: () => void;
  }
): {
  pipe: (writable: { write: (v: string) => void }) => void;
  pipeTo: (writable: WritableStream) => void;
} {}
export function ssr(template: string[] | string, ...nodes: any[]): { t: string } {}
export function resolveSSRNode(node: any): string {}

Review comment (suggestion):
This is debatable, we can try throwing, but sometimes may the user's making something env agnostic, so they don't want the app breaks while importing/using such functions!

Code after:
//@ts-nocheck
function throwInBrowser(func: Function) {
  const err = new Error(`${func.name} is not supported in the browser, returning undefined`);

  console.error(err);
}

export function renderToString<T>(
  fn: () => T,
  options?: {
    nonce?: string;
    renderId?: string;
  }
): string {
  throwInBrowser(renderToString);
}
export function renderToStringAsync<T>(
  fn: () => T,
  options?: {
    timeoutMs?: number;
    nonce?: string;
    renderId?: string;
  }
): Promise<string> {
  throwInBrowser(renderToStringAsync);
}
export function renderToStream<T>(
  fn: () => T,
  options?: {
    nonce?: string;
Repository: solidjs/solid
File: packages/solid/src/reactive/observable.ts (TypeScript)

Code before:
  | {
    next?: (v: T) => void;
    error?: (v: any) => void;
    complete?: (v: boolean) => void;
  };
/**
 * creates a simple observable from a signal's accessor to be used with the `from` operator of observable libraries like e.g. rxjs
 * ```typescript
 * import { from } from "rxjs";
 * const [s, set] = createSignal(0);
 * const obsv$ = from(observable(s));
 * obsv$.subscribe((v) => console.log(v));
 * ```
 * description https://www.solidjs.com/docs/latest/api#observable
 */
export function observable<T>(input: Accessor<T>) {
  const $$observable = getSymbol();
  return {
    subscribe(observer: ObservableObserver<T>) {
      if (!(observer instanceof Object) || observer == null) {
        throw new TypeError("Expected the observer to be an object.");
      }

      const handler = typeof observer === 'function'
        ? observer
        : observer.next?.bind(observer);

      if (!handler) {
        return { unsubscribe() { } };
      }

      const dispose = createRoot((disposer) => {
        createComputed(() => {
          const v = input();
          untrack(() => handler(v));
        });

        return disposer;
      })

      if (getOwner()) onCleanup(dispose);

      return {
        unsubscribe() {
          dispose();
        }
      };
    },
    [$$observable]() {
      return this;
    }

Review comment (suggestion):
Small nit. We don't use optional chaining in Solid core as it breaks some of the platforms we support. And we won't transpile the source code. Don't always trust it to do the most performant thing. 

Code after:
  }
}

function getSymbol() {
  return Symbol.observable || "@@observable";
}

export type ObservableObserver<T> =
  | ((v: T) => void)
  | {
    next?: (v: T) => void;
    error?: (v: any) => void;
    complete?: (v: boolean) => void;
  };
/**
 * creates a simple observable from a signal's accessor to be used with the `from` operator of observable libraries like e.g. rxjs
 * ```typescript
 * import { from } from "rxjs";
 * const [s, set] = createSignal(0);
 * const obsv$ = from(observable(s));
 * obsv$.subscribe((v) => console.log(v));
 * ```
 * description https://www.solidjs.com/docs/latest/api#observable
 */
export function observable<T>(input: Accessor<T>) {
  const $$observable = getSymbol();
  return {
    subscribe(observer: ObservableObserver<T>) {
      if (!(observer instanceof Object) || observer == null) {
        throw new TypeError("Expected the observer to be an object.");
      }

      const handler = typeof observer === 'function'
        ? observer
        : observer.next && observer.next.bind(observer);

      if (!handler) {
        return { unsubscribe() { } };
      }

      const dispose = createRoot((disposer) => {
        createComputed(() => {
          const v = input();
          untrack(() => handler(v));
        });

        return disposer;
      })

      if (getOwner()) onCleanup(dispose);
Repository: solidjs/solid
File: packages/solid/src/reactive/observable.ts (TypeScript)

Code before:
import { Accessor, createComputed, createSignal, onCleanup, Setter, untrack } from "./signal";

function getSymbol() {
  const SymbolCopy = Symbol as any;
  return SymbolCopy.observable || "@@observable";
}

export type ObservableObserver<T> =
  | ((v: T) => void)
  | {
      next: (v: T) => void;
      error?: (v: any) => void;
      complete?: (v: boolean) => void;
    };
/**
 * creates a simple observable from a signal's accessor to be used with the `from` operator of observable libraries like e.g. rxjs
 * ```typescript
 * import { from } from "rxjs";
 * const [s, set] = createSignal(0);
 * const obsv$ = from(observable(s));
 * obsv$.subscribe((v) => console.log(v));
 * ```
 * description https://www.solidjs.com/docs/latest/api#observable
 */
export function observable<T>(input: Accessor<T>) {
  const $$observable = getSymbol();
  return {
    subscribe(observer: ObservableObserver<T>) {
      if (!(observer instanceof Object) || observer == null) {
        throw new TypeError("Expected the observer to be an object.");
      }
      const handler = "next" in observer ? observer.next.bind(observer) : observer;
      let complete = false;
      createComputed(() => {

Review comment (suggestion):
As the comment above this interface suggests, ensuring that a type for `Symbol.observable` exists is necessary for Solid's `observable()` function to be properly typed for RXJS (and I imagine other observable library's as well). This is because RXJS's `from()` function expects an object with `{ [Symbol.observable](): Subscribabble<T> }`. Previously, `getSymbol()` didn't return `Symbol.observable` but instead returned `any` which breaks type interoperability.

Code after:
import { Accessor, createComputed, createRoot, createSignal, getOwner, onCleanup, Setter, untrack } from "./signal";

// Note: This will add Symbol.observable globally for all TypeScript users,
// however, we are not polyfilling Symbol.observable. Ensuring the type for
// this global symbol is present is necessary for `observable()` to be
// properly typed for 3rd party library's like RXJS.
declare global {
  interface SymbolConstructor {
    readonly observable: symbol;
  }
}

function getSymbol() {
  return Symbol.observable || "@@observable";
}

export type ObservableObserver<T> =
  | ((v: T) => void)
  | {
    next?: (v: T) => void;
    error?: (v: any) => void;
    complete?: (v: boolean) => void;
  };
/**
 * creates a simple observable from a signal's accessor to be used with the `from` operator of observable libraries like e.g. rxjs
 * ```typescript
 * import { from } from "rxjs";
 * const [s, set] = createSignal(0);
 * const obsv$ = from(observable(s));
 * obsv$.subscribe((v) => console.log(v));
 * ```
 * description https://www.solidjs.com/docs/latest/api#observable
 */
export function observable<T>(input: Accessor<T>) {
Repository: solidjs/solid
File: packages/solid/src/server/rendering.ts (TypeScript)

Code before:
    v: Promise<any> | any,
    error?: boolean,
    deferStream?: boolean
  ) => void;
  replace: (id: string, replacement: () => any) => void;
  block: (p: Promise<any>) => void;
  resources: Record<string, any>;
  suspense: Record<string, SuspenseContextType>;
  registerFragment: (v: string) => (v?: string, err?: any) => boolean;
  lazy: Record<string, Promise<any>>;
  async?: boolean;
  noHydrate: boolean;
};

export function SuspenseList(props: {
  children: string;
  revealOrder: "forwards" | "backwards" | "together";
  tail?: "collapsed" | "hidden";
}) {
  // TODO: support tail options
  return props.children;
}

export function Suspense(props: { fallback?: string; children: string }) {
  let done: undefined | ((html?: string, error?: any) => boolean);
  let clean: any;
  const ctx = sharedConfig.context!;
  const id = ctx.id + ctx.count;
  const o = createOwner();
  const value: SuspenseContextType =
    ctx.suspense[id] ||
    (ctx.suspense[id] = {
      resources: new Map<string, { loading: boolean; error: any }>(),
      completed: () => {
        const res = runSuspense();
        if (suspenseComplete(value)) {
          done!(resolveSSRNode(res));
        }
      }
    });
  function runSuspense() {
    setHydrateContext({ ...ctx, count: 0 });
    o && cleanNode(o);
    return runWithOwner(o!, () => {
      return createComponent(SuspenseContext.Provider, {
        value,
        get children() {
          return props.children;
        }
      });
    });

Review comment (suggestion):
`clean` wasn't being used anywhere anymore. maybe that's a mistake? not sure what it did

Code after:
    v: Promise<any> | any,
    error?: boolean,
    deferStream?: boolean
  ) => void;
  replace: (id: string, replacement: () => any) => void;
  block: (p: Promise<any>) => void;
  resources: Record<string, any>;
  suspense: Record<string, SuspenseContextType>;
  registerFragment: (v: string) => (v?: string, err?: any) => boolean;
  lazy: Record<string, Promise<any>>;
  async?: boolean;
  noHydrate: boolean;
};

export function SuspenseList(props: {
  children: string;
  revealOrder: "forwards" | "backwards" | "together";
  tail?: "collapsed" | "hidden";
}) {
  // TODO: support tail options
  return props.children;
}

export function Suspense(props: { fallback?: string; children: string }) {
  let done: undefined | ((html?: string, error?: any) => boolean);
  const ctx = sharedConfig.context!;
  const id = ctx.id + ctx.count;
  const o = createOwner();
  const value: SuspenseContextType =
    ctx.suspense[id] ||
    (ctx.suspense[id] = {
      resources: new Map<string, { loading: boolean; error: any }>(),
      completed: () => {
        const res = runSuspense();
        if (suspenseComplete(value)) {
          done!(resolveSSRNode(res));
        }
      }
    });
  function runSuspense() {
    setHydrateContext({ ...ctx, count: 0 });
    cleanNode(o);
    return runWithOwner(o, () => {
      return createComponent(SuspenseContext.Provider, {
        value,
        get children() {
          return props.children;
        }
      });
    });
  }
Repository: spf13/cobra
File: command.go (Go)

Code before:
		return commandFound, a, fmt.Errorf("unknown command %q for %q", argsWOflags[0], commandFound.CommandPath())
	}

	return commandFound, a, nil
}

func (c *Command) Root() *Command {
	var findRoot func(*Command) *Command

	findRoot = func(x *Command) *Command {
		if x.HasParent() {
			return findRoot(x.parent)
		} else {
			return x
		}
	}

	return findRoot(c)
}

func (c *Command) execute(a []string) (err error) {
	if c == nil {
		return fmt.Errorf("Called Execute() on a nil Command")
	}

	if len(c.Deprecated) > 0 {
		c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated)
	}

	// initialize help flag as the last point possible to allow for user
	// overriding
	c.initHelpFlag()

	err = c.ParseFlags(a)
	if err != nil {
		return err
	}
	// If help is called, regardless of other flags, return we want help
	// Also say we need help if the command isn't runnable.
	helpVal, err := c.Flags().GetBool("help")
	if err != nil {
		// should be impossible to get here as we always declare a help
		// flag in initHelpFlag()
		c.Println("\"help\" flag declared as non-bool. Please correct your code")
		return err
	}
	if helpVal || !c.Runnable() {
		return flag.ErrHelp
	}

	c.preRun()

Review comment (bug):
So if I disable suggestions, and type a wrong command, do I have a trailing `\n`?


Code after:
	}

	// root command with subcommands, do subcommand checking
	if commandFound == c && len(argsWOflags) > 0 {
		suggestions := ""
		if !c.DisableSuggestions {
			if c.SuggestionsMinimumDistance <= 0 {
				c.SuggestionsMinimumDistance = 2
			}
			similar := []string{}
			for _, cmd := range c.commands {
				if cmd.IsAvailableCommand() {
					levenshtein := ld(argsWOflags[0], cmd.Name(), true)
					if levenshtein <= c.SuggestionsMinimumDistance {
						similar = append(similar, cmd.Name())
					}
				}
			}
			if len(similar) > 0 {
				suggestions += "\n\nDid you mean this?\n"
				for _, s := range similar {
					suggestions += fmt.Sprintf("\t%v\n", s)
				}
			}
		}
		return commandFound, a, fmt.Errorf("unknown command %q for %q%s", argsWOflags[0], commandFound.CommandPath(), suggestions)
	}

	return commandFound, a, nil
}

func (c *Command) Root() *Command {
	var findRoot func(*Command) *Command

	findRoot = func(x *Command) *Command {
		if x.HasParent() {
			return findRoot(x.parent)
		} else {
			return x
		}
	}

	return findRoot(c)
}

func (c *Command) execute(a []string) (err error) {
	if c == nil {
		return fmt.Errorf("Called Execute() on a nil Command")
	}

	if len(c.Deprecated) > 0 {