<commit_before>/** Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const { uniqBy } = require('lodash');
const JDLReader = require('./readers/jdl-reader');
const { readJSONFile } = require('./readers/json-file-reader');
const { doesFileExist } = require('./utils/file-utils');
const DocumentParser = require('./converters/parsed-jdl-to-jdl-object/parsed-jdl-to-jdl-object-converter');
const JDLWithoutApplicationToJSONConverter = require('./converters/jdl-to-json/jdl-without-application-to-json-converter');
const JDLWithApplicationsToJSONConverter = require('./converters/jdl-to-json/jdl-with-applications-to-json-converter');
const JHipsterApplicationExporter = require('./exporters/applications/jhipster-application-exporter');
const JHipsterApplicationFormatter = require('./exporters/applications/jhipster-application-formatter');
const JHipsterDeploymentExporter = require('./exporters/jhipster-deployment-exporter');
const JHipsterEntityExporter = require('./exporters/jhipster-entity-exporter');
const BusinessErrorChecker = require('./validators/business-error-checker');

module.exports = {
    createImporterFromContent,
    createImporterFromFiles,
};

/**
 * Creates a new JDL importer from files.
 * There are two ways to create an importer:
 *   - By providing an existing application content, if there's one
 *   - Deprecated: providing some application options
 *
 * @param {Array} files - the JDL files to parse.
 * @param {Object} configuration - a configuration object.
 * @param {Object} configuration.application - an existing application file content
 * @param {String} configuration.applicationName - deprecated, the application's name, optional if parsing applications
 * @param {String} configuration.applicationType - deprecated, the application type, optional if parsing applications
 * @param {String} configuration.databaseType - deprecated, the database type, optional if parsing applications
 * @param {String} configuration.generatorVersion - deprecated, the generator's version, optional if parsing applications
 * @param {String} configuration.forceNoFiltering - whether to force filtering
 * @param {Boolean} configuration.skipFileGeneration - whether not to generate the .yo-rc.json file
 * @returns {Object} a JDL importer.
 * @throws {Error} if files aren't passed.
 */
function createImporterFromFiles(files, configuration) {
    if (!files) {
        throw new Error('Files must be passed to create a new JDL importer.');
    }
    const content = parseFiles(files);
    return makeJDLImporter(content, configuration || {});
}

/**
 * Creates a new JDL importer from a JDL string content.
 * There are two ways to create an importer:
 *   - By providing an existing application content, if there's one
 *   - Deprecated: providing some application options
 *
 * @param {String} jdlString - the JDL String content to parse.
 * @param {Object} configuration - a configuration object.
 * @param {Object} configuration.application - an existing application file content
 * @param {String} configuration.applicationName - deprecated, the application's name, optional if parsing applications
 * @param {String} configuration.applicationType - deprecated, the application type, optional if parsing applications
 * @param {String} configuration.databaseType - deprecated, the database type, optional if parsing applications
 * @param {String} configuration.generatorVersion - deprecated, the generator's version, optional if parsing applications
 * @param {String} configuration.forceNoFiltering - whether to force filtering
 * @param {Boolean} configuration.skipFileGeneration - whether not to generate the .yo-rc.json file
 * @returns {Object} a JDL importer.
 * @throws {Error} if the content isn't passed.
 */
function createImporterFromContent(jdlString, configuration) {
    if (!jdlString) {
        throw new Error('A JDL content must be passed to create a new JDL importer.');
    }
    const content = JDLReader.parseFromContent(jdlString);
    return makeJDLImporter(content, configuration || {});
}

function makeJDLImporter(content, configuration) {
    let importState = {
        exportedApplications: [],
        exportedApplicationsWithEntities: {},
        exportedEntities: [],
        exportedDeployments: [],
    };

    return {
        /**
         * Processes JDL files and converts them to JSON.
         * @returns {object} the state of the process:
         *          - exportedDeployments: the exported deployments, or an empty list
         *          - exportedApplications: the exported applications, or an empty list
         *          - exportedEntities: the exported entities, or an empty list
         */
        import: () => {
            const jdlObject = getJDLObject(content, configuration);
            checkForErrors(jdlObject, configuration);
            if (jdlObject.getApplicationQuantity() === 0 && jdlObject.getEntityQuantity() > 0) {
                importState.exportedEntities = importOnlyEntities(jdlObject, configuration);
            } else if (jdlObject.getApplicationQuantity() === 1) {
                importState = importOneApplicationAndEntities(jdlObject, configuration);
            } else {
                importState = importApplicationsAndEntities(jdlObject, configuration);
            }
            if (jdlObject.getDeploymentQuantity()) {
                importState.exportedDeployments = importDeployments(jdlObject.deployments);
            }
            return importState;
        },
    };
}

function parseFiles(files) {
    return JDLReader.parseFromFiles(files);
}

function getJDLObject(parsedJDLContent, configuration) {
    let baseName = configuration.applicationName;
    let applicationType = configuration.applicationType;
    let generatorVersion = configuration.generatorVersion;
    let databaseType = configuration.databaseType;
    let skippedUserManagement = false;

    if (configuration.application) {
        baseName = configuration.application['generator-jhipster'].baseName;
        applicationType = configuration.application['generator-jhipster'].applicationType;
        generatorVersion = configuration.application['generator-jhipster'].jhipsterVersion;
        skippedUserManagement = configuration.application['generator-jhipster'].skipUserManagement;
        databaseType = configuration.application['generator-jhipster'].databaseType;
    }

    return DocumentParser.parseFromConfigurationObject({
        parsedContent: parsedJDLContent,
        applicationType,
        applicationName: baseName,
        generatorVersion,
        skippedUserManagement,
        databaseType,
    });
}

function checkForErrors(jdlObject, configuration) {
    let applicationType = configuration.applicationType;
    let databaseType = configuration.databaseType;
    let skippedUserManagement = false;
    if (configuration.application) {
        applicationType = configuration.application['generator-jhipster'].applicationType;
        databaseType = configuration.application['generator-jhipster'].databaseType;
        skippedUserManagement = configuration.application['generator-jhipster'].skipUserManagement;
    }
    const errorChecker = new BusinessErrorChecker(jdlObject, {
        applicationType,
        databaseType,
        skippedUserManagement,
    });
    errorChecker.checkForErrors();
}

function importOnlyEntities(jdlObject, configuration) {
    let { applicationName, applicationType, databaseType } = configuration;

    let application = configuration.application;
    if (!configuration.application && doesFileExist('.yo-rc.json')) {
        application = readJSONFile('.yo-rc.json');
    }
    if (application && application['generator-jhipster']) {
        if (applicationType === undefined) applicationType = application['generator-jhipster'].applicationType;
        if (applicationName === undefined) applicationName = application['generator-jhipster'].baseName;
        if (databaseType === undefined) databaseType = application['generator-jhipster'].databaseType;
    }

    const entitiesPerApplicationMap = JDLWithoutApplicationToJSONConverter.convert({
        jdlObject,
        applicationName,
        applicationType,
        databaseType,
    });
    const jsonEntities = entitiesPerApplicationMap.get(applicationName);
    return exportJSONEntities(jsonEntities, configuration);
}

function importOneApplicationAndEntities(jdlObject, configuration) {
    const { skipFileGeneration } = configuration;

    const importState = {
        exportedApplications: [],
        exportedApplicationsWithEntities: {},
        exportedEntities: [],
        exportedDeployments: [],
    };
    const formattedApplication = JHipsterApplicationFormatter.formatApplicationToExport(jdlObject.getApplications()[0], configuration);
    if (!skipFileGeneration) {
        JHipsterApplicationExporter.exportApplication(formattedApplication);
    }
    importState.exportedApplications.push(formattedApplication);
    const jdlApplication = jdlObject.getApplications()[0];
    const applicationName = jdlApplication.getConfigurationOptionValue('baseName');
    const entitiesPerApplicationMap = JDLWithApplicationsToJSONConverter.convert({
        jdlObject,
    });
    const jsonEntities = entitiesPerApplicationMap.get(applicationName);
    importState.exportedApplicationsWithEntities[applicationName] = {
        config: formattedApplication['generator-jhipster'],
        entities: [],
    };
    if (jsonEntities.length !== 0) {
        const exportedJSONEntities = exportJSONEntities(jsonEntities, {
            applicationName,
            applicationType: jdlApplication.getConfigurationOptionValue('applicationType'),
            forSeveralApplications: false,
            skipFileGeneration,
        });
        importState.exportedApplicationsWithEntities[applicationName].entities = exportedJSONEntities;
        importState.exportedEntities = uniqBy([...importState.exportedEntities, ...exportedJSONEntities], 'name');
    }
    return importState;
}

