Abort if PhantomJS version isn't adequate.
763086
function(version) {
        var current = [version.major, version.minor, version.patch].join('.');
        var required = '>= 1.6.0';
        if (!semver.satisfies(current, required)) {
          exports.halt();
          grunt.log.writeln();
          grunt.log.errorlns(
            'In order for this task to work properly, PhantomJS version ' +
            required + ' must be installed, but version ' + current +
            ' was detected.'
          );
          grunt.warn('The correct version of PhantomJS needs to be installed.', 127);
        }
      }
624229
def check_alert(step, text):
    

    try:
        alert = Alert(world.browser)
        assert_equals(alert.text, text)
    except WebDriverException:
        # PhantomJS is kinda poor
        pass
1025214
public void abort() {
    LOG.info("Aborting session driver");
    running = false;
    cmNotifier.clearCalls();
    cmNotifier.doShutdown();
    server.stop();
    incomingCallExecutor.interrupt();
  }
1284492
function () {

      try {

        // we're creating a simple reporter to:
        // 1. track stats on the specs run
        // 2. mimic a 'finished' callback
        function FinishedReporter () {
          this.total = this.passed = this.failed = 0;
        }

        FinishedReporter.prototype = {
          reportRunnerResults: function (runner) {
            window.__runner__.failures = this.failed;
            window.__runner__.passed = (this.failed === 0);
            window.__runner__.finished = true;
          },

          reportSpecStarting: function (spec) {
            this.total++;
          },

          reportSpecResults: function(spec) {
            if (spec.results().skipped) {
              return;
            }

            spec.results().passed() ? this.passed++ : this.failed++;
          }
        };

        // this reporter is always added last
        jasmineEnv.addReporter(new FinishedReporter());

        jasmineEnv.execute();

        return true;
      }
      catch (e) {
        var out = 'Script Error in PhantomJS\n\nMessage:\n  ' + e.message +
          '\nStack:\n  ' + e.stack + '\n';

        console.log(out);

        return false;
      }
    }
677172
def skip_pickle_inject(app, what, name, obj, skip, options):
    """"""
    if name.endswith('._raw_slave'):
        return True
    return None
