text:
"use strict";

//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------

var assert = require("chai").assert,
    proxyquire = require("proxyquire"),
    sinon = require("sinon"),
    rules = require("../../lib/rules"),
    Config = require("../../lib/config");

require("shelljs/global");
proxyquire = proxyquire.noCallThru().noPreserveCache();

/*global tempdir, mkdir, rm, cp*/

//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------

describe("CLIEngine", function() {

    var examplePluginName = "eslint-plugin-example",
        examplePluginNameWithNamespace = "@eslint/eslint-plugin-example",
        requireStubs = {},
        examplePlugin = { rules: { "example-rule": require("../fixtures/rules/custom-rule") } },
        CLIEngine,
        examplePreprocessorName = "eslint-plugin-processor";

    requireStubs[examplePluginName] = examplePlugin;
    requireStubs[examplePluginNameWithNamespace] = examplePlugin;
    requireStubs[examplePreprocessorName] = require("../fixtures/processors/custom-processor");

    beforeEach(function() {
        CLIEngine = proxyquire("../../lib/cli-engine", requireStubs);
    });

    describe("executeOnText()", function() {

        var engine;

        it("should report three messages when using local cwd .eslintrc", function() {

            engine = new CLIEngine();

            var report = engine.executeOnText("var foo = 'bar';");
            assert.equal(report.results.length, 1);
            assert.equal(report.errorCount, 4);
            assert.equal(report.warningCount, 0);
            assert.equal(report.results[0].messages.length, 4);
            assert.equal(report.results[0].messages[0].ruleId, "strict");
            assert.equal(report.results[0].messages[1].ruleId, "eol-last");
            assert.equal(report.results[0].messages[2].ruleId, "no-unused-vars");
            assert.equal(report.results[0].messages[3].ruleId, "quotes");
        });

        it("should report one message when using specific config file", function() {

            engine = new CLIEngine({
                configFile: "tests/fixtures/configurations/quotes-error.json",
                reset: true,
                useEslintrc: false
            });

            var report = engine.executeOnText("var foo = 'bar';");
            assert.equal(report.results.length, 1);
            assert.equal(report.errorCount, 1);
            assert.equal(report.warningCount, 0);
            assert.equal(report.results[0].messages.length, 1);
            assert.equal(report.results[0].messages[0].ruleId, "quotes");
            assert.equal(report.results[0].errorCount, 1);
            assert.equal(report.results[0].warningCount, 0);
        });

        it("should report the filename when passed in", function() {

            engine = new CLIEngine();

            var report = engine.executeOnText("var foo = 'bar';", "test.js");
            assert.equal(report.results[0].filePath, "test.js");
        });

        it("should return a warning when given a filename by --stdin-filename in excluded files list", function() {
            engine = new CLIEngine({
                ignorePath: "tests/fixtures/.eslintignore"
            });

            var report = engine.executeOnText("var bar = foo;", "tests/fixtures/passing.js");

            assert.equal(report.results.length, 1);
            assert.equal(report.errorCount, 0);
            assert.equal(report.warningCount, 1);
            assert.equal(report.results[0].filePath, "tests/fixtures/passing.js");
            assert.equal(report.results[0].messages[0].severity, 1);
            assert.equal(report.results[0].messages[0].message, "File ignored because of your .eslintignore file. Use --no-ignore to override.");
            assert.equal(report.results[0].errorCount, 0);
            assert.equal(report.results[0].warningCount, 1);
        });

        it("should return a message when given a filename by --stdin-filename in excluded files list and ignore is off", function() {

            engine = new CLIEngine({
                ignorePath: "tests/fixtures/.eslintignore",
                ignore: false,
                reset: true,
                rules: {
                    "no-undef": 2
                }
            });

            var report = engine.executeOnText("var bar = foo;", "tests/fixtures/passing.js");
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "tests/fixtures/passing.js");
            assert.equal(report.results[0].messages[0].ruleId, "no-undef");
            assert.equal(report.results[0].messages[0].severity, 2);
        });

    });

    describe("executeOnFiles()", function() {

        var engine;

        it("should report zero messages when given a config file and a valid file", function() {

            engine = new CLIEngine({
                // configFile: path.join(__dirname, "..", "..", ".eslintrc")
            });

            var report = engine.executeOnFiles(["lib/cli.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should report zero messages when given a directory with a .js2 file", function() {

            engine = new CLIEngine({
                extensions: [".js2"],
                reset: true
            });

            var report = engine.executeOnFiles(["tests/fixtures/files/"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should report zero messages when given a directory with a .js and a .js2 file", function() {

            engine = new CLIEngine({
                extensions: [".js", ".js2"],
                reset: true
            });

            var report = engine.executeOnFiles(["tests/fixtures/files/"]);
            assert.equal(report.results.length, 2);
            assert.equal(report.results[0].messages.length, 0);
            assert.equal(report.results[1].messages.length, 0);
        });

        it("should return one error message when given a config with rules with options and severity level set to error", function() {

            engine = new CLIEngine({
                configFile: "tests/fixtures/configurations/quotes-error.json",
                reset: true
            });

            var report = engine.executeOnFiles(["tests/fixtures/single-quoted.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].messages.length, 1);
            assert.equal(report.errorCount, 1);
            assert.equal(report.warningCount, 0);
            assert.equal(report.results[0].messages[0].ruleId, "quotes");
            assert.equal(report.results[0].messages[0].severity, 2);
            assert.equal(report.results[0].errorCount, 1);
            assert.equal(report.results[0].warningCount, 0);
        });

        it("should return two messages when given a config file and a directory of files", function() {

            engine = new CLIEngine({
                configFile: "tests/fixtures/configurations/semi-error.json",
                reset: true
            });

            var report = engine.executeOnFiles(["tests/fixtures/formatters"]);
            assert.equal(report.results.length, 2);
            assert.equal(report.errorCount, 0);
            assert.equal(report.warningCount, 0);
            assert.equal(report.results[0].messages.length, 0);
            assert.equal(report.results[1].messages.length, 0);
            assert.equal(report.results[0].errorCount, 0);
            assert.equal(report.results[0].warningCount, 0);
            assert.equal(report.results[1].errorCount, 0);
            assert.equal(report.results[1].warningCount, 0);
        });

        it("should return zero messages when given a config with environment set to browser", function() {

            engine = new CLIEngine({
                configFile: "tests/fixtures/configurations/env-browser.json",
                reset: true
            });

            var report = engine.executeOnFiles(["tests/fixtures/globals-browser.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should return zero messages when given an option to set environment to browser", function() {

            engine = new CLIEngine({
                envs: ["browser"],
                rules: {
                    "no-undef": 2
                },
                reset: true
            });

            var report = engine.executeOnFiles(["tests/fixtures/globals-browser.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should return zero messages when given a config with environment set to Node.js", function() {

            engine = new CLIEngine({
                configFile: "tests/fixtures/configurations/env-node.json",
                reset: true
            });

            var report = engine.executeOnFiles(["tests/fixtures/globals-node.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should not return results from previous call when calling more than once", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true,
                rules: {
                    semi: 2
                }
            });

            var report = engine.executeOnFiles(["tests/fixtures/missing-semicolon.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "tests/fixtures/missing-semicolon.js");
            assert.equal(report.results[0].messages.length, 1);
            assert.equal(report.results[0].messages[0].ruleId, "semi");
            assert.equal(report.results[0].messages[0].severity, 2);

            report = engine.executeOnFiles(["tests/fixtures/passing.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "tests/fixtures/passing.js");
            assert.equal(report.results[0].messages.length, 0);

        });

        it("should return zero messages when given a directory with eslint excluded files in the directory", function() {

            engine = new CLIEngine({
                ignorePath: "tests/fixtures/.eslintignore"
            });

            var report = engine.executeOnFiles(["tests/fixtures/"]);
            assert.equal(report.results.length, 0);
        });

        it("should return zero messages when all given files are ignored", function() {
            engine = new CLIEngine({
                ignorePath: "tests/fixtures/.eslintignore"
            });

            var report = engine.executeOnFiles(["tests/fixtures/"]);
            assert.equal(report.results.length, 0);
        });

        it("should return a warning when an explicitly given file is ignored", function() {
            engine = new CLIEngine({
                ignorePath: "tests/fixtures/.eslintignore"
            });

            var report = engine.executeOnFiles(["tests/fixtures/passing.js"]);

            assert.equal(report.results.length, 1);
            assert.equal(report.errorCount, 0);
            assert.equal(report.warningCount, 1);
            assert.equal(report.results[0].filePath, "tests/fixtures/passing.js");
            assert.equal(report.results[0].messages[0].severity, 1);
            assert.equal(report.results[0].messages[0].message, "File ignored because of your .eslintignore file. Use --no-ignore to override.");
            assert.equal(report.results[0].errorCount, 0);
            assert.equal(report.results[0].warningCount, 1);
        });

        it("should return two messages when given a file in excluded files list while ignore is off", function() {

            engine = new CLIEngine({
                ignorePath: "tests/fixtures/.eslintignore",
                ignore: false,
                reset: true,
                rules: {
                    "no-undef": 2
                }
            });

            var report = engine.executeOnFiles(["tests/fixtures/undef.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "tests/fixtures/undef.js");
            assert.equal(report.results[0].messages[0].ruleId, "no-undef");
            assert.equal(report.results[0].messages[0].severity, 2);
            assert.equal(report.results[0].messages[1].ruleId, "no-undef");
            assert.equal(report.results[0].messages[1].severity, 2);
        });

        it("should return zero messages when executing a file with a shebang", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true
            });

            var report = engine.executeOnFiles(["tests/fixtures/shebang.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should throw an error when loading a custom rule that doesn't exist", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true,
                rulesPaths: ["./tests/fixtures/rules/wrong"],
                configFile: "./tests/fixtures/rules/eslint.json"
            });

            assert.throws(function() {
                engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);
            }, /Definition for rule 'custom-rule' was not found/);

        });

        it("should throw an error when loading a custom rule that doesn't exist", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true,
                rulePaths: ["./tests/fixtures/rules/wrong"],
                configFile: "./tests/fixtures/rules/eslint.json"
            });

            assert.throws(function() {
                engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);
            }, /Error while loading rule 'custom-rule'/);
        });

        it("should return one message when a custom rule matches a file", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true,
                useEslintrc: false,
                rulePaths: ["./tests/fixtures/rules/"],
                configFile: "./tests/fixtures/rules/eslint.json"
            });

            var report = engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "tests/fixtures/rules/test/test-custom-rule.js");
            assert.equal(report.results[0].messages.length, 2);
            assert.equal(report.results[0].messages[0].ruleId, "custom-rule");
            assert.equal(report.results[0].messages[0].severity, 1);
        });

        it("should return messages when multiple custom rules match a file", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true,
                rulePaths: [
                    "./tests/fixtures/rules/dir1",
                    "./tests/fixtures/rules/dir2"
                ],
                configFile: "./tests/fixtures/rules/multi-rulesdirs.json"
            });

            var report = engine.executeOnFiles(["tests/fixtures/rules/test-multi-rulesdirs.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "tests/fixtures/rules/test-multi-rulesdirs.js");
            assert.equal(report.results[0].messages.length, 2);
            assert.equal(report.results[0].messages[0].ruleId, "no-literals");
            assert.equal(report.results[0].messages[0].severity, 2);
            assert.equal(report.results[0].messages[1].ruleId, "no-strings");
            assert.equal(report.results[0].messages[1].severity, 2);
        });

        it("should return zero messages when executing with reset flag", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true,
                useEslintrc: false
            });

            var report = engine.executeOnFiles(["./tests/fixtures/missing-semicolon.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "./tests/fixtures/missing-semicolon.js");
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should return zero messages when executing with reset flag in Node.js environment", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true,
                useEslintrc: false,
                envs: ["node"]
            });

            var report = engine.executeOnFiles(["./tests/fixtures/process-exit.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "./tests/fixtures/process-exit.js");
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should return zero messages when executing with base-config flag set to false", function() {

            engine = new CLIEngine({
                ignore: false,
                baseConfig: false,
                useEslintrc: false
            });

            var report = engine.executeOnFiles(["./tests/fixtures/missing-semicolon.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "./tests/fixtures/missing-semicolon.js");
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should return zero messages and ignore .eslintrc files when executing with no-eslintrc flag", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true,
                useEslintrc: false,
                envs: ["node"]
            });

            var report = engine.executeOnFiles(["./tests/fixtures/eslintrc/quotes.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "./tests/fixtures/eslintrc/quotes.js");
            assert.equal(report.results[0].messages.length, 0);
        });

        it("should return zero messages and ignore package.json files when executing with no-eslintrc flag", function() {

            engine = new CLIEngine({
                ignore: false,
                reset: true,
                useEslintrc: false,
                envs: ["node"]
            });

            var report = engine.executeOnFiles(["./tests/fixtures/packagejson/quotes.js"]);
            assert.equal(report.results.length, 1);
            assert.equal(report.results[0].filePath, "./tests/fixtures/packagejson/quotes.js");
            assert.equal(report.results[0].messages.length, 0);
        });

        // These tests have to do with https://github.com/eslint/eslint/issues/963

        describe("configuration hierarchy", function() {

            var fixtureDir;

            // copy into clean area so as not to get "infected" by this project's .eslintrc files
            before(function() {
                fixtureDir = tempdir() + "/eslint/fixtures";
                mkdir("-p", fixtureDir);
                cp("-r", "./tests/fixtures/config-hierarchy", fixtureDir);
            });

            after(function() {
                rm("-r", fixtureDir);
            });

            // Default configuration - blank
            it("should return zero messages when executing with reset and no .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true,
                    useEslintrc: false
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 0);
            });

            // Default configuration - conf/eslint.json
            it("should return three messages when executing with no .eslintrc", function() {

                engine = new CLIEngine({
                    useEslintrc: false
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 3);
                assert.equal(report.results[0].messages[0].ruleId, "no-console");
                assert.equal(report.results[0].messages[0].severity, 2);
                assert.equal(report.results[0].messages[1].ruleId, "no-undef");
                assert.equal(report.results[0].messages[1].severity, 2);
                assert.equal(report.results[0].messages[2].ruleId, "quotes");
                assert.equal(report.results[0].messages[2].severity, 2);
            });

            // Default configuration - conf/environments.js (/*eslint-env node*/)
            it("should return one message when executing with no .eslintrc in the Node.js environment", function() {

                engine = new CLIEngine({
                    useEslintrc: false
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes-node.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "quotes");
                assert.equal(report.results[0].messages[0].severity, 2);
            });

            // Project configuration - first level .eslintrc
            it("should return one message when executing with .eslintrc in the Node.js environment", function() {

                engine = new CLIEngine();

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/process-exit.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "no-process-exit");
                assert.equal(report.results[0].messages[0].severity, 2);
            });

            // Project configuration - first level .eslintrc
            it("should return zero messages when executing with .eslintrc in the Node.js environment and reset", function() {

                engine = new CLIEngine({
                    reset: true
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/process-exit.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 0);
            });

            // Project configuration - first level .eslintrc
            it("should return one message when executing with .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "quotes");
                assert.equal(report.results[0].messages[0].severity, 2);
            });

            // Project configuration - second level .eslintrc
            it("should return one message when executing with local .eslintrc that overrides parent .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "no-console");
                assert.equal(report.results[0].messages[0].severity, 1);
            });

            // Project configuration - third level .eslintrc
            it("should return one message when executing with local .eslintrc that overrides parent and grandparent .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/subsubbroken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "quotes");
                assert.equal(report.results[0].messages[0].severity, 1);
            });

            // Project configuration - first level package.json
            it("should return one message when executing with package.json", function() {

                engine = new CLIEngine({
                    reset: true
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/packagejson/subdir/wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "quotes");
                assert.equal(report.results[0].messages[0].severity, 1);
            });

             // Project configuration - second level package.json
            it("should return zero messages when executing with local package.json that overrides parent package.json", function() {

                engine = new CLIEngine({
                    reset: true
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/packagejson/subdir/subsubdir/wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 0);
            });

            // Project configuration - third level package.json
            it("should return one message when executing with local package.json that overrides parent and grandparent package.json", function() {

                engine = new CLIEngine({
                    reset: true
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/packagejson/subdir/subsubdir/subsubsubdir/wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "quotes");
                assert.equal(report.results[0].messages[0].severity, 2);
            });

            // Project configuration - .eslintrc overrides package.json in same directory
            it("should return one message when executing with .eslintrc that overrides a package.json in the same directory", function() {

                engine = new CLIEngine({
                    reset: true
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/packagejson/wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "quotes");
                assert.equal(report.results[0].messages[0].severity, 2);
            });

            // Command line configuration - --config with first level .eslintrc
            it("should return two messages when executing with config file that adds to local .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true,
                    configFile: fixtureDir + "/config-hierarchy/broken/add-conf.yaml"
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
                assert.equal(report.results[0].messages[0].ruleId, "quotes");
                assert.equal(report.results[0].messages[0].severity, 2);
                assert.equal(report.results[0].messages[1].ruleId, "semi");
                assert.equal(report.results[0].messages[1].severity, 1);
            });

            // Command line configuration - --config with first level .eslintrc
            it("should return no messages when executing with config file that overrides local .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true,
                    configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml"
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 0);
            });

            // Command line configuration - --config with second level .eslintrc
            it("should return two messages when executing with config file that adds to local and parent .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true,
                    configFile: fixtureDir + "/config-hierarchy/broken/add-conf.yaml"
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
                assert.equal(report.results[0].messages[0].ruleId, "no-console");
                assert.equal(report.results[0].messages[0].severity, 1);
                assert.equal(report.results[0].messages[1].ruleId, "semi");
                assert.equal(report.results[0].messages[1].severity, 1);
            });

            // Command line configuration - --config with second level .eslintrc
            it("should return one message when executing with config file that overrides local and parent .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true,
                    configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml"
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/subbroken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "no-console");
                assert.equal(report.results[0].messages[0].severity, 1);
            });

            // Command line configuration - --config with first level .eslintrc
            it("should return no messages when executing with config file that overrides local .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true,
                    configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml"
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 0);
            });

            // Command line configuration - --rule with --config and first level .eslintrc
            it("should return one message when executing with command line rule and config file that overrides local .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true,
                    configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml",
                    rules: {
                        quotes: [1, "double"]
                    }
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "quotes");
                assert.equal(report.results[0].messages[0].severity, 1);
            });

            // Command line configuration - --rule with --config and first level .eslintrc
            it("should return one message when executing with command line rule and config file that overrides local .eslintrc", function() {

                engine = new CLIEngine({
                    reset: true,
                    configFile: fixtureDir + "/config-hierarchy/broken/override-conf.yaml",
                    rules: {
                        quotes: [1, "double"]
                    }
                });

                var report = engine.executeOnFiles([fixtureDir + "/config-hierarchy/broken/console-wrong-quotes.js"]);
                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 1);
                assert.equal(report.results[0].messages[0].ruleId, "quotes");
                assert.equal(report.results[0].messages[0].severity, 1);
            });

        });

        describe("plugins", function() {
            it("should return two messages when executing with config file that specifies a plugin", function() {
                engine = new CLIEngine({
                    configFile: "./tests/fixtures/configurations/plugins-with-prefix.json",
                    reset: true,
                    useEslintrc: false
                });

                var report = engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);

                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
                assert.equal(report.results[0].messages[0].ruleId, "example/example-rule");
            });

            it("should return two messages when executing with config file that specifies a plugin with namespace", function() {
                engine = new CLIEngine({
                    configFile: "./tests/fixtures/configurations/plugins-with-prefix-and-namespace.json",
                    reset: true,
                    useEslintrc: false
                });

                var report = engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);

                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
                assert.equal(report.results[0].messages[0].ruleId, "example/example-rule");
            });

            it("should return two messages when executing with config file that specifies a plugin without prefix", function() {
                engine = new CLIEngine({
                    configFile: "./tests/fixtures/configurations/plugins-without-prefix.json",
                    reset: true,
                    useEslintrc: false
                });

                var report = engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);

                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
                assert.equal(report.results[0].messages[0].ruleId, "example/example-rule");
            });

            it("should return two messages when executing with config file that specifies a plugin without prefix and with namespace", function() {
                engine = new CLIEngine({
                    configFile: "./tests/fixtures/configurations/plugins-without-prefix-with-namespace.json",
                    reset: true,
                    useEslintrc: false
                });

                var report = engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);

                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
                assert.equal(report.results[0].messages[0].ruleId, "example/example-rule");
            });

            it("should import the same plugin only once if it is configured multiple times", sinon.test(function() {
                var importPlugin = this.spy(rules, "import");

                engine = new CLIEngine({
                    configFile: "./tests/fixtures/configurations/plugins-with-prefix.json",
                    reset: true,
                    useEslintrc: false
                });

                engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);
                engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);

                assert.equal(importPlugin.calledOnce, true, "same plugin was imported more than once");
                assert.equal(importPlugin.calledWithExactly(examplePlugin.rules, "example"), true);
            }));

            it("should return two messages when executing with cli option that specifies a plugin", function() {
                engine = new CLIEngine({
                    reset: true,
                    useEslintrc: false,
                    plugins: ["example"],
                    rules: { "example/example-rule": 1 }
                });

                var report = engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);

                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
                assert.equal(report.results[0].messages[0].ruleId, "example/example-rule");
            });

            it("should return two messages when executing with cli option that specifies preloaded plugin", function() {
                engine = new CLIEngine({
                    reset: true,
                    useEslintrc: false,
                    plugins: ["test"],
                    rules: { "test/example-rule": 1 }
                });

                engine.addPlugin("eslint-plugin-test", { rules: { "example-rule": require("../fixtures/rules/custom-rule") } });

                var report = engine.executeOnFiles(["tests/fixtures/rules/test/test-custom-rule.js"]);

                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
                assert.equal(report.results[0].messages[0].ruleId, "test/example-rule");
            });
        });

        describe("processors", function() {
            it("should return two messages when executing with config file that specifies a processor", function() {
                engine = new CLIEngine({
                    configFile: "./tests/fixtures/configurations/processors.json",
                    reset: true,
                    useEslintrc: false,
                    extensions: ["js", "txt"]
                });

                var report = engine.executeOnFiles(["tests/fixtures/processors/test/test-processor.txt"]);

                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
            });
            it("should return two messages when executing with config file that specifies preloaded processor", function() {
                engine = new CLIEngine({
                    reset: true,
                    useEslintrc: false,
                    plugins: ["test-processor"],
                    rules: {
                        "no-console": 2,
                        "no-unused-vars": 2
                    },
                    extensions: ["js", "txt"]
                });

                engine.addPlugin("test-processor", {
                    processors: {
                        ".txt": {
                            preprocess: function(text) {
                                return [text];
                            },
                            postprocess: function(messages) {
                                return messages[0];
                            }
                        }
                    }
                });

                var report = engine.executeOnFiles(["tests/fixtures/processors/test/test-processor.txt"]);

                assert.equal(report.results.length, 1);
                assert.equal(report.results[0].messages.length, 2);
            });
            it("should run processors when calling executeOnFiles with config file that specifies a processor", function() {
                engine = new CLIEngine({
                    configFile: "./tests/fixtures/configurations/processors.json",
                    reset: true,
                    useEslintrc: false,
                    extensions: ["js", "txt"]
                });

                var report = engine.executeOnFiles(["tests/fixtures/processors/test/test-processor.txt"]);

                assert.equal(report.results[0].messages[0].message, "b is defined but never used");
                assert.equal(report.results[0].messages[0].ruleId, "post-processed");
            });
            it("should run processors when calling executeOnFiles with config file that specifies preloaded processor", function() {
                engine = new CLIEngine({
                    reset: true,
                    useEslintrc: false,
                    plugins: ["test-processor"],
                    rules: {
                        "no-console": 2,
                        "no-unused-vars": 2
                    },
                    extensions: ["js", "txt"]
                });

                engine.addPlugin("test-processor", {
                    processors: {
                        ".txt": {
                            preprocess: function(text) {
                                return [text.replace("a()", "b()")];
                            },
                            postprocess: function(messages) {
                                messages[0][0].ruleId = "post-processed";
                                return messages[0];
                            }
                        }
                    }
                });

                var report = engine.executeOnFiles(["tests/fixtures/processors/test/test-processor.txt"]);

                assert.equal(report.results[0].messages[0].message, "b is defined but never used");
                assert.equal(report.results[0].messages[0].ruleId, "post-processed");
            });
            it("should run processors when calling executeOnText with config file that specifies a processor", function() {
                engine = new CLIEngine({
                    configFile: "./tests/fixtures/configurations/processors.json",
                    reset: true,
                    useEslintrc: false,
                    extensions: ["js", "txt"]
                });

                var report = engine.executeOnText("function a() {console.log(\"Test\");}", "tests/fixtures/processors/test/test-processor.txt");

                assert.equal(report.results[0].messages[0].message, "b is defined but never used");
                assert.equal(report.results[0].messages[0].ruleId, "post-processed");
            });
            it("should run processors when calling executeOnText with config file that specifies preloaded processor", function() {
                engine = new CLIEngine({
                    reset: true,
                    useEslintrc: false,
                    plugins: ["test-processor"],
                    rules: {
                        "no-console": 2,
                        "no-unused-vars": 2
                    },
                    extensions: ["js", "txt"]
                });

                engine.addPlugin("test-processor", {
                    processors: {
                        ".txt": {
                            preprocess: function(text) {
                                return [text.replace("a()", "b()")];
                            },
                            postprocess: function(messages) {
                                messages[0][0].ruleId = "post-processed";
                                return messages[0];
                            }
                        }
                    }
                });

                var report = engine.executeOnText("function a() {console.log(\"Test\");}", "tests/fixtures/processors/test/test-processor.txt");

                assert.equal(report.results[0].messages[0].message, "b is defined but never used");
                assert.equal(report.results[0].messages[0].ruleId, "post-processed");
            });
        });
    });

    describe("getConfigForFile", function() {

        it("should return the info from Config#getConfig when called", function() {

            var engine = new CLIEngine({
                configFile: "tests/fixtures/configurations/quotes-error.json",
                reset: true
            });

            var configHelper = new Config(engine.options);

            assert.deepEqual(
                engine.getConfigForFile("tests/fixtures/single-quoted.js"),
                configHelper.getConfig("tests/fixtures/single-quoted.js")
            );

        });

    });

    describe("isPathIgnored", function() {

        it("should check if the given path is ignored", function() {
            var engine = new CLIEngine({
                ignorePath: "tests/fixtures/.eslintignore2"
            });

            assert.isTrue(engine.isPathIgnored("undef.js"));
            assert.isFalse(engine.isPathIgnored("passing.js"));
        });

        it("should always return false if ignoring is disabled", function() {
            var engine = new CLIEngine({
                ignorePath: "tests/fixtures/.eslintignore2",
                ignore: false
            });

            assert.isFalse(engine.isPathIgnored("undef.js"));
            assert.isFalse(engine.isPathIgnored("passing.js"));
        });

    });

    describe("getFormatter()", function() {

        it("should return a function when a bundled formatter is requested", function() {
            var engine = new CLIEngine(),
                formatter = engine.getFormatter("compact");

            assert.isFunction(formatter);
        });

        it("should return a function when no argument is passed", function() {
            var engine = new CLIEngine(),
                formatter = engine.getFormatter();

            assert.isFunction(formatter);
        });

        it("should return a function when a custom formatter is requested", function() {
            var engine = new CLIEngine(),
                formatter = engine.getFormatter("./tests/fixtures/formatters/simple.js");

            assert.isFunction(formatter);
        });

        it("should return a function when a custom formatter is requested, also if the path has backslashes", function() {
            var engine = new CLIEngine(),
                formatter = engine.getFormatter(".\\tests\\fixtures\\formatters\\simple.js");

            assert.isFunction(formatter);
        });

        it("should return null when a customer formatter doesn't exist", function() {
            var engine = new CLIEngine(),
                formatter = engine.getFormatter("./tests/fixtures/formatters/doesntexist.js");

            assert.isNull(formatter);
        });

        it("should return null when a built-in formatter doesn't exist", function() {
            var engine = new CLIEngine(),
                formatter = engine.getFormatter("special");

            assert.isNull(formatter);
        });

        it("should return null when a non-string formatter name is passed", function() {
            var engine = new CLIEngine(),
                formatter = engine.getFormatter(5);

            assert.isNull(formatter);
        });

    });

});