function importApplicationsAndEntities(jdlObject, configuration) {
    const { skipFileGeneration } = configuration;

    const importState = {
        exportedApplications: [],
        exportedApplicationsWithEntities: {},
        exportedEntities: [],
        exportedDeployments: [],
    };

    const formattedApplications = JHipsterApplicationFormatter.formatApplicationsToExport(jdlObject.applications, configuration);
    importState.exportedApplications = formattedApplications;
    if (!skipFileGeneration) {
        JHipsterApplicationExporter.exportApplications(formattedApplications);
    }
    const entitiesPerApplicationMap = JDLWithApplicationsToJSONConverter.convert({
        jdlObject,
    });
    entitiesPerApplicationMap.forEach((jsonEntities, applicationName) => {
        const jdlApplication = jdlObject.getApplication(applicationName);
        const exportedJSONEntities = exportJSONEntities(jsonEntities, {
            applicationName,
            applicationType: jdlApplication.getConfigurationOptionValue('applicationType'),
            forSeveralApplications: true,
            skipFileGeneration,
        });
        const exportedConfig = importState.exportedApplications.find(config => applicationName === config['generator-jhipster'].baseName);
        importState.exportedApplicationsWithEntities[applicationName] = {
            config: exportedConfig['generator-jhipster'],
            entities: exportedJSONEntities,
        };
        importState.exportedEntities = uniqBy([...importState.exportedEntities, ...exportedJSONEntities], 'name');
    });
    return importState;
}

function importDeployments(deployments) {
    return JHipsterDeploymentExporter.exportDeployments(deployments);
}

function exportJSONEntities(entities, configuration) {
    const { forceNoFiltering, skipFileGeneration } = configuration;
    let baseName = configuration.applicationName;
    let applicationType = configuration.applicationType;

    if (configuration.application) {
        baseName = configuration.application['generator-jhipster'].baseName;
        applicationType = configuration.application['generator-jhipster'].applicationType;
    }

    return JHipsterEntityExporter.exportEntities({
        entities,
        forceNoFiltering,
        skipFileGeneration,
        application: {
            name: baseName,
            type: applicationType,
            forSeveralApplications: !!configuration.forSeveralApplications,
        },
    });
}
<commit_msg>Use curly brackets.<commit_after>/** Copyright 2013-2020 the original author or authors from the JHipster project.
 *
 * This file is part of the JHipster project, see http://www.jhipster.tech/
 * for more information.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const { uniqBy } = require('lodash');
const JDLReader = require('./readers/jdl-reader');
const { readJSONFile } = require('./readers/json-file-reader');
const { doesFileExist } = require('./utils/file-utils');
const DocumentParser = require('./converters/parsed-jdl-to-jdl-object/parsed-jdl-to-jdl-object-converter');
const JDLWithoutApplicationToJSONConverter = require('./converters/jdl-to-json/jdl-without-application-to-json-converter');
const JDLWithApplicationsToJSONConverter = require('./converters/jdl-to-json/jdl-with-applications-to-json-converter');
const JHipsterApplicationExporter = require('./exporters/applications/jhipster-application-exporter');
const JHipsterApplicationFormatter = require('./exporters/applications/jhipster-application-formatter');
const JHipsterDeploymentExporter = require('./exporters/jhipster-deployment-exporter');
const JHipsterEntityExporter = require('./exporters/jhipster-entity-exporter');
const BusinessErrorChecker = require('./validators/business-error-checker');

module.exports = {
    createImporterFromContent,
    createImporterFromFiles,
};

/**
 * Creates a new JDL importer from files.
 * There are two ways to create an importer:
 *   - By providing an existing application content, if there's one
 *   - Deprecated: providing some application options
 *
 * @param {Array} files - the JDL files to parse.
 * @param {Object} configuration - a configuration object.
 * @param {Object} configuration.application - an existing application file content
 * @param {String} configuration.applicationName - deprecated, the application's name, optional if parsing applications
 * @param {String} configuration.applicationType - deprecated, the application type, optional if parsing applications
 * @param {String} configuration.databaseType - deprecated, the database type, optional if parsing applications
 * @param {String} configuration.generatorVersion - deprecated, the generator's version, optional if parsing applications
 * @param {String} configuration.forceNoFiltering - whether to force filtering
 * @param {Boolean} configuration.skipFileGeneration - whether not to generate the .yo-rc.json file
 * @returns {Object} a JDL importer.
 * @throws {Error} if files aren't passed.
 */
function createImporterFromFiles(files, configuration) {
    if (!files) {
        throw new Error('Files must be passed to create a new JDL importer.');
    }
    const content = parseFiles(files);
    return makeJDLImporter(content, configuration || {});
}

/**
 * Creates a new JDL importer from a JDL string content.
 * There are two ways to create an importer:
 *   - By providing an existing application content, if there's one
 *   - Deprecated: providing some application options
 *
 * @param {String} jdlString - the JDL String content to parse.
 * @param {Object} configuration - a configuration object.
 * @param {Object} configuration.application - an existing application file content
 * @param {String} configuration.applicationName - deprecated, the application's name, optional if parsing applications
 * @param {String} configuration.applicationType - deprecated, the application type, optional if parsing applications
 * @param {String} configuration.databaseType - deprecated, the database type, optional if parsing applications
 * @param {String} configuration.generatorVersion - deprecated, the generator's version, optional if parsing applications
 * @param {String} configuration.forceNoFiltering - whether to force filtering
 * @param {Boolean} configuration.skipFileGeneration - whether not to generate the .yo-rc.json file
 * @returns {Object} a JDL importer.
 * @throws {Error} if the content isn't passed.
 */
function createImporterFromContent(jdlString, configuration) {
    if (!jdlString) {
        throw new Error('A JDL content must be passed to create a new JDL importer.');
    }
    const content = JDLReader.parseFromContent(jdlString);
    return makeJDLImporter(content, configuration || {});
}

function makeJDLImporter(content, configuration) {
    let importState = {
        exportedApplications: [],
        exportedApplicationsWithEntities: {},
        exportedEntities: [],
        exportedDeployments: [],
    };

    return {
        /**
         * Processes JDL files and converts them to JSON.
         * @returns {object} the state of the process:
         *          - exportedDeployments: the exported deployments, or an empty list
         *          - exportedApplications: the exported applications, or an empty list
         *          - exportedEntities: the exported entities, or an empty list
         */
        import: () => {
            const jdlObject = getJDLObject(content, configuration);
            checkForErrors(jdlObject, configuration);
            if (jdlObject.getApplicationQuantity() === 0 && jdlObject.getEntityQuantity() > 0) {
                importState.exportedEntities = importOnlyEntities(jdlObject, configuration);
            } else if (jdlObject.getApplicationQuantity() === 1) {
                importState = importOneApplicationAndEntities(jdlObject, configuration);
            } else {
                importState = importApplicationsAndEntities(jdlObject, configuration);
            }
            if (jdlObject.getDeploymentQuantity()) {
                importState.exportedDeployments = importDeployments(jdlObject.deployments);
            }
            return importState;
        },
    };
}

function parseFiles(files) {
    return JDLReader.parseFromFiles(files);
}

function getJDLObject(parsedJDLContent, configuration) {
    let baseName = configuration.applicationName;
    let applicationType = configuration.applicationType;
    let generatorVersion = configuration.generatorVersion;
    let databaseType = configuration.databaseType;
    let skippedUserManagement = false;

    if (configuration.application) {
        baseName = configuration.application['generator-jhipster'].baseName;
        applicationType = configuration.application['generator-jhipster'].applicationType;
        generatorVersion = configuration.application['generator-jhipster'].jhipsterVersion;
        skippedUserManagement = configuration.application['generator-jhipster'].skipUserManagement;
        databaseType = configuration.application['generator-jhipster'].databaseType;
    }

    return DocumentParser.parseFromConfigurationObject({
        parsedContent: parsedJDLContent,
        applicationType,
        applicationName: baseName,
        generatorVersion,
        skippedUserManagement,
        databaseType,
    });
}

function checkForErrors(jdlObject, configuration) {
    let applicationType = configuration.applicationType;
    let databaseType = configuration.databaseType;
    let skippedUserManagement = false;
    if (configuration.application) {
        applicationType = configuration.application['generator-jhipster'].applicationType;
        databaseType = configuration.application['generator-jhipster'].databaseType;
        skippedUserManagement = configuration.application['generator-jhipster'].skipUserManagement;
    }
    const errorChecker = new BusinessErrorChecker(jdlObject, {
        applicationType,
        databaseType,
        skippedUserManagement,
    });
    errorChecker.checkForErrors();
}