1105485
function phantomas(url, opts) {
	var events = new EventEmitter(),
		browser, options;

	debug('OS: %s %s', process.platform, process.arch);
	debug('Node.js: %s', process.version);
	debug('phantomas: %s', VERSION);
	debug('Puppeteer: preferred revision r%s', puppeteer._launcher._preferredRevision);
	debug('URL: <%s>', url);

	// options handling
	options = util._extend({}, opts || {}); // use util._extend to avoid #563
	options.url = options.url || url || false;

	debug('Options: %s', JSON.stringify(options));

	events.setMaxListeners(100); // MaxListenersExceededWarning: Possible EventEmitter memory leak detected.

	var results = new Results();
	results.setUrl(url);
	results.setGenerator('phantomas v' + VERSION);

	// set up and run Puppeteer
	browser = new Browser();
	browser.bind(events);

	var promise = new Promise(async (resolve, reject) => {
		try {
			if (typeof options.url !== 'string') {
				return reject(Error('URL must be a string'));
			}

			const page = await browser.init(),
				debugScope = require('debug')('phantomas:scope:log');

			// prepare a small instance object that will be passed to modules and extensions on init
			const scope = {
				getParam: (param, _default) => {
					return options[param] || _default;
				},
				getVersion: () => VERSION,

				emit: events.emit.bind(events),
				on: events.on.bind(events),
				once: events.once.bind(events),

				log: debugScope.bind(debug),

				addOffender: results.addOffender.bind(results),
				incrMetric: results.incrMetric.bind(results),
				setMetric: results.setMetric,
				addToAvgMetric: results.addToAvgMetric,

				getMetric: results.getMetric,

				// @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluatepagefunction-args
				evaluate: page.evaluate.bind(page),

				// @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageselector-1
				querySelectorAll: async (selector) => {
					debug('querySelectorAll("%s")', selector)
					return page.$$(selector);
				},

				// @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args
				injectJs: async (script) => {
					const debug = require('debug')('phantomas:injectJs'),
						preloadFile = require('fs').readFileSync(script, 'utf8');

					await page.evaluateOnNewDocument(preloadFile);

					debug(script + ' JavaScript file has been injected into page scope');
				}
			};

			// pass phantomas options to page scope
			// https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageevaluateonnewdocumentpagefunction-args
			await page.evaluateOnNewDocument(options => {
				window.__phantomas_options = options;
			}, options);

			// expose the function that will pass events from page scope code into Node.js layer
			// @see https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pageexposefunctionname-puppeteerfunction
			await page.exposeFunction('__phantomas_emit', scope.emit);

			// Inject helper code into the browser's scope
			events.on('init', () => {
				scope.injectJs(__dirname + '/../core/scope.js');
			});

			// bind to sendMsg calls from page scope code
			events.on('scopeMessage', (type, args) => {
				const debug = require('debug')('phantomas:core:scopeEvents');
				// debug(type + ' [' + args + ']');

				switch(type) {
					case 'addOffender':
					case 'incrMetric':
					case 'log':
					case 'setMetric':
						scope[type].apply(scope, args);
						break;

					default:
						debug('Unrecognized event type: ' + type);
				}
			});

			// bind to a first response
			// and reject a promise if the first response is 4xx / 5xx HTTP error
			var firstResponseReceived = false;

			events.once('recv', async entry => {
				if (!firstResponseReceived && entry.status >= 400) {
					debug('<%s> response code is HTTP %d %s', entry.url, entry.status, entry.statusText);

					// close the browser before leaving here, otherwise subsequent instances will have problems
					await browser.close();
					reject(new Error('HTTP response code from <' + entry.url + '> is ' + entry.status));
				}

				firstResponseReceived = true;
			});

			// load modules and extensions
			debug('Loading core modules...');
			loader.loadCoreModules(scope);

			debug('Loading extensions...');
			loader.loadExtensions(scope);

			debug('Loading modules...');
			loader.loadModules(scope);

			await events.emit('init', page, browser); // @desc Browser's scope and modules are set up, the page is about to be loaded

			// https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pagegotourl-options
			const waitUntil = options['wait-for-network-idle'] ? 'networkidle0' : undefined,
				timeout = options.timeout;

			await browser.visit(url, waitUntil, timeout);

			// resolve our run
			// https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#browserclose
			await events.emit('beforeClose', page); // @desc Called before the Chromium (and all of its pages) is closed
			await browser.close();

			// your last chance to add metrics
			await events.emit('report'); // @desc Called just before the phantomas results are returned to the caller

			resolve(results);
		}
		catch(ex) {
			// close the browser before leaving here, otherwise subsequent instances will have problems
			await browser.close();
			reject(ex);
		}
	});

	promise.on = events.on.bind(events);

	return promise;
}
335232
private function stopServer()
    {
        if ($this->resource !== null) {
            $this->write('Stopping PhantomJS Server.');

            // Wait till the server has been stopped.
            $max_checks = 10;
            for ($i = 0; $i < $max_checks; $i++) {
                // If we're on the last loop, and it's still not shut down, just
                // unset resource to allow the tests to finish.
                if ($i === $max_checks - 1 && proc_get_status($this->resource)['running'] === true) {
                    $this->writeln('');
                    $this->writeln('Unable to properly shutdown PhantomJS server.');
                    unset($this->resource);
                    break;
                }

                // Check if the process has stopped yet.
                if (proc_get_status($this->resource)['running'] === false) {
                    $this->writeln('');
                    $this->writeln('PhantomJS server stopped.');
                    unset($this->resource);
                    break;
                }

                foreach ($this->pipes as $pipe) {
                    if (is_resource($pipe)) {
                        fclose($pipe);
                    }
                }

                // Terminate the process.
                // Note: Use of SIGINT adds dependency on PCTNL extension so we
                // use the integer value instead.
                proc_terminate($this->resource, 2);

                $this->write('.');

                // Wait before checking again.
                sleep(1);
            }
        }
    }
886683
def process(self, item_session: ItemSession, request, response, file_writer_session):
        '''
        '''
        if response.status_code != 200:
            return

        if not HTMLReader.is_supported(request=request, response=response):
            return

        _logger.debug('Starting PhantomJS processing.')

        self._file_writer_session = file_writer_session

        # FIXME: this is a quick hack for crashes. See #137.
        attempts = int(os.environ.get('WPULL_PHANTOMJS_TRIES', 5))

        for dummy in range(attempts):
            try:
                yield from self._run_driver(item_session, request, response)
            except asyncio.TimeoutError:
                _logger.warning(_('Waiting for page load timed out.'))
                break
            except PhantomJSCrashed as error:
                _logger.exception(__('PhantomJS crashed: {}', error))
            else:
                break
        else:
            _logger.warning(__(
                _('PhantomJS failed to fetch ‘{url}’. I am sorry.'),
                url=request.url_info.url
            ))
261200
public function acceptPopup()
    {
        if ($this->isPhantom()) {
            throw new ModuleException($this, 'PhantomJS does not support working with popups');
        }
        $this->webDriver->switchTo()->alert()->accept();
    }
