ronantakizawa/codereview-bench huggingface dataset:
Repository: nvbn/thefuck
File: tests/rules/test_terraform_no_command.py (Python)

Code before:
import pytest
from thefuck.rules.terraform_no_command import match, get_new_command
from thefuck.types import Command


@pytest.mark.parametrize('script, output', [
    ('terraform appyl', 'Terraform has no command named \"appyl\". Did you mean \"apply\"?)'),
    ('terraform destory', 'Terraform has no command named \"destory\". Did you mean \"destroy\"?)')])
def test_match(script, output):
    assert match(Command(script, output))


@pytest.mark.parametrize('script, output', [
    ('terraform --version', 'Terraform v0.12.2'),
    ('terraform plan', 'No changes. Infrastructure is up-to-date.'),
    ('terraform apply', 'Apply complete! Resources: 0 added, 0 changed, 0 destroyed.'),
])
def test_not_match(script, output):
    assert not match(Command(script, output=output))


@pytest.mark.parametrize('command, new_command', [
    (Command('terraform appyl', 'Terraform has no command named \"appyl\". Did you mean \"apply\"?)'), 'terraform apply'),
    (Command('terraform destory --some-other-option', 'Terraform has no command named \"destory\". Did you mean \"destroy\"?)'), 'terraform destroy --some-other-option'),
])
def test_get_new_command(command, new_command):
    assert get_new_command(command) == new_command


Review comment (suggestion):
```suggestion
    assert not match(Command(script, output))
```

Code after:
import pytest
from thefuck.rules.terraform_no_command import match, get_new_command
from thefuck.types import Command


@pytest.mark.parametrize('script, output', [
    ('terraform appyl', 'Terraform has no command named "appyl". Did you mean "apply"?'),
    ('terraform destory', 'Terraform has no command named "destory". Did you mean "destroy"?')])
def test_match(script, output):
    assert match(Command(script, output))


@pytest.mark.parametrize('script, output', [
    ('terraform --version', 'Terraform v0.12.2'),
    ('terraform plan', 'No changes. Infrastructure is up-to-date.'),
    ('terraform apply', 'Apply complete! Resources: 0 added, 0 changed, 0 destroyed.'),
])
def test_not_match(script, output):
    assert not match(Command(script, output))


@pytest.mark.parametrize('script, output, new_command', [
    ('terraform appyl', 'Terraform has no command named "appyl". Did you mean "apply"?', 'terraform apply',),
    ('terraform destory --some-other-option', 'Terraform has no command named "destory". Did you mean "destroy"?', 'terraform destroy --some-other-option',),
])
def test_get_new_command(script, output, new_command):
    assert get_new_command(Command(script, output)) == new_command
Repository: nvbn/thefuck
File: tests/rules/test_terraform_no_command.py (Python)

Code before:
from thefuck.rules.terraform_no_command import match, get_new_command
from thefuck.types import Command


@pytest.mark.parametrize('script, output', [
    ('terraform appyl', 'Terraform has no command named \"appyl\". Did you mean \"apply\"?)'),
    ('terraform destory', 'Terraform has no command named \"destory\". Did you mean \"destroy\"?)')])
def test_match(script, output):
    assert match(Command(script, output))


@pytest.mark.parametrize('script, output', [
    ('terraform --version', 'Terraform v0.12.2'),
    ('terraform plan', 'No changes. Infrastructure is up-to-date.'),
    ('terraform apply', 'Apply complete! Resources: 0 added, 0 changed, 0 destroyed.'),
])
def test_not_match(script, output):
    assert not match(Command(script, output=output))


@pytest.mark.parametrize('command, new_command', [
    (Command('terraform appyl', 'Terraform has no command named \"appyl\". Did you mean \"apply\"?)'), 'terraform apply'),
    (Command('terraform destory --some-other-option', 'Terraform has no command named \"destory\". Did you mean \"destroy\"?)'), 'terraform destroy --some-other-option'),
])
def test_get_new_command(command, new_command):
    assert get_new_command(command) == new_command


Review comment (suggestion):
I like that you passed in string parameters and instantiated `Command` with them. How about doing the same here?

```suggestion
@pytest.mark.parametrize('script, output, new_command', [
    ('terraform appyl', 'Terraform has no command named "appyl". Did you mean "apply"?', 'terraform apply',),
    ('terraform destory --some-other-option', 'Terraform has no command named "destory". Did you mean "destroy"?', 'terraform destroy --some-other-option',),
])
def test_get_new_command(script, output, new_command):
    assert get_new_command(Command(script, output)) == new_command
```