function importOnlyEntities(jdlObject, configuration) {
    let { applicationName, applicationType, databaseType } = configuration;

    let application = configuration.application;
    if (!configuration.application && doesFileExist('.yo-rc.json')) {
        application = readJSONFile('.yo-rc.json');
    }
    if (application && application['generator-jhipster']) {
        if (applicationType === undefined) {
            applicationType = application['generator-jhipster'].applicationType;
        }
        if (applicationName === undefined) {
            applicationName = application['generator-jhipster'].baseName;
        }
        if (databaseType === undefined) {
            databaseType = application['generator-jhipster'].databaseType;
        }
    }

    const entitiesPerApplicationMap = JDLWithoutApplicationToJSONConverter.convert({
        jdlObject,
        applicationName,
        applicationType,
        databaseType,
    });
    const jsonEntities = entitiesPerApplicationMap.get(applicationName);
    return exportJSONEntities(jsonEntities, configuration);
}

function importOneApplicationAndEntities(jdlObject, configuration) {
    const { skipFileGeneration } = configuration;

    const importState = {
        exportedApplications: [],
        exportedApplicationsWithEntities: {},
        exportedEntities: [],
        exportedDeployments: [],
    };
    const formattedApplication = JHipsterApplicationFormatter.formatApplicationToExport(jdlObject.getApplications()[0], configuration);
    if (!skipFileGeneration) {
        JHipsterApplicationExporter.exportApplication(formattedApplication);
    }
    importState.exportedApplications.push(formattedApplication);
    const jdlApplication = jdlObject.getApplications()[0];
    const applicationName = jdlApplication.getConfigurationOptionValue('baseName');
    const entitiesPerApplicationMap = JDLWithApplicationsToJSONConverter.convert({
        jdlObject,
    });
    const jsonEntities = entitiesPerApplicationMap.get(applicationName);
    importState.exportedApplicationsWithEntities[applicationName] = {
        config: formattedApplication['generator-jhipster'],
        entities: [],
    };
    if (jsonEntities.length !== 0) {
        const exportedJSONEntities = exportJSONEntities(jsonEntities, {
            applicationName,
            applicationType: jdlApplication.getConfigurationOptionValue('applicationType'),
            forSeveralApplications: false,
            skipFileGeneration,
        });
        importState.exportedApplicationsWithEntities[applicationName].entities = exportedJSONEntities;
        importState.exportedEntities = uniqBy([...importState.exportedEntities, ...exportedJSONEntities], 'name');
    }
    return importState;
}

function importApplicationsAndEntities(jdlObject, configuration) {
    const { skipFileGeneration } = configuration;

    const importState = {
        exportedApplications: [],
        exportedApplicationsWithEntities: {},
        exportedEntities: [],
        exportedDeployments: [],
    };

    const formattedApplications = JHipsterApplicationFormatter.formatApplicationsToExport(jdlObject.applications, configuration);
    importState.exportedApplications = formattedApplications;
    if (!skipFileGeneration) {
        JHipsterApplicationExporter.exportApplications(formattedApplications);
    }
    const entitiesPerApplicationMap = JDLWithApplicationsToJSONConverter.convert({
        jdlObject,
    });
    entitiesPerApplicationMap.forEach((jsonEntities, applicationName) => {
        const jdlApplication = jdlObject.getApplication(applicationName);
        const exportedJSONEntities = exportJSONEntities(jsonEntities, {
            applicationName,
            applicationType: jdlApplication.getConfigurationOptionValue('applicationType'),
            forSeveralApplications: true,
            skipFileGeneration,
        });
        const exportedConfig = importState.exportedApplications.find(config => applicationName === config['generator-jhipster'].baseName);
        importState.exportedApplicationsWithEntities[applicationName] = {
            config: exportedConfig['generator-jhipster'],
            entities: exportedJSONEntities,
        };
        importState.exportedEntities = uniqBy([...importState.exportedEntities, ...exportedJSONEntities], 'name');
    });
    return importState;
}

function importDeployments(deployments) {
    return JHipsterDeploymentExporter.exportDeployments(deployments);
}

function exportJSONEntities(entities, configuration) {
    const { forceNoFiltering, skipFileGeneration } = configuration;
    let baseName = configuration.applicationName;
    let applicationType = configuration.applicationType;

    if (configuration.application) {
        baseName = configuration.application['generator-jhipster'].baseName;
        applicationType = configuration.application['generator-jhipster'].applicationType;
    }

    return JHipsterEntityExporter.exportEntities({
        entities,
        forceNoFiltering,
        skipFileGeneration,
        application: {
            name: baseName,
            type: applicationType,
            forSeveralApplications: !!configuration.forSeveralApplications,
        },
    });
}
<|endoftext|>


<commit_before>
module.exports = exports = configure

/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , glob = require('glob')
  , which = require('which')
  , semver = require('semver')
  , mkdirp = require('./util/mkdirp')
  , createHook = require('./util/hook')
  , asyncEmit = require('./util/asyncEmit')
  , win = process.platform == 'win32'

exports.usage = 'Generates ' + (win ? 'MSVC project files' : 'a Makefile') + ' for the current module'

function configure (gyp, argv, callback) {

  var python = process.env.PYTHON || gyp.opts.python || 'python'
    , buildDir = path.resolve('build')
    , configPath
    , emitter
    , versionStr
    , version

  // Very first step is to load up the user-defined 'gyp-configure.js' file if it
  // exists. We relay filecycle events using the eventemitter returned from this
  createHook('gyp-configure.js', function (err, _e) {
    if (err) return callback(err)
    emitter = _e
    checkPython()
  })

  // Make sure that Python is in the $PATH
  function checkPython () {
    which(python, function (err, execPath) {
      if (err) {
        if (win) {
          guessPython()
        } else {
          failNoPython()
        }
        return
      }
      gyp.verbose('`which` succeeded for `' + python + '`', execPath)
      getTargetVersion()
    })
  }

  // Called on Windows when "python" isn't available in the current $PATH.
  // We're gonna glob C:\python2*
  function guessPython () {
    gyp.verbose('could not find "' + python + '". guessing location')
    var rootDir = process.env.HOMEDRIVE || process.env.SystemDrive || 'C:\\'
    if (rootDir[rootDir.length - 1] !== '\\') {
      rootDir += '\\'
    }
    var pythonPath = path.resolve(rootDir, 'Python27', 'python.exe')
    gyp.verbose('ensuring that file exists:', pythonPath)
    fs.stat(pythonPath, function (err, stat) {
      if (err) {
        if (err.code == 'ENOENT') {
          failNoPython()
        } else {
          callbackk(err)
        }
        return
      }
      python = pythonPath
      getTargetVersion()
    })
  }

  function failNoPython () {
    callback(new Error('Can\'t find Python, you can set the PYTHON env variable.'))
  }

  function getTargetVersion () {
    if (gyp.opts.target) {
      // if --target was given, then ensure that version is installed
      versionStr = gyp.opts.target
      gyp.verbose('compiling against --target node version', versionStr)
    } else {
      // if no --target was specified then use the current host node version
      versionStr = process.version
      gyp.verbose('no --target version specified, falling back to host node version', versionStr)
    }
    version = semver.parse(versionStr)
    if (!version) {
      return callback(new Error('Invalid version number: ' + versionStr))
    }
    gyp.opts.ensure = true
    gyp.commands.install([ versionStr ], function (err, _version) {
      if (err) return callback(err)
      version = _version
      gyp.verbose('setting target version to:', version)
      createBuildDir()
    })
  }

  function createBuildDir () {
    gyp.verbose('attempting to create "build" dir', buildDir)
    mkdirp(buildDir, function (err, isNew) {
      if (err) return callback(err)
      gyp.verbose('"build" dir needed to be created?', isNew)
      createConfigFile()
    })
  }

  function createConfigFile (err) {
    if (err) return callback(err)
    gyp.verbose('creating build/config.gypi file')

    configPath = path.resolve(buildDir, 'config.gypi')

    var config = process.config || {}
      , defaults = config.target_defaults
      , variables = config.variables

    if (!defaults) {
      defaults = config.target_defaults = {}
    }
    if (!variables) {
      variables = config.variables = {}
    }
    if (!defaults.cflags) {
      defaults.cflags = []
    }
    if (!defaults.defines) {
      defaults.defines = []
    }
    if (!defaults.include_dirs) {
      defaults.include_dirs = []
    }
    if (!defaults.libraries) {
      defaults.libraries = []
    }

    // set the default_configuration prop
    if ('debug' in gyp.opts) {
      defaults.default_configuration = gyp.opts.debug ? 'Debug' : 'Release'
    }
    if (!defaults.default_configuration) {
      defaults.default_configuration = 'Release'
    }

    // set the target_arch variable
    variables.target_arch = gyp.opts.arch || process.arch || 'ia32'

    // loop through the rest of the opts and add the unknown ones as variables.
    // this allows for module-specific configure flags like:
    //
    //   $ node-gyp configure --shared-libxml2
    Object.keys(gyp.opts).forEach(function (opt) {
      if (opt === 'argv') return
      if (opt in gyp.configDefs) return
      variables[opt.replace(/-/g, '_')] = gyp.opts[opt]
    })

    // ensures that any boolean values from `process.config` get stringified
    function boolsToString (k, v) {
      if (typeof v === 'boolean')
        return String(v)
      return v
    }

    // now write out the config.gypi file to the build/ dir
    var prefix = '# Do not edit. File was generated by node-gyp\'s "configure" step'
      , json = JSON.stringify(config, boolsToString, 2)
    gyp.verbose('writing out config file', configPath)
    fs.writeFile(configPath, [prefix, json, ''].join('\n'), runGypAddon)
  }

  function runGypAddon (err) {
    if (err) return callback(err)

    var devDir = path.resolve(process.env.HOME, '.node-gyp', version)
      , gyp_addon = path.resolve(devDir, 'tools', 'gyp_addon')

    if (!~argv.indexOf('-f') && !~argv.indexOf('--format')) {
      if (win) {
        gyp.verbose('gyp format was not specified; forcing "msvs"')
        // force the 'make' target for non-Windows
        argv.push('-f', 'msvs')
      } else {
        gyp.verbose('gyp format was not specified; forcing "make"')
        // force the 'make' target for non-Windows
        argv.push('-f', 'make')
      }
    }

    function hasMsvsVersion () {
      return argv.some(function (arg) {
        return arg.indexOf('msvs_version') === 0
      })
    }

    if (win && !hasMsvsVersion()) {
      if ('msvs_version' in gyp.opts) {
        argv.push('-G', 'msvs_version=' + gyp.opts.msvs_version)
      } else {
        argv.push('-G', 'msvs_version=2010')
      }
    }

    // include the "config.gypi" file that was generated
    argv.unshift('-I' + configPath)

    // enforce use of the "binding.gyp" file
    argv.unshift('binding.gyp')

    // execute `gyp_addon` from the current target node version
    argv.unshift(gyp_addon)

    asyncEmit(emitter, 'before', function (err) {
      if (err) return callback(err)

      var cp = gyp.spawn(python, argv)
      cp.on('exit', onCpExit)
    })
  }

  /**
   * Called when the `gyp_addon` child process exits.
   */

  function onCpExit (code, signal) {
    asyncEmit(emitter, 'after', function (err) {
      if (err) {
        callback(err)
      } else if (code !== 0) {
        callback(new Error('`gyp_addon` failed with exit code: ' + code))
      } else {
        // we're done
        callback()
      }
    })
  }

}
<commit_msg>configure: set the PYTHON env variable<commit_after>
module.exports = exports = configure