684983
function downloadPhantomjs() {
  var downloadSpec = getDownloadSpec()
  if (!downloadSpec) {
    console.error(
        'Unexpected platform or architecture: ' + getTargetPlatform() + '/' + getTargetArch() + '\n' +
        'It seems there is no binary available for your platform/architecture\n' +
        'Try to install PhantomJS globally')
    exit(1)
  }

  var downloadUrl = downloadSpec.url
  var downloadedFile

  return Q.fcall(function () {
    // Can't use a global version so start a download.
    var tmpPath = findSuitableTempDirectory()
    var fileName = downloadUrl.split('/').pop()
    downloadedFile = path.join(tmpPath, fileName)

    if (fs.existsSync(downloadedFile)) {
      console.log('Download already available at', downloadedFile)
      return verifyChecksum(downloadedFile, downloadSpec.checksum)
    }
    return false
  }).then(function (verified) {
    if (verified) {
      return downloadedFile
    }

    // Start the install.
    console.log('Downloading', downloadUrl)
    console.log('Saving to', downloadedFile)
    return requestBinary(getRequestOptions(), downloadedFile)
  })
}
59778
function _abort(err) {
  this._queue = null;
  this._commands = null;
  // listen for the event so we can clean reference
  function onError() {
    this._client = null;
  }
  this._client.once('error', onError.bind(this));
  this._client.emit('error', err);
}
1030381
def skip():
	""""""

	if not settings.platformCompatible():
		return False

	(output, error) = subprocess.Popen(["osascript", "-e", SKIP], stdout=subprocess.PIPE).communicate()
100689
private void abort(Error error) {
    try {
      if (mContext == null || mContext.getError() != null || mContext.isDoneUnsafe()) {
        // Note, we may reach here via events due to network errors bubbling up before
        // mContext is initialized, or stream error after the request is finished.
        return;
      }
      mContext.setError(error);
      cleanupRequest(mContext);
      replyError();
    } catch (Exception e) {
      LOG.warn("Failed to cleanup states with error {}.", e.getMessage());
    }
  }
1246718
def abort!
      console = Console.new
      console.log(messages.shift) until messages.empty?
    end
1188132
function startPhantom ( next, options ) {

    phantomProcess = spawn('node', [phantomLoc +'/phantomjs', '--webdriver=' + options.phantomPort, '--webdriver-selenium-grid-hub=http://' + options.host + ':' + options.port, '--ignore-ssl-errors=' + options.ignoreSslErrors]);
//    console.log( phantomLoc +'/phantomjs', '--webdriver=' + options.phantomPort, '--webdriver-selenium-grid-hub=http://' + options.host + ':' + options.port, '--ignore-ssl-errors=' + options.ignoreSslErrors );
    phantomProcess.stderr.setEncoding('utf8');
    phantomProcess.stderr.on('data', function(data) {
//        console.log('error',data);
        data = data.trim();
    });
    phantomProcess.stdout.setEncoding('utf8');
    // wait for client ready message before proceeding
    phantomProcess.stdout.on('data', function( msg ) {
        var error;
//        console.log('out',data);
        // look for msg that indicates it's ready and then stop logging messages
        if ( !started && msg.indexOf( 'Registered with grid' ) > -1) {
            console.log ('registered phantomjs with hub running on ' + options.host + ':' + options.port);
            started = true;
            starting = false;
            if (typeof next === 'function') {
                return next();
            }
        } else if (msg.indexOf('ERROR') > -1) {
            error = JSON.parse(msg.substring(msg.indexOf('{')));
            console.trace(error);
            process.exit(1);
        }
    });
}
405078
function findExecutable(opt_exe) {
  var exe = opt_exe || io.findInPath(PHANTOMJS_EXE, true);
  if (!exe) {
    throw Error(
        'The PhantomJS executable could not be found on the current PATH. ' +
        'Please download the latest version from ' +
        'http://phantomjs.org/download.html and ensure it can be found on ' +
        'your PATH. For more information, see ' +
        'https://github.com/ariya/phantomjs/wiki');
  }
  if (!fs.existsSync(exe)) {
    throw Error('File does not exist: ' + exe);
  }
  return exe;
}
1080883
function startPhantom (specPath, cfg, cb) {
        var args = [specPath];
        if (cfg.verbose) {
            args.push("--verbose"); // custom, to be handled by spec runner
        }
        if (cfg.debug) {
            args.push("--debug"); // custom, to be handled by spec runner
        }
        if (cfg.color) {
            args.push("--color"); // custom, to be handled by spec runner
        }
        args.push("--xunitName=" + cfg.xunitName);
        var phantomProcess = grunt.util.spawn({
            cmd : 'phantomjs',
            args : args
        }, cb);

        phantomProcess.stdout.pipe(process.stdout);
        phantomProcess.stderr.pipe(process.stderr);
        return phantomProcess;
    }