text:
import React from 'react';

export default class Calendar extends React.Component {

    constructor(props){
        super(props);
          this.state = {
              time: (new Date()).toLocaleTimeString(),
              date: null
          };
    }

    getTime(){
        var options = {
            weekday: "long", year: "numeric", month: "short",
            day: "numeric"
        };

       var currentTime = new Date();

          this.setState({
              date: currentTime.toLocaleDateString("ko-kr", options),
              time: currentTime.toLocaleTimeString("en-US")
          });
    }

    componentDidMount(){
       this.timer =  setInterval(this.getTime.bind(this), 1000);
    }

    componentWillUnmount(){
        clearInterval(this.timer);
    }

    render() {
        return

{this.state.date}

{this.state.time}

;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package com.zhy.zhylib.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Rect;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.io.File;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class DeviceUtils {
    private static final String TAG = DeviceUtils.class.getSimpleName();

    /**
     * 获取屏幕宽度
     */
    public static int getScreenWidth(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    /**
     * 获取屏幕高度
     */
    public static int getScreenHeight(Activity activity) {
        DisplayMetrics dm = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /**
     * 网络是否可用
     */
    public static boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        }
        NetworkInfo mNetworkInfo = cm.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }

    /**
     * GPS是否关闭
     */
    public static boolean hasOpenedGPS(Context context) {
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        return (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER));
    }

    /**
     * 获取可用存储路径
     */
    public static File getAvailableStorageDirectory(Context context) {
        File directory = null;
        if (isSDcardAvailable()) {
            directory = Environment.getExternalStorageDirectory();
        } else {
            directory = context.getFilesDir();
        }
        return directory;
    }

    /**
     * SD卡是否可用
     */
    public static boolean isSDcardAvailable() {
        try {
            return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 获取MAC地址
     */
    public static String getLocalMacAddress(Context context) {
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /**
     * 获取本机IP
     *
     * @return
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e(TAG, ex.toString());
        }
        return null;
    }

    /**
     * 获取设备deviceId
     */
    public static String getDeviceId(Context mContext) {
        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getDeviceId();
    }

    /**
     * 获得本机手机号码
     * 只能获取那些很古老的sim卡的电话号码
     */
    public static String getMobile(Context mContext) {
        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        return tm.getLine1Number();//获取本机号码
    }

    /**
     * 获取设备信息
     */
    public static String getDeviceInfo(Context mContext) {
        TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        StringBuilder sb = new StringBuilder();
        sb.append("{\"DeviceId(IMEI)\":\"" + tm.getDeviceId());
        sb.append("\",\"DeviceSoftwareVersion\":\"" + tm.getDeviceSoftwareVersion());
        sb.append("\",\"Line1Number\":\"" + tm.getLine1Number());
        sb.append("\",\"NetworkCountryIso\":\"" + tm.getNetworkCountryIso());
        sb.append("\",\"NetworkOperator\":\"" + tm.getNetworkOperator());
        sb.append("\",\"NetworkOperatorName\":\"" + tm.getNetworkOperatorName());
        sb.append("\",\"NetworkType\":\"" + tm.getNetworkType());
        sb.append("\",\"PhoneType\":\"" + tm.getPhoneType());
        sb.append("\",\"SimCountryIso\":\"" + tm.getSimCountryIso());
        sb.append("\",\"SimOperator\":\"" + tm.getSimOperator());
        sb.append("\",\"SimOperatorName\":\"" + tm.getSimOperatorName());
        sb.append("\",\"SimSerialNumber\":\"" + tm.getSimSerialNumber());
        sb.append("\",\"SimState\":\"" + tm.getSimState());
        sb.append("\",\"SubscriberId(IMSI)\":\"" + tm.getSubscriberId());
        sb.append("\",\"VoiceMailNumber\":\"" + tm.getVoiceMailNumber() + "\"}");
        return sb.toString();
    }

    /**
     * 显示键盘
     */
    public static void showSoftInput(View v) {
        v.setFocusable(true);
        v.setFocusableInTouchMode(true);
        v.requestFocus();
        InputMethodManager inputManager = (InputMethodManager) v.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(v, 0);
    }

    /**
     * 隐藏键盘
     */
    public static void hideSoftInput(View v) {
        InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(v, InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    public static void setScreenRotation(ContentResolver cr, boolean rotation) {
        Settings.System.putInt(cr, Settings.System.ACCELEROMETER_ROTATION, rotation ? 1 : 0);
    }

    public static boolean isScreenRotation(ContentResolver cr) throws SettingNotFoundException {
        return Settings.System.getInt(cr, Settings.System.ACCELEROMETER_ROTATION) == 1;
    }

    /**
     * 获取状态栏高度
     */
    public static int getStatusBarHeight(Activity activity) {
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        return frame.top;
    }

    /**
     * 实现文本复制功能
     */
    public static void copy(String content, Context context) {
        // 得到剪贴板管理器
        ClipboardManager cmb = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        cmb.setText(content.trim());
    }
}


text:
"""Compatibility code for using magicbus with various versions of Python.

Magic Bus 3.3 is compatible with Python versions 2.7+. This module provides a
useful abstraction over the differences between Python versions, sometimes by
preferring a newer idiom, sometimes an older one, and sometimes a custom one.

In particular, Python 2 uses str and '' for byte strings, while Python 3
uses str and '' for unicode strings. We will call each of these the 'native
string' type for each version. Because of this major difference, this module
provides new 'bytestr', 'unicodestr', and 'nativestr' attributes, as well as
the function: 'ntob', which translates native strings (of type 'str') into
byte strings regardless of Python version.
"""
import sys

if sys.version_info >= (3, 0):
    py3k = True
    basestring = (bytes, str)
    unicodestr = str

    def ntob(n, encoding='ISO-8859-1'):
        """Return the given native string as a byte string in the given
        encoding."""
        # In Python 3, the native string type is unicode
        return n.encode(encoding)
else:
    # Python 2
    py3k = False
    basestring = basestring
    unicodestr = unicode

    def ntob(n, encoding='ISO-8859-1'):
        """Return the given native string as a byte string in the given
        encoding."""
        # In Python 2, the native string type is bytes. Assume it's already
        # in the given encoding, which for ISO-8859-1 is almost always what
        # was intended.
        return n

try:
    from http.server import HTTPServer, BaseHTTPRequestHandler as HTTPHandler
except ImportError:
    from BaseHTTPServer import HTTPServer
    from BaseHTTPServer import BaseHTTPRequestHandler as HTTPHandler

try:
    from http.client import HTTPConnection
except ImportError:
    from httplib import HTTPConnection

import threading

try:
    from _thread import get_ident as get_thread_ident
except ImportError:
    from thread import get_ident as get_thread_ident

if sys.version_info >= (3, 3):
    TimerClass = threading.Timer
else:
    TimerClass = threading._Timer


text:
import json
from django.db import models
from django.forms import model_to_dict
import six

class DefaultContextSerializer(object):
    """
    Default class for serializing context data
    """

    def __init__(self, context):
        super(DefaultContextSerializer, self).__init__()
        self.context = context

    @property
    def data(self):
        """
        Data property that will return the serialized data
        :return:
        """

        # Create a serialized context dict
        serialized_context = self.serialize_value(self.context)

        # Return the serialized context
        return serialized_context

    def serialize_value(self, value):
        """
        Given a value, ensure that it is serialized properly
        :param value:
        :return:
        """
        # Create a list of serialize methods to run the value through
        serialize_methods = [
            self.serialize_model,
            self.serialize_json_string,
            self.serialize_list,
            self.serialize_dict
        ]

        # Run all of our serialize methods over our value
        for serialize_method in serialize_methods:
            value = serialize_method(value)

        # Return the serialized context value
        return value

    def serialize_model(self, value):
        """
        Serializes a model and all of its prefetched foreign keys
        :param value:
        :return:
        """

        # Check if the context value is a model
        if not isinstance(value, models.Model):
            return value

        # Serialize the model
        serialized_model = model_to_dict(value)

        # Check the model for cached foreign keys
        for model_field, model_value in serialized_model.items():
            model_state = value._state

            # Django >= 2
            if hasattr(model_state, 'fields_cache'):  # pragma: no cover
                if model_state.fields_cache.get(model_field):
                    serialized_model[model_field] = model_state.fields_cache.get(model_field)
            else:  # pragma: no cover
                # Django < 2
                cache_field = '_{0}_cache'.format(model_field)
                if hasattr(value, cache_field):
                    serialized_model[model_field] = getattr(value, cache_field)

        # Return the serialized model
        return self.serialize_value(serialized_model)

    def serialize_json_string(self, value):
        """
        Tries to load an encoded json string back into an object
        :param json_string:
        :return:
        """

        # Check if the value might be a json string
        if not isinstance(value, six.string_types):
            return value

        # Make sure it starts with a brace
        if not value.startswith('{') or value.startswith('['):
            return value

        # Try to load the string
        try:
            return json.loads(value)
        except:
            return value

    def serialize_list(self, value):
        """
        Ensure that all values of a list or tuple are serialized
        :return:
        """

        # Check if this is a list or a tuple
        if not isinstance(value, (list, tuple)):
            return value

        # Loop over all the values and serialize the values
        return [
            self.serialize_value(list_value)
            for list_value in value
        ]

    def serialize_dict(self, value):
        """
        Ensure that all values of a dictionary are properly serialized
        :param value:
        :return:
        """

        # Check if this is a dict
        if not isinstance(value, dict):
            return value

        # Loop over all the values and serialize them
        return {
            dict_key: self.serialize_value(dict_value)
            for dict_key, dict_value in value.items()
        }


text: module.exports = require('./lib/nodes');


text: This template provides a easy way to deploy web app on Azure Web Apps on Windows with Azure database for MySQL(Preview).


text:
<?php

namespace Magento\Usps\Model\Source;

/**
 * Machinable source
 */
class Machinable extends Generic
{
    /**
     * Carrier code
     *
     * @var string
     */
    protected $code = 'machinable';
}


text:
package com.evolveum.midpoint.eclipse.logviewer.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IRegion;

import com.evolveum.midpoint.eclipse.logviewer.config.EditorConfiguration;
import com.evolveum.midpoint.eclipse.logviewer.editor.DocumentUtils;
import com.evolveum.midpoint.eclipse.logviewer.parsing.ParsingUtils;

public class ContextNodeDefinition extends OutlineNodeDefinition<ContextNodeContent> {

	private static final ContentSelectionStrategy CONTENT_SELECTION_STRATEGY = new ContextDumpContentSelectionStrategy();

	private ContextNodeDefinition(EditorConfiguration editorConfiguration) {
		super(editorConfiguration);
	}

	private static class ContextDumpContentSelectionStrategy implements ContentSelectionStrategy {

		@Override
		public Result computeContent(OutlineNode<?> outlineNode, TreeMap<Integer, OutlineNode<?>> availableNodes) {

			NavigableMap<Integer, OutlineNode<?>> content = ContentSelectionStrategy.HEADER_LAST.computeContent(outlineNode, availableNodes).getContent();
			int startLine = !content.isEmpty() ? content.firstKey() : outlineNode.getStartLine();

			// find next log line

			IDocument document = outlineNode.getDocument();
			Integer nextLogLine = ParsingUtils.findNextLogLine(document, outlineNode.getStartLine()+1);
			if (nextLogLine == null) {
				nextLogLine = document.getNumberOfLines();
			}

			TreeMap<Integer, OutlineNode<?>> subNodes = new TreeMap<>(availableNodes.subMap(startLine, true, nextLogLine, false));
			subNodes.remove(outlineNode.getStartLine());		// context dump node should not be in the result!

//			System.out.print("# ContextDumpCSS for line " + outlineNode.getStartLine() + " returned: ");
//			if (subNodes.isEmpty()) {
//				System.out.print("(empty map)");
//			} else {
//				System.out.print(subNodes.firstKey() + ".." + subNodes.lastKey());
//			}
//			System.out.println(", continuing after " + nextLogLine);

			return new Result(subNodes, nextLogLine);
		}

	}

	public static String recognizeLine(String line) {
		if (line.contains("---[ SYNCHRONIZATION")) {
			return line.substring(line.indexOf("---["));
		} else if (line.startsWith("---[ PROJECTOR") ||
				line.startsWith("---[ CLOCKWORK") ||
				line.startsWith("---[ WORKFLOW") ||
				line.startsWith("---[ preview")) {
			return line;
		} else {
			return null;
		}
	}

	@Override
	public ContextNodeContent recognize(int lineNumber, String line, String entry, String header, IRegion region, IDocument document) throws BadLocationException {

		String lineContent = recognizeLine(line);
		if (lineContent == null) {
			return null;
		}

		ContextNodeContent content = new ContextNodeContent();
		String line2 = DocumentUtils.getLine(document, lineNumber+1);
		content.parseWaveInfo(line2);
		content.parseLabelCore(lineContent);
		content.setLabelSuffix("");

		findComponents(content, lineNumber+2, document);
		return content;
	}

	private static final Pattern RULES_PATTERN = Pattern.compile("^      (\\w)+ policy rules \\(total (\\d)+, triggered (\\d)+\\):.*");

	private void findComponents(ContextNodeContent content, int lineNumber, IDocument document) {

		List<String> zero = new ArrayList<>();
		List<String> plus = new ArrayList<>();
		List<String> minus = new ArrayList<>();
		List<String> current = null;
		while (lineNumber < document.getNumberOfLines()) {
			String line = DocumentUtils.getLine(document, lineNumber);
			if (line == null || line.startsWith("  PROJECTIONS:")) {
				break;
			}
			Matcher matcher = RULES_PATTERN.matcher(line);
			if (matcher.matches()) {
				try {
					content.setObjectRulesTotal(Integer.parseInt(matcher.group(2)));
					content.setObjectRulesTriggered(Integer.parseInt(matcher.group(3)));
				} catch (NumberFormatException e) {
					e.printStackTrace();
				}
			} else if (line.startsWith("        Zero:")) {
				current = zero;
			} else if (line.startsWith("        Plus:")) {
				current = plus;
			} else if (line.startsWith("        Minus:")) {
				current = minus;
			} else if (line.startsWith("          -> ") && current != null) {
				current.add(line);
			}
			lineNumber++;
		}
		content.setZeroAssignments(zero.size());
		content.setPlusAssignments(plus.size());
		content.setMinusAssignments(minus.size());
	}

	@Override
	public ContentSelectionStrategy getContentSelectionStrategy() {
		return CONTENT_SELECTION_STRATEGY;
	}

	public static OutlineNodeDefinition<?> parseFromLine(EditorConfiguration editorConfiguration, String line) {
		return new ContextNodeDefinition(editorConfiguration).parseFromLine(line);
	}

}