Code after:
from thefuck.rules.terraform_no_command import match, get_new_command
from thefuck.types import Command


@pytest.mark.parametrize('script, output', [
    ('terraform appyl', 'Terraform has no command named "appyl". Did you mean "apply"?'),
    ('terraform destory', 'Terraform has no command named "destory". Did you mean "destroy"?')])
def test_match(script, output):
    assert match(Command(script, output))


@pytest.mark.parametrize('script, output', [
    ('terraform --version', 'Terraform v0.12.2'),
    ('terraform plan', 'No changes. Infrastructure is up-to-date.'),
    ('terraform apply', 'Apply complete! Resources: 0 added, 0 changed, 0 destroyed.'),
])
def test_not_match(script, output):
    assert not match(Command(script, output))


@pytest.mark.parametrize('script, output, new_command', [
    ('terraform appyl', 'Terraform has no command named "appyl". Did you mean "apply"?', 'terraform apply',),
    ('terraform destory --some-other-option', 'Terraform has no command named "destory". Did you mean "destroy"?', 'terraform destroy --some-other-option',),
])
def test_get_new_command(script, output, new_command):
    assert get_new_command(Command(script, output)) == new_command
Repository: nvbn/thefuck
File: thefuck/rules/terraform_no_command.py (Python)

Code before:
import re
from thefuck.utils import for_app

MISTAKE = r"(?<=Terraform has no command named \")(.*)(?=\"\.)"
FIX = r"(?<=Did you mean \")(.*)(?=\"\?)"


@for_app('terraform')
def match(command):
    return ('Terraform has no command named' in command.output and 'Did you mean' in command.output)


def get_new_command(command):
    mistake = re.search(MISTAKE, command.output).group(0)
    fix = re.search(FIX, command.output).group(0)
    return command.script.replace(mistake, fix)


Review comment (bug):
These lines can fail if the structure of the output message changes a bit — such as punctuation. If that ever happens, the rule will start failing. But that's better than it silently stop matching because of a stricter `match` function.

That hints at the possibility of running each rule inside a try/except block and displaying a proper error instead of letting it explode. But I digress (note taken).

Code after:
import re
from thefuck.utils import for_app

MISTAKE = r'(?<=Terraform has no command named ")([^"]+)(?="\.)'
FIX = r'(?<=Did you mean ")([^"]+)(?="\?)'


@for_app('terraform')
def match(command):
    return re.search(MISTAKE, command.output) and re.search(FIX, command.output)


def get_new_command(command):
    mistake = re.search(MISTAKE, command.output).group(0)
    fix = re.search(FIX, command.output).group(0)
    return command.script.replace(mistake, fix)
Repository: pedronauck/docz
File: core/gatsby-theme-docz/src/components/Playground/index.js (JavaScript)

Code before:
            {showLivePreview && (
              <LivePreview style={styles.preview} data-testid="live-preview" />
            )}
            <ReactResizeDetector
              handleHeight
              onResize={(width, height) => {
                setPreviewHeight(height)
              }}
            />
          </Wrapper>
          <div sx={styles.buttons}>
            <button sx={styles.button} onClick={copyCode}>
              <Icons.Clipboard size={12} />
            </button>
            <button sx={styles.button} onClick={toggleCode}>
              <Icons.Code size={12} />
            </button>
          </div>
        </div>
        {showingCode && (
          <Wrapper height={editorHeight}>
            <div style={styles.editor(theme)}>
              <LiveEditor data-testid="live-editor" />
            </div>
            <ReactResizeDetector
              handleHeight
              onResize={(width, height) => {
                setEditorHeight(height)
              }}
            />
          </Wrapper>
        )}
        {showLiveError && (
          <LiveError sx={styles.error} data-testid="live-error" />
        )}
      </LiveProvider>
    </Resizable>
  )
}


Review comment (suggestion):
Am i correct in the assumption that this was done to solve this issue #1271 ?

Because now that you are wrapping the component in a iframe the encapsulation of the editor should not be needed any more. Am i missing something? :)