/**
 * Module dependencies.
 */

var fs = require('fs')
  , path = require('path')
  , glob = require('glob')
  , which = require('which')
  , semver = require('semver')
  , mkdirp = require('./util/mkdirp')
  , createHook = require('./util/hook')
  , asyncEmit = require('./util/asyncEmit')
  , win = process.platform == 'win32'

exports.usage = 'Generates ' + (win ? 'MSVC project files' : 'a Makefile') + ' for the current module'

function configure (gyp, argv, callback) {

  var python = process.env.PYTHON || gyp.opts.python || 'python'
    , buildDir = path.resolve('build')
    , configPath
    , emitter
    , versionStr
    , version

  // Very first step is to load up the user-defined 'gyp-configure.js' file if it
  // exists. We relay filecycle events using the eventemitter returned from this
  createHook('gyp-configure.js', function (err, _e) {
    if (err) return callback(err)
    emitter = _e
    checkPython()
  })

  // Make sure that Python is in the $PATH
  function checkPython () {
    which(python, function (err, execPath) {
      if (err) {
        if (win) {
          guessPython()
        } else {
          failNoPython()
        }
        return
      }
      gyp.verbose('`which` succeeded for `' + python + '`', execPath)
      getTargetVersion()
    })
  }

  // Called on Windows when "python" isn't available in the current $PATH.
  // We're gonna glob C:\python2*
  function guessPython () {
    gyp.verbose('could not find "' + python + '". guessing location')
    var rootDir = process.env.HOMEDRIVE || process.env.SystemDrive || 'C:\\'
    if (rootDir[rootDir.length - 1] !== '\\') {
      rootDir += '\\'
    }
    var pythonPath = path.resolve(rootDir, 'Python27', 'python.exe')
    gyp.verbose('ensuring that file exists:', pythonPath)
    fs.stat(pythonPath, function (err, stat) {
      if (err) {
        if (err.code == 'ENOENT') {
          failNoPython()
        } else {
          callbackk(err)
        }
        return
      }
      python = pythonPath
      getTargetVersion()
    })
  }

  function failNoPython () {
    callback(new Error('Can\'t find Python, you can set the PYTHON env variable.'))
  }

  function getTargetVersion () {

    // 'python' should be set by now
    process.env.PYTHON = python

    if (gyp.opts.target) {
      // if --target was given, then ensure that version is installed
      versionStr = gyp.opts.target
      gyp.verbose('compiling against --target node version', versionStr)
    } else {
      // if no --target was specified then use the current host node version
      versionStr = process.version
      gyp.verbose('no --target version specified, falling back to host node version', versionStr)
    }
    version = semver.parse(versionStr)
    if (!version) {
      return callback(new Error('Invalid version number: ' + versionStr))
    }
    gyp.opts.ensure = true
    gyp.commands.install([ versionStr ], function (err, _version) {
      if (err) return callback(err)
      version = _version
      gyp.verbose('setting target version to:', version)
      createBuildDir()
    })
  }

  function createBuildDir () {
    gyp.verbose('attempting to create "build" dir', buildDir)
    mkdirp(buildDir, function (err, isNew) {
      if (err) return callback(err)
      gyp.verbose('"build" dir needed to be created?', isNew)
      createConfigFile()
    })
  }

  function createConfigFile (err) {
    if (err) return callback(err)
    gyp.verbose('creating build/config.gypi file')

    configPath = path.resolve(buildDir, 'config.gypi')

    var config = process.config || {}
      , defaults = config.target_defaults
      , variables = config.variables

    if (!defaults) {
      defaults = config.target_defaults = {}
    }
    if (!variables) {
      variables = config.variables = {}
    }
    if (!defaults.cflags) {
      defaults.cflags = []
    }
    if (!defaults.defines) {
      defaults.defines = []
    }
    if (!defaults.include_dirs) {
      defaults.include_dirs = []
    }
    if (!defaults.libraries) {
      defaults.libraries = []
    }

    // set the default_configuration prop
    if ('debug' in gyp.opts) {
      defaults.default_configuration = gyp.opts.debug ? 'Debug' : 'Release'
    }
    if (!defaults.default_configuration) {
      defaults.default_configuration = 'Release'
    }

    // set the target_arch variable
    variables.target_arch = gyp.opts.arch || process.arch || 'ia32'

    // loop through the rest of the opts and add the unknown ones as variables.
    // this allows for module-specific configure flags like:
    //
    //   $ node-gyp configure --shared-libxml2
    Object.keys(gyp.opts).forEach(function (opt) {
      if (opt === 'argv') return
      if (opt in gyp.configDefs) return
      variables[opt.replace(/-/g, '_')] = gyp.opts[opt]
    })

    // ensures that any boolean values from `process.config` get stringified
    function boolsToString (k, v) {
      if (typeof v === 'boolean')
        return String(v)
      return v
    }

    // now write out the config.gypi file to the build/ dir
    var prefix = '# Do not edit. File was generated by node-gyp\'s "configure" step'
      , json = JSON.stringify(config, boolsToString, 2)
    gyp.verbose('writing out config file', configPath)
    fs.writeFile(configPath, [prefix, json, ''].join('\n'), runGypAddon)
  }

  function runGypAddon (err) {
    if (err) return callback(err)

    var devDir = path.resolve(process.env.HOME, '.node-gyp', version)
      , gyp_addon = path.resolve(devDir, 'tools', 'gyp_addon')

    if (!~argv.indexOf('-f') && !~argv.indexOf('--format')) {
      if (win) {
        gyp.verbose('gyp format was not specified; forcing "msvs"')
        // force the 'make' target for non-Windows
        argv.push('-f', 'msvs')
      } else {
        gyp.verbose('gyp format was not specified; forcing "make"')
        // force the 'make' target for non-Windows
        argv.push('-f', 'make')
      }
    }

    function hasMsvsVersion () {
      return argv.some(function (arg) {
        return arg.indexOf('msvs_version') === 0
      })
    }

    if (win && !hasMsvsVersion()) {
      if ('msvs_version' in gyp.opts) {
        argv.push('-G', 'msvs_version=' + gyp.opts.msvs_version)
      } else {
        argv.push('-G', 'msvs_version=2010')
      }
    }

    // include the "config.gypi" file that was generated
    argv.unshift('-I' + configPath)

    // enforce use of the "binding.gyp" file
    argv.unshift('binding.gyp')

    // execute `gyp_addon` from the current target node version
    argv.unshift(gyp_addon)

    asyncEmit(emitter, 'before', function (err) {
      if (err) return callback(err)

      var cp = gyp.spawn(python, argv)
      cp.on('exit', onCpExit)
    })
  }

  /**
   * Called when the `gyp_addon` child process exits.
   */

  function onCpExit (code, signal) {
    asyncEmit(emitter, 'after', function (err) {
      if (err) {
        callback(err)
      } else if (code !== 0) {
        callback(new Error('`gyp_addon` failed with exit code: ' + code))
      } else {
        // we're done
        callback()
      }
    })
  }

}
<|endoftext|>


<commit_before>/*jslint plusplus: true */

"use strict";
var oBlogsPager = {
    template: '

@date

@title

@content

Read more

',
    pageIndex: 0,
    pagesize: 6
}, id, highlightid, sClickedHighlightTitle, iClickedHighlightID,
iTotalBlogs = 0,
iIterator = 0,
iMaxPageIndex,
oBlogsData = null,
oBlogsContainer,
sScrollElement = "body,html",
sLoadingClass = "Loading",
     iCount, iTotalHighlight = 6, oBlogsHighlightTitle = [iTotalHighlight], oHighlightBlogsID = [iTotalHighlight];

function renderBlogs() {
    var iStart, iEnd, entry1, sDate, oDatePart, oDate, sTitle, sContent, sRawTitle, slink;
    oBlogsContainer.removeClass(sLoadingClass);
    if (iTotalBlogs) {
        iStart = oBlogsPager.pageIndex * oBlogsPager.pagesize;
        if (iStart >= iTotalBlogs) {
            iStart = iTotalBlogs - 1;
            oBlogsPager.pageIndex = iStart;
            if (iTotalBlogs > 1) {
                $("#Previous").removeClass("hidden");
                $("#Next").addClass("hidden");
            }
        } else if (iStart <= 0) {
            iStart = 0;
            oBlogsPager.pageIndex = iStart;
            if (iTotalBlogs > 1) {
                $("#Next").removeClass("hidden");
                $("#Previous").addClass("hidden");
            }
            else if (iTotalBlogs = 1) {
                $("#Next").addClass("hidden");
                $("#Previous").addClass("hidden");
            }
        }
        iEnd = iStart + oBlogsPager.pagesize;
        if (iEnd > iTotalBlogs) {
            iEnd = iTotalBlogs;
        }
        for (iIterator = iStart; iIterator < iEnd; iIterator++) {
            entry1 = oBlogsData.getElementsByTagName('entry').item(iIterator);
            if (entry1) {
                sDate = entry1.getElementsByTagName('published')[0].childNodes[0].nodeValue.toLowerCase().split("t");
                oDatePart = [];
                if (sDate[0]) {
                    oDatePart = sDate[0].split("-");
                }
                oDate = null;
                if (oDatePart.length === 3) {
                    oDate = new Date(oDatePart[0], (oDatePart[1] - 1), oDatePart[2]);
                } else {
                    oDate = new Date(sDate[0]);
                }
                oDate = oDate.format();
                sTitle = entry1.getElementsByTagName('title')[0].childNodes[0].nodeValue;
                sRawTitle = sTitle;
                slink = entry1.getElementsByTagName('link')[2].getAttribute('href');

                sContent = entry1.getElementsByTagName('content')[0].childNodes[0].nodeValue;

                $("#bloggerContent").html(sContent);
                var bloggerContent = document.getElementById("bloggerContent");
                var imgs = bloggerContent.getElementsByTagName('img');
                var img, src = "";

                if (typeof imgs !== "undefined" && imgs.length > 0) {
                    img = imgs[0];
                    src = img.src;
                    img.parentNode.removeChild(img);
                }
                sContent = $("#bloggerContent").html();
                oBlogsContainer.append(oBlogsPager.template.replace(/@title/g, sRawTitle).replace("@href", slink).replace("@date", oDate).replace("@content", sContent).replace("@href1", slink).replace("@tooltip", getFirstNWordsWithEllipses(sTitle, 4)));
            }
        }
        oBlogsContainer.find("img").addClass("post - media");

        $('#LoadPageBlogs *').removeAttr('style');
        for (var iCount = 0; iCount < iTotalHighlight; iCount++) {
            for (iIterator = 0; iIterator < iTotalBlogs; iIterator++) {
                entry1 = oBlogsData.getElementsByTagName('entry').item(iIterator);
                if (entry1) {
                    sTitle = entry1.getElementsByTagName('title')[0].childNodes[0].nodeValue;
                    if (sTitle === oBlogsHighlightTitle[iCount]) {
                        oHighlightBlogsID[iCount] = iIterator;
                        break;
                    }
                }
            }
        }
    }
}
function loadBlogs(sBlogsData) {
    try {
        var parser = new DOMParser();
        oBlogsData = parser.parseFromString(sBlogsData, "text/xml");
        iTotalBlogs = oBlogsData.getElementsByTagName('entry').length;
        if (iTotalBlogs || oBlogsData.getElementsByTagName('content')) {
            iMaxPageIndex = Math.round(iTotalBlogs / oBlogsPager.pagesize);
            //$("#Pagination").show();
            renderBlogs();
        }
    } catch (ignore) {
    }
}

function loadBlogsGrid() {
    oBlogsContainer.html("").addClass(sLoadingClass);
    getBloggerData('https://www.blogger.com/feeds/3262801613185975083/posts/default/-/Blogs', getBlogsSuccess, getBlogsOnComplete);
}
function getBlogsSuccess(sResponse) {
    var iTop;
    loadBlogs(sResponse);
    if (typeof highlightid !== "undefined" && highlightid !== "") {
        //debugger;
        highlightid = parseInt(iClickedHighlightID % oBlogsPager.pagesize);
        iTop = $("#LoadPageBlogs").children('div').eq(Number(highlightid) * 3).offset().top - 65;
        $(sScrollElement).animate({ scrollTop: iTop }, 300);
    } else if (typeof id !== "undefined" && id !== "") {
        //debugger;
        id = id > oBlogsPager.pagesize ? id - oBlogsPager.pagesize : id;
        iTop = $("#LoadPageBlogs").children('div').eq(id - 1).offset().top - $("#highlights").offset().top - 65 - 34; // 34 for date of blog
        $(sScrollElement).animate({ scrollTop: iTop }, 300);
    }

}
function getBlogsOnComplete() {
    oBlogsContainer.removeClass(sLoadingClass);
}

function blogsConstructor() {
    //debugger;

    oBlogsPager.pageIndex = 0;
    highlightid = "";
    oBlogsContainer = $("#LoadPageBlogs");
    var iTop = 0;
    id = getParameterByName("id");

    if (typeof id !== "undefined" && id !== "") {
        $(sScrollElement).animate({ scrollTop: iTop }, 500);
        oBlogsPager.pageIndex = id > oBlogsPager.pagesize ? 1 : 0;

    }

    loadBlogsGrid();

    $("#Pagination p").click(function () {
        var oCurrentElement = $(this),
            iClicked = oCurrentElement.attr("data-clicked");
        if (!oCurrentElement.hasClass("hidden")) {
            if (iClicked === "0") {
                oBlogsPager.pageIndex--;
                $("#Next").removeClass("hidden");
                if (oBlogsPager.pageIndex <= 0) {
                    oBlogsPager.pageIndex = 0;
                    $("#Previous").addClass("hidden");
                }
            } else {
                oBlogsPager.pageIndex++;
                if (oBlogsPager.pageIndex >= iMaxPageIndex) {
                    oBlogsPager.pageIndex = iMaxPageIndex;
                    $("#Next").addClass("hidden");
                } else {
                    $("#Previous").removeClass("hidden");
                }
            }
            oBlogsContainer.html("").addClass(sLoadingClass);
            iTop = oBlogsContainer.offset().top - 65; // -65 for header/padding
            $(sScrollElement).animate({ scrollTop: iTop }, 500);
            renderBlogs();
        }
    });

};
<commit_msg>Simplified Blog main page<commit_after>/*jslint plusplus: true */