Code after:
        language={language}
        theme={theme}
      >
        <div sx={styles.previewWrapper}>
          <Wrapper height={previewHeight}>
            {showLivePreview && (
              <LivePreview style={styles.preview} data-testid="live-preview" />
            )}
            <ReactResizeDetector
              handleHeight
              onResize={(width, height) => {
                setPreviewHeight(height)
              }}
            />
          </Wrapper>
          <div sx={styles.buttons}>
            <button sx={styles.button} onClick={copyCode}>
              <Icons.Clipboard size={12} />
            </button>
            <button sx={styles.button} onClick={toggleCode}>
              <Icons.Code size={12} />
            </button>
          </div>
        </div>
        {showingCode && (
          <Wrapper height={editorHeight}>
            <div style={styles.editor(theme)}>
              <LiveEditor data-testid="live-editor" />
            </div>
            <ReactResizeDetector
              handleHeight
              onResize={(width, height) => {
                setEditorHeight(height)
              }}
            />
          </Wrapper>
        )}
        {showLiveError && (
          <LiveError sx={styles.error} data-testid="live-error" />
        )}
      </LiveProvider>
    </Resizable>
  )
}
Repository: pedroslopez/whatsapp-web.js
File: src/authStrategies/BaseAuthStrategy.js (JavaScript)

Code before:
'use strict';

/**
 * Base class which all authentication strategies extend
 */
class BaseAuthStrategy {
    constructor() {}
    setup(client) {
        this.client = client;
    }
    async beforeBrowserInitialized() {}
    async afterBrowserInitialized() {}
    async onAuthenticationNeeded() {
        return {
            failed: false,
            restart: false,
            failureEventPayload: undefined
        };
    }
    async getAuthEventPayload() {}
    async authReady() {}
    async logout() {}
}

module.exports = BaseAuthStrategy;

Review comment (security):
Let's try to name these "hooks" to indicate a bit more clearly when they're called, I would suggest 
```suggestion
    async afterAuthReady() {}
```

Code after:
'use strict';

/**
 * Base class which all authentication strategies extend
 */
class BaseAuthStrategy {
    constructor() {}
    setup(client) {
        this.client = client;
    }
    async beforeBrowserInitialized() {}
    async afterBrowserInitialized() {}
    async onAuthenticationNeeded() {
        return {
            failed: false,
            restart: false,
            failureEventPayload: undefined
        };
    }
    async getAuthEventPayload() {}
    async afterAuthReady() {}
    async disconnect() {}
    async destroy() {}
    async logout() {}
}

module.exports = BaseAuthStrategy;
Repository: pedroslopez/whatsapp-web.js
File: src/authStrategies/RemoteAuth.js (JavaScript)

Code before:
'use strict';

const path = require('path');
const fs = require('fs-extra');
const unzipper = require('unzipper');
const archiver = require('archiver');
const { Events } = require('./../util/Constants');
const BaseAuthStrategy = require('./BaseAuthStrategy');

/**
 * Remote-based authentication
 * @param {object} options - options
 * @param {object} options.store - Remote database store instance
 * @param {string} options.clientId - Client id to distinguish instances if you are using multiple, otherwise keep null if you are using only one instance
 * @param {string} options.dataPath - Change the default path for saving session files, default is: "./.wwebjs_auth/" 
 * @param {number} options.backupSyncIntervalMs - Sets the time interval for periodic session backups. Accepts values starting from 60000ms {1 minute}
 */