"use strict";
var oBlogsPager = {
    template: '

@date

@title

Read more

',
    pageIndex: 0,
    pagesize: 6
}, id, highlightid, sClickedHighlightTitle, iClickedHighlightID,
iTotalBlogs = 0,
iIterator = 0,
iMaxPageIndex,
oBlogsData = null,
oBlogsContainer,
sScrollElement = "body,html",
sLoadingClass = "Loading",
     iCount, iTotalHighlight = 6, oBlogsHighlightTitle = [iTotalHighlight], oHighlightBlogsID = [iTotalHighlight];

function renderBlogs() {
    var iStart, iEnd, entry1, sDate, oDatePart, oDate, sTitle, sContent, sRawTitle, slink;
    oBlogsContainer.removeClass(sLoadingClass);
    if (iTotalBlogs) {
        iStart = oBlogsPager.pageIndex * oBlogsPager.pagesize;
        if (iStart >= iTotalBlogs) {
            iStart = iTotalBlogs - 1;
            oBlogsPager.pageIndex = iStart;
            if (iTotalBlogs > 1) {
                $("#Previous").removeClass("hidden");
                $("#Next").addClass("hidden");
            }
        } else if (iStart <= 0) {
            iStart = 0;
            oBlogsPager.pageIndex = iStart;
            if (iTotalBlogs > 1) {
                $("#Next").removeClass("hidden");
                $("#Previous").addClass("hidden");
            }
            else if (iTotalBlogs = 1) {
                $("#Next").addClass("hidden");
                $("#Previous").addClass("hidden");
            }
        }
        iEnd = iStart + oBlogsPager.pagesize;
        if (iEnd > iTotalBlogs) {
            iEnd = iTotalBlogs;
        }
        for (iIterator = iStart; iIterator < iEnd; iIterator++) {
            entry1 = oBlogsData.getElementsByTagName('entry').item(iIterator);
            if (entry1) {
                sDate = entry1.getElementsByTagName('published')[0].childNodes[0].nodeValue.toLowerCase().split("t");
                oDatePart = [];
                if (sDate[0]) {
                    oDatePart = sDate[0].split("-");
                }
                oDate = null;
                if (oDatePart.length === 3) {
                    oDate = new Date(oDatePart[0], (oDatePart[1] - 1), oDatePart[2]);
                } else {
                    oDate = new Date(sDate[0]);
                }
                oDate = oDate.format();
                sTitle = entry1.getElementsByTagName('title')[0].childNodes[0].nodeValue;
                sRawTitle = sTitle;
                slink = entry1.getElementsByTagName('link')[2].getAttribute('href');

                sContent = entry1.getElementsByTagName('content')[0].childNodes[0].nodeValue;

                $("#bloggerContent").html(sContent);
                var bloggerContent = document.getElementById("bloggerContent");
                var imgs = bloggerContent.getElementsByTagName('img');
                var img, src = "";

                if (typeof imgs !== "undefined" && imgs.length > 0) {
                    img = imgs[0];
                    src = img.src;
                    img.parentNode.removeChild(img);
                }
                sContent = $("#bloggerContent").html();
                oBlogsContainer.append(oBlogsPager.template.replace(/@title/g, sRawTitle).replace("@href", slink).replace("@date", oDate).replace("@content", sContent).replace("@href1", slink).replace("@tooltip", getFirstNWordsWithEllipses(sTitle, 4)));
            }
        }
        oBlogsContainer.find("img").addClass("post - media");

        $('#LoadPageBlogs *').removeAttr('style');
        for (var iCount = 0; iCount < iTotalHighlight; iCount++) {
            for (iIterator = 0; iIterator < iTotalBlogs; iIterator++) {
                entry1 = oBlogsData.getElementsByTagName('entry').item(iIterator);
                if (entry1) {
                    sTitle = entry1.getElementsByTagName('title')[0].childNodes[0].nodeValue;
                    if (sTitle === oBlogsHighlightTitle[iCount]) {
                        oHighlightBlogsID[iCount] = iIterator;
                        break;
                    }
                }
            }
        }
    }
}
function loadBlogs(sBlogsData) {
    try {
        var parser = new DOMParser();
        oBlogsData = parser.parseFromString(sBlogsData, "text/xml");
        iTotalBlogs = oBlogsData.getElementsByTagName('entry').length;
        if (iTotalBlogs || oBlogsData.getElementsByTagName('content')) {
            iMaxPageIndex = Math.round(iTotalBlogs / oBlogsPager.pagesize);
            //$("#Pagination").show();
            renderBlogs();
        }
    } catch (ignore) {
    }
}

function loadBlogsGrid() {
    oBlogsContainer.html("").addClass(sLoadingClass);
    getBloggerData('https://www.blogger.com/feeds/3262801613185975083/posts/default/-/Blogs', getBlogsSuccess, getBlogsOnComplete);
}
function getBlogsSuccess(sResponse) {
    var iTop;
    loadBlogs(sResponse);
    if (typeof highlightid !== "undefined" && highlightid !== "") {
        //debugger;
        highlightid = parseInt(iClickedHighlightID % oBlogsPager.pagesize);
        iTop = $("#LoadPageBlogs").children('div').eq(Number(highlightid) * 3).offset().top - 65;
        $(sScrollElement).animate({ scrollTop: iTop }, 300);
    } else if (typeof id !== "undefined" && id !== "") {
        //debugger;
        id = id > oBlogsPager.pagesize ? id - oBlogsPager.pagesize : id;
        iTop = $("#LoadPageBlogs").children('div').eq(id - 1).offset().top - $("#highlights").offset().top - 65 - 34; // 34 for date of blog
        $(sScrollElement).animate({ scrollTop: iTop }, 300);
    }

}
function getBlogsOnComplete() {
    oBlogsContainer.removeClass(sLoadingClass);
}

function blogsConstructor() {
    //debugger;

    oBlogsPager.pageIndex = 0;
    highlightid = "";
    oBlogsContainer = $("#LoadPageBlogs");
    var iTop = 0;
    id = getParameterByName("id");

    if (typeof id !== "undefined" && id !== "") {
        $(sScrollElement).animate({ scrollTop: iTop }, 500);
        oBlogsPager.pageIndex = id > oBlogsPager.pagesize ? 1 : 0;

    }

    loadBlogsGrid();

    $("#Pagination p").click(function () {
        var oCurrentElement = $(this),
            iClicked = oCurrentElement.attr("data-clicked");
        if (!oCurrentElement.hasClass("hidden")) {
            if (iClicked === "0") {
                oBlogsPager.pageIndex--;
                $("#Next").removeClass("hidden");
                if (oBlogsPager.pageIndex <= 0) {
                    oBlogsPager.pageIndex = 0;
                    $("#Previous").addClass("hidden");
                }
            } else {
                oBlogsPager.pageIndex++;
                if (oBlogsPager.pageIndex >= iMaxPageIndex) {
                    oBlogsPager.pageIndex = iMaxPageIndex;
                    $("#Next").addClass("hidden");
                } else {
                    $("#Previous").removeClass("hidden");
                }
            }
            oBlogsContainer.html("").addClass(sLoadingClass);
            iTop = oBlogsContainer.offset().top - 65; // -65 for header/padding
            $(sScrollElement).animate({ scrollTop: iTop }, 500);
            renderBlogs();
        }
    });

};
<|endoftext|>


<commit_before>'use strict';

angular.module('arachne.controllers')

    .controller('SearchFormController', ['$scope', '$location', 'arachneSettings', '$http', function ($scope, $location, arachneSettings, $http) {

        $scope.search = function (fq) {
            if ($scope.q) {
                var url = '/search?q=' + $scope.q;
                if (fq) url += "&fq=" + fq;
                $scope.q = null;
                $location.url(url);
            }
        };

        $scope.getSuggestions = function (value) {
            return $http.get(arachneSettings.dataserviceUri + '/suggest?q=' + value)
                .then(function (response) {
                    return response.data.suggestions;
                });
        };
    }
    ]);<commit_msg>Revert "Revert "added promise check""<commit_after>'use strict';