class RemoteAuth extends BaseAuthStrategy {
    constructor({ clientId, dataPath, store, backupSyncIntervalMs } = {}) {
        super();

        const idRegex = /^[-_\w]+$/i;
        if (clientId && !idRegex.test(clientId)) {
            throw new Error('Invalid clientId. Only alphanumeric characters, underscores and hyphens are allowed.');
        }
        if (!backupSyncIntervalMs || backupSyncIntervalMs < 60000) {
            throw new Error('Invalid backupSyncIntervalMs. Accepts values starting from 60000ms {1 minute}.');
        }
        if(!store) throw new Error('Remote database store is required.');

Review comment (suggestion):
We need some try-catch since this modules are optional

```
try {
   const fs = require('fs-extra');
   const unzipper = require('unzipper');
const archiver = require('archiver');
} catch {
    console.log('You don\'t have the optional packages, install .......')
    process.exit(1);
}```

Code after:
'use strict';

/* Require Optional Dependencies */
try {
    var fs = require('fs-extra');
    var unzipper = require('unzipper');
    var archiver = require('archiver');
} catch {
    throw new Error('Optional Dependencies [fs-extra, unzipper, archiver] are required to use RemoteAuth. Make sure to run npm install correctly and remove the --no-optional flag');
}

const path = require('path');
const { Events } = require('./../util/Constants');
const BaseAuthStrategy = require('./BaseAuthStrategy');

/**
 * Remote-based authentication
 * @param {object} options - options
 * @param {object} options.store - Remote database store instance
 * @param {string} options.clientId - Client id to distinguish instances if you are using multiple, otherwise keep null if you are using only one instance
 * @param {string} options.dataPath - Change the default path for saving session files, default is: "./.wwebjs_auth/" 
 * @param {number} options.backupSyncIntervalMs - Sets the time interval for periodic session backups. Accepts values starting from 60000ms {1 minute}
 */
class RemoteAuth extends BaseAuthStrategy {
    constructor({ clientId, dataPath, store, backupSyncIntervalMs } = {}) {
        super();

        const idRegex = /^[-_\w]+$/i;
        if (clientId && !idRegex.test(clientId)) {
Repository: pedroslopez/whatsapp-web.js
File: src/util/Injected.js (JavaScript)

Code before:
        return Object.assign(media, {
            mimetype: options.mimeType,
            data: dataUrl.replace(`data:${options.mimeType};base64,`, '')
        });
    };

    window.WWebJS.setPicture = async (chatid, media) => {
        const thumbnail = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 96 });
        const profilePic = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 640 });

        const chatWid = window.Store.WidFactory.createWid(chatid);
        try {
            const res = await window.Store.GroupUtils.sendSetPicture(chatWid, thumbnail, profilePic);
            return res ? res.status === 200 : false;
        } catch (err) {
            if(err.name === 'ServerStatusCodeError') return false;
            throw err;
        }
    };

    window.WWebJS.deletePicture = async (chatid) => {
        const chatWid = window.Store.WidFactory.createWid(chatid);
        try {
            const res = await window.Store.GroupUtils.requestDeletePicture(chatWid);
            return res ? res.status === 200 : false;
        } catch (err) {
            if(err.name === 'ServerStatusCodeError') return false;
            throw err;
        }
    };
};


Review comment (suggestion):
```suggestion
        try {
          const collection = window.Store.ProfilePicThumb.get(chatid);
          if (!collection.canDelete()) return;
```

Code after:
        return Object.assign(media, {
            mimetype: options.mimeType,
            data: dataUrl.replace(`data:${options.mimeType};base64,`, '')
        });
    };

    window.WWebJS.setPicture = async (chatid, media) => {
        const thumbnail = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 96 });
        const profilePic = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 640 });

        const chatWid = window.Store.WidFactory.createWid(chatid);
        try {
            const collection = window.Store.ProfilePicThumb.get(chatid);
            if (!collection.canSet()) return;

            const res = await window.Store.GroupUtils.sendSetPicture(chatWid, thumbnail, profilePic);
            return res ? res.status === 200 : false;
        } catch (err) {
            if(err.name === 'ServerStatusCodeError') return false;
            throw err;
        }
    };

    window.WWebJS.deletePicture = async (chatid) => {
        const chatWid = window.Store.WidFactory.createWid(chatid);
        try {
            const collection = window.Store.ProfilePicThumb.get(chatid);
            if (!collection.canDelete()) return;

            const res = await window.Store.GroupUtils.requestDeletePicture(chatWid);
            return res ? res.status === 200 : false;
        } catch (err) {
            if(err.name === 'ServerStatusCodeError') return false;
            throw err;
        }
    };
};
Repository: pedroslopez/whatsapp-web.js
File: src/util/Injected.js (JavaScript)

Code before:

        return Object.assign(media, {
            mimetype: options.mimeType,
            data: dataUrl.replace(`data:${options.mimeType};base64,`, '')
        });
    };

    window.WWebJS.setPicture = async (chatid, media) => {
        const thumbnail = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 96 });
        const profilePic = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 640 });

        const chatWid = window.Store.WidFactory.createWid(chatid);
        try {
            const res = await window.Store.GroupUtils.sendSetPicture(chatWid, thumbnail, profilePic);
            return res ? res.status === 200 : false;
        } catch (err) {
            if(err.name === 'ServerStatusCodeError') return false;
            throw err;
        }
    };

    window.WWebJS.deletePicture = async (chatid) => {
        const chatWid = window.Store.WidFactory.createWid(chatid);
        try {
          const collection = window.Store.ProfilePicThumb.get(chatid);
          if (!collection.canDelete()) return;
            const res = await window.Store.GroupUtils.requestDeletePicture(chatWid);
            return res ? res.status === 200 : false;
        } catch (err) {
            if(err.name === 'ServerStatusCodeError') return false;
            throw err;
        }
    };
};