angular.module('arachne.controllers')

    .controller('SearchFormController', ['$scope', '$location', 'arachneSettings', '$http', function ($scope, $location, arachneSettings, $http) {

        $scope.search = function (fq) {
            if ($scope.q) {
                var url = '/search?q=' + $scope.q;
                if (fq) url += "&fq=" + fq;
                $scope.q = null;
                $location.url(url);
            }
        };

        $scope.getSuggestions = function (value) {
            var promise = $http.get(arachneSettings.dataserviceUri + '/suggest?q=' + value)
                .then(function (response) {
                    return response.data.suggestions;
                });
            if(promise != 'undefined') return promise;
        };
    }
    ]);<|endoftext|>


<commit_before>'use strict';

// Imports
const {join} = require('path');
const {name, version} = require('../package.json');

// Constants
const VERSION_STAMP = `${name} v${version}`;
const BIN_DIR = join(__dirname, '../bin');
const DEF_CODE = cmd => [
  '#!/usr/bin/env node',
  '\'use strict\';',
  '// eslint-disable-next-line max-len',
  `const cmd = module.exports = '${cmd.replace(/'/g, '\\\'')}';`,
  'if (require.main === module) {',
  '  require(\'../../lib/index\').run(cmd);',
  '}',
].join('\n');
const ALIASES = {
  // Git
  git: {
    // STATUS
    gs: 'git status',
    gl: 'git log --decorate $*',
    gl1: 'git log --decorate --oneline $*',
    gd: 'ngm-diff-wh $*',
    gdh: 'ngm-diff-wh HEAD $*',
    gd1: 'ngm-diff-wh HEAD~1 $*',

    // STASH
    gst: 'git stash $*',
    gstk: 'git stash save --keep-index $*',
    gstl: 'git stash list $*',
    gstp: 'git stash pop --index $*',

    // CHECKOUT
    gco: 'git checkout $*',
    gcom: 'git checkout master $*',
    gcopr: 'git fetch upstream pull/$1/head && git checkout FETCH_HEAD',

    // ADD / COMMIT
    gaa: 'git add --all',
    gcm: 'git commit --all $*',
    gcmf: 'git commit --all --fixup HEAD~${1:0}',
    gcma: 'git commit --all --amend $*',
    gcmane: 'git commit --all --amend --no-edit $*',

    // PUSH
    gp: 'git push --verbose $*',
    gpf: 'git push --force-with-lease --verbose $*',

    // BRANCH
    gb: 'git branch $*',
    gbc: 'git checkout master -b $1 && git push --verbose --set-upstream origin $1',
    gbd: 'git branch --delete --force $*',

    // PULL(-REBASE)
    gpr: 'git pull --rebase $*',
    gpro: 'git pull --rebase origin $*',
    gprom: 'git pull --rebase origin master $*',
    gpru: 'git pull --rebase upstream $*',
    gprum: 'git pull --rebase upstream master $*',

    // SYNC MASTER
    gsync: 'git checkout ${1:master} && git pull upstream ${1:master} && git push origin ${1:master}',

    // REBASE
    grb: 'git rebase $*',
    grbm: 'git rebase master $*',
    grbi: 'git rebase --interactive HEAD~$1',
    grbia: 'git rebase --autosquash --interactive HEAD~$1',
    grbin: 'git rebase --no-autosquash --interactive HEAD~$1',
    grbc: 'git rebase --continue',
    grba: 'git rebase --abort',
    gmt: 'git mergetool',
    gcl: 'git clean --interactive',

    // MERGE NG PR
    gngprh: 'ngm-pr-merge $* --instructions',
    gngprm: 'ngm-pr-merge $*',

    // BACKPORT
    gcp: 'git checkout $2 && ' +
         'git pull --rebase origin $2 && ' +
         'git cherry-pick $1 && ' +
         'ngm-diff-wh origin/$2 && ' +
         'git log --decorate && ' +
         'echo "----------------------------------------------------------" && ' +
         'echo ">>>  (Don\'t forget to manually push the changes.)  <<<"',
    gcpl: 'echo "  Cherry-picking SHA: ${0:`git rev-parse HEAD`}" && ' +
          'echo "----------------------------------------------------------------" && ' +
          'gcp ${0:`git rev-parse HEAD`} $1',
  },

  // Node
  node: {
    // INFO / SWITCHING
    nv: 'node --version',
    nls: 'npm list --depth=0',
    nls1: 'npm list --depth=1',
    nlsg: 'npm list --depth=0 --global',
    nlsg1: 'npm list --depth=1 --global',
    // nvu: 'FOR /F "TOKENS=1" %%i IN (\'nvm list ^| sed -n -e "s/^.*\\($1\\.[0-9]\\+\\.[0-9]\\+\\).*$/\\1/p"\') DO ' +
    //        'nvm use %%i',

    // INSTALL / UNINSTALL
    nis: 'npm install --save $*',
    nid: 'npm install --save-dev $*',
    nrms: 'npm rm --save $*',
    nrmd: 'npm rm --save-dev $*',

    // RUN / TEST
    nr: 'npm run $*',
    ns: 'npm start $*',
    nt: 'npm test $*',
    yr: 'yarn run $*',
    ys: 'yarn start $*',
    yt: 'yarn test $*',

    // SPECIAL
    niga: 'npm install --global ' + [
      'csslint',
      'eslint',
      'firebase-tools',
      'grunt-cli',
      'gulp',
      'http-server',
      'lr-http-server',
      'typescript',
      'yarn',
      '@gkalpak/aliases',
      '@gkalpak/ng-maintain',
    ].join(' '),
  },

  // Misc
  misc: {
    // DIRECTORY LISTING
    ll: 'ls -hl $*',
    lla: 'ls -ahl $*',

    // SELF-UPDATE
    salfup: `npm install --global ${name}`,

    // VERSION
    alv: {
      desc: `Display the installed version of ${name}.`,
      code: [
        '#!/usr/bin/env node',
        '\'use strict\';',
        `console.log('${VERSION_STAMP}');`,
      ].join('\n'),
    },

    // HELP
    halp: {
      desc: 'Display this message.',
      code: [
        '#!/usr/bin/env node',
        '\'use strict\';',
        'require(\'../../lib/index\').help();',
      ].join('\n'),
    },
  },
};

// Exports
module.exports = {
  ALIASES,
  BIN_DIR,
  DEF_CODE,
  VERSION_STAMP,
};
<commit_msg>style(git): improve whitespace of `gcl(l)`<commit_after>'use strict';

// Imports
const {join} = require('path');
const {name, version} = require('../package.json');

// Constants
const VERSION_STAMP = `${name} v${version}`;
const BIN_DIR = join(__dirname, '../bin');
const DEF_CODE = cmd => [
  '#!/usr/bin/env node',
  '\'use strict\';',
  '// eslint-disable-next-line max-len',
  `const cmd = module.exports = '${cmd.replace(/'/g, '\\\'')}';`,
  'if (require.main === module) {',
  '  require(\'../../lib/index\').run(cmd);',
  '}',
].join('\n');
const ALIASES = {
  // Git
  git: {
    // STATUS
    gs: 'git status',
    gl: 'git log --decorate $*',
    gl1: 'git log --decorate --oneline $*',
    gd: 'ngm-diff-wh $*',
    gdh: 'ngm-diff-wh HEAD $*',
    gd1: 'ngm-diff-wh HEAD~1 $*',

    // STASH
    gst: 'git stash $*',
    gstk: 'git stash save --keep-index $*',
    gstl: 'git stash list $*',
    gstp: 'git stash pop --index $*',

    // CHECKOUT
    gco: 'git checkout $*',
    gcom: 'git checkout master $*',
    gcopr: 'git fetch upstream pull/$1/head && git checkout FETCH_HEAD',

    // ADD / COMMIT
    gaa: 'git add --all',
    gcm: 'git commit --all $*',
    gcmf: 'git commit --all --fixup HEAD~${1:0}',
    gcma: 'git commit --all --amend $*',
    gcmane: 'git commit --all --amend --no-edit $*',

    // PUSH
    gp: 'git push --verbose $*',
    gpf: 'git push --force-with-lease --verbose $*',

    // BRANCH
    gb: 'git branch $*',
    gbc: 'git checkout master -b $1 && git push --verbose --set-upstream origin $1',
    gbd: 'git branch --delete --force $*',

    // PULL(-REBASE)
    gpr: 'git pull --rebase $*',
    gpro: 'git pull --rebase origin $*',
    gprom: 'git pull --rebase origin master $*',
    gpru: 'git pull --rebase upstream $*',
    gprum: 'git pull --rebase upstream master $*',

    // SYNC MASTER
    gsync: 'git checkout ${1:master} && git pull upstream ${1:master} && git push origin ${1:master}',

    // REBASE
    grb: 'git rebase $*',
    grbm: 'git rebase master $*',
    grbi: 'git rebase --interactive HEAD~$1',
    grbia: 'git rebase --autosquash --interactive HEAD~$1',
    grbin: 'git rebase --no-autosquash --interactive HEAD~$1',
    grbc: 'git rebase --continue',
    grba: 'git rebase --abort',
    gmt: 'git mergetool',
    gcl: 'git clean --interactive',

    // MERGE NG PR
    gngprh: 'ngm-pr-merge $* --instructions',
    gngprm: 'ngm-pr-merge $*',

    // BACKPORT
    gcp: 'git checkout $2 && ' +
         'git pull --rebase origin $2 && ' +
         'git cherry-pick $1 && ' +
         'ngm-diff-wh origin/$2 && ' +
         'git log --decorate && ' +
         'echo "                                                          " && ' +
         'echo "----------------------------------------------------------" && ' +
         'echo "  >>>  (Don\'t forget to manually push the changes.)  <<<  "',
    gcpl: 'echo "  Cherry-picking SHA: ${0:`git rev-parse HEAD`}  " && ' +
          'echo "----------------------------------------------------------------" && ' +
          'echo "                                                                " && ' +
          'gcp ${0:`git rev-parse HEAD`} $1',
  },

  // Node
  node: {
    // INFO / SWITCHING
    nv: 'node --version',
    nls: 'npm list --depth=0',
    nls1: 'npm list --depth=1',
    nlsg: 'npm list --depth=0 --global',
    nlsg1: 'npm list --depth=1 --global',
    // nvu: 'FOR /F "TOKENS=1" %%i IN (\'nvm list ^| sed -n -e "s/^.*\\($1\\.[0-9]\\+\\.[0-9]\\+\\).*$/\\1/p"\') DO ' +
    //        'nvm use %%i',

    // INSTALL / UNINSTALL
    nis: 'npm install --save $*',
    nid: 'npm install --save-dev $*',
    nrms: 'npm rm --save $*',
    nrmd: 'npm rm --save-dev $*',

    // RUN / TEST
    nr: 'npm run $*',
    ns: 'npm start $*',
    nt: 'npm test $*',
    yr: 'yarn run $*',
    ys: 'yarn start $*',
    yt: 'yarn test $*',

    // SPECIAL
    niga: 'npm install --global ' + [
      'csslint',
      'eslint',
      'firebase-tools',
      'grunt-cli',
      'gulp',
      'http-server',
      'lr-http-server',
      'typescript',
      'yarn',
      '@gkalpak/aliases',
      '@gkalpak/ng-maintain',
    ].join(' '),
  },

  // Misc
  misc: {
    // DIRECTORY LISTING
    ll: 'ls -hl $*',
    lla: 'ls -ahl $*',

    // SELF-UPDATE
    salfup: `npm install --global ${name}`,

    // VERSION
    alv: {
      desc: `Display the installed version of ${name}.`,
      code: [
        '#!/usr/bin/env node',
        '\'use strict\';',
        `console.log('${VERSION_STAMP}');`,
      ].join('\n'),
    },

    // HELP
    halp: {
      desc: 'Display this message.',
      code: [
        '#!/usr/bin/env node',
        '\'use strict\';',
        'require(\'../../lib/index\').help();',
      ].join('\n'),
    },
  },
};

// Exports
module.exports = {
  ALIASES,
  BIN_DIR,
  DEF_CODE,
  VERSION_STAMP,
};
<|endoftext|>


<commit_before>/**
 * Created by kintesh on 28/01/15.
 */
;(function(){

    /**
     * Basic constants
     * @type {string}
     */
    exports.frame_separator = "====";
    exports.math_type_inline = 0;
    exports.math_type_block = 1;
    exports.math_marker = function(number) {
        return "%{MATH"+number+"}";
    };
    exports.math_replace = "%{MATH}";

    /**
     * Regular expressions.
     */
    exports.regex_comments = /(\/\*([^*]|[\r\n]|(\*+([^\*/]|[\r\n])))*\*+\/)|((\/\/[^\n]*))/g;
    exports.regex_lines = /\r\n|\r|\n/m;
    exports.regex_properties = /([\w]+):\s*(.*)\s*/m;
    exports.regex_frame = /={4}[^=]((?:[^=\\]|\\.|={0,3}[^=])*)={4}/g;
    exports.regex_maths = /(\$(?!\$)((?:[^$\\]|\\.)*)\$(?!\$))|(\$\$((?:[^\$\\]|\\.)*)\$\$)/g;
    exports.regex_controlElemBlock = /\[\[([\w:, ]+)]]/g;
    exports.regex_controlElemProp = /\s*([\w]+)\s*:\s*([\w]+)\s*/g;
    exports.regex_controlElemClass = /class="controlElem"/g;

    /**
     * HTML Templates.
     */
    exports.temp_html = function(head, body) {
        return "<!DOCTYPE html>\n\n\n"+head+"\n\n\n"+body+"\n";
    };
    exports.temp_controlElem = function(props) {
        return "
"+props+"
";
    };
    exports.temp_slide = function(content) {
        return "
\n"+content+"\n
\n";
    };
    exports.temp_title = function(title) {
        return "
"+title+"
";
    };
    exports.temp_subTitle = function(subTitle) {
        return "
"+subTitle+"
";
    };
    exports.temp_author = function(author) {
        return "
"+author+"
";
    };
    exports.temp_date = function(date) {
        return "
"+date+"
";
    };
    exports.temp_inlineMath = "
%{MATH}
";
    exports.temp_blockMath = "
%{MATH}

";

    /**
     * Make all properties constant
     */
    (function() {
        Object.getOwnPropertyNames(exports).map(function(name) {
            var descriptor = Object.getOwnPropertyDescriptor(exports, name);
            descriptor.writable = false;
            descriptor.configurable = false;
            Object.defineProperty(exports, name, descriptor);
        });
    }).call();

})();<commit_msg>inline math fix.<commit_after>/**
 * Created by kintesh on 28/01/15.
 */
;(function(){

    /**
     * Basic constants
     * @type {string}
     */
    exports.frame_separator = "====";
    exports.math_type_inline = 0;
    exports.math_type_block = 1;
    exports.math_marker = function(number) {
        return "%{MATH"+number+"}";
    };
    exports.math_replace = "%{MATH}";

    /**
     * Regular expressions.
     */
    exports.regex_comments = /(\/\*([^*]|[\r\n]|(\*+([^\*/]|[\r\n])))*\*+\/)|((\/\/[^\n]*))/g;
    exports.regex_lines = /\r\n|\r|\n/m;
    exports.regex_properties = /([\w]+):\s*(.*)\s*/m;
    exports.regex_frame = /={4}[^=]((?:[^=\\]|\\.|={0,3}[^=])*)={4}/g;
    exports.regex_maths = /(\$(?!\$)((?:[^$\\]|\\.)*)\$(?!\$))|(\$\$((?:[^\$\\]|\\.)*)\$\$)/g;
    exports.regex_controlElemBlock = /\[\[([\w:, ]+)]]/g;
    exports.regex_controlElemProp = /\s*([\w]+)\s*:\s*([\w]+)\s*/g;
    exports.regex_controlElemClass = /class="controlElem"/g;

    /**
     * HTML Templates.
     */
    exports.temp_html = function(head, body) {
        return "<!DOCTYPE html>\n\n\n"+head+"\n\n\n"+body+"\n";
    };
    exports.temp_controlElem = function(props) {
        return "
"+props+"
";
    };
    exports.temp_slide = function(content) {
        return "
\n"+content+"\n
\n";
    };
    exports.temp_title = function(title) {
        return "
"+title+"
";
    };
    exports.temp_subTitle = function(subTitle) {
        return "
"+subTitle+"
";
    };
    exports.temp_author = function(author) {
        return "
"+author+"
";
    };
    exports.temp_date = function(date) {
        return "
"+date+"
";
    };
    exports.temp_inlineMath = "%{MATH}";
    exports.temp_blockMath = "
%{MATH}

";

    /**
     * Make all properties constant
     */
    (function() {
        Object.getOwnPropertyNames(exports).map(function(name) {
            var descriptor = Object.getOwnPropertyDescriptor(exports, name);
            descriptor.writable = false;
            descriptor.configurable = false;
            Object.defineProperty(exports, name, descriptor);
        });
    }).call();

})();<|endoftext|>


<commit_before>'use strict';

module.exports = function (app) {
    app.route('GET /hello/(<name>/)', 'hello_page');
};
<commit_msg>Add append-slash modifier to hello example route<commit_after>'use strict';

module.exports = function (app) {
    app.route('GET /hello/(<name>/) s', 'hello_page');
};
<|endoftext|>