Review comment (suggestion):
```suggestion
            const collection = window.Store.ProfilePicThumb.get(chatid);
            if (!collection.canDelete()) return;
```

ESLint

Code after:

        return Object.assign(media, {
            mimetype: options.mimeType,
            data: dataUrl.replace(`data:${options.mimeType};base64,`, '')
        });
    };

    window.WWebJS.setPicture = async (chatid, media) => {
        const thumbnail = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 96 });
        const profilePic = await window.WWebJS.cropAndResizeImage(media, { asDataUrl: true, mimetype: 'image/jpeg', size: 640 });

        const chatWid = window.Store.WidFactory.createWid(chatid);
        try {
            const collection = window.Store.ProfilePicThumb.get(chatid);
            if (!collection.canSet()) return;

            const res = await window.Store.GroupUtils.sendSetPicture(chatWid, thumbnail, profilePic);
            return res ? res.status === 200 : false;
        } catch (err) {
            if(err.name === 'ServerStatusCodeError') return false;
            throw err;
        }
    };

    window.WWebJS.deletePicture = async (chatid) => {
        const chatWid = window.Store.WidFactory.createWid(chatid);
        try {
            const collection = window.Store.ProfilePicThumb.get(chatid);
            if (!collection.canDelete()) return;

            const res = await window.Store.GroupUtils.requestDeletePicture(chatWid);
            return res ? res.status === 200 : false;
        } catch (err) {
            if(err.name === 'ServerStatusCodeError') return false;
            throw err;
        }
    };
};
Repository: pedroslopez/whatsapp-web.js
File: src/authStrategies/LocalAuth.js (JavaScript)

Code before:
        this.dataPath = path.resolve(dataPath || './.wwebjs_auth/');
        this.clientId = clientId;
    }

    async beforeBrowserInitialized() {
        const puppeteerOpts = this.client.options.puppeteer;
        const sessionDirName = this.clientId ? `session-${this.clientId}` : 'session';
        const dirPath = path.join(this.dataPath, sessionDirName);

        if(puppeteerOpts.userDataDir && puppeteerOpts.userDataDir !== dirPath) {
            throw new Error('LocalAuth is not compatible with a user-supplied userDataDir.');
        }

        fs.mkdirSync(dirPath, { recursive: true });
        
        this.client.options.puppeteer = {
            ...puppeteerOpts,
            userDataDir: dirPath
        };

        this.userDataDir = dirPath;
    }

    async logout() {
        if (this.userDataDir) {
            await this.client.pupBrowser.close();
            return (fs.rmSync ? fs.rmSync : fs.rmdirSync).call(this, this.userDataDir, { recursive: true, force: true });
        }
    }

}

module.exports = LocalAuth;

Review comment (refactor):
Any browser manipulation should be done on the `Client` - could we move this to the client's logout function?

Code after:
        this.dataPath = path.resolve(dataPath || './.wwebjs_auth/');
        this.clientId = clientId;
    }

    async beforeBrowserInitialized() {
        const puppeteerOpts = this.client.options.puppeteer;
        const sessionDirName = this.clientId ? `session-${this.clientId}` : 'session';
        const dirPath = path.join(this.dataPath, sessionDirName);

        if(puppeteerOpts.userDataDir && puppeteerOpts.userDataDir !== dirPath) {
            throw new Error('LocalAuth is not compatible with a user-supplied userDataDir.');
        }

        fs.mkdirSync(dirPath, { recursive: true });
        
        this.client.options.puppeteer = {
            ...puppeteerOpts,
            userDataDir: dirPath
        };

        this.userDataDir = dirPath;
    }

    async logout() {
        if (this.userDataDir) {
            return (fs.rmSync ? fs.rmSync : fs.rmdirSync).call(this, this.userDataDir, { recursive: true, force: true });
        }
    }

}

module.exports = LocalAuth;