Test the main script that drives phantom.
Its responsibilities are:
- open a URL
- communicate through callbacks (like sendEvent and screenshot)
- handle error messages
- auto-exit if the page is not loaded correctly
330995
function startPhantom(requestListener, callback, wait, startCfg) {
    startCfg = startCfg || {};
    // If wait is specified, it calls the callback 'wait' ms after server.listening
    // Otherwise the callback is called on phantom.exit
    var server = http.createServer(requestListener).listen(0);
    server.on("listening", function () {
        var instanceId = Math.round(Math.random() * 1000) % 1000;
        var state = {
            retries: [],
            erroredPhantomInstances: 0
        };

        var stdout = ""; // stores stdout for later inspection in test cases
        var cfg = {
            maxRetries: startCfg.maxRetries || 0,
            phantomPath: "phantomjs",
            slaveURL: "http://localhost:" + server.address().port,
            pipeStdOut: false,
            phantomInstances: 1,
            args: {
                autoExitPolling: startCfg.autoExitPolling || 200
            },
            onData: function (data) {
                stdout += data.toString();
            },
            onAllPhantomsDied: startCfg.onAllPhantomsDied
        };
        cfg.onExit = wait ? (function () {}) : function (code) {
            if (cfg.maxRetries > 0) {
                // add the original onexit callback only if explicitly asked for
                var originalOnExit = phantomLauncher.createPhantomExitCb(cfg, state, instanceId).bind(phantomLauncher);
                originalOnExit(code);
            }
            callback(code, stdOutToMessages(stdout));
        };

        var phantomProcess = phantomLauncher.bootPhantom(cfg, state, instanceId);
        if (wait) {
            setTimeout(function () {
                phantomProcess.kill();
                callback(0, stdOutToMessages(stdout));
            }, wait);
        }
    });
}
1122864
function(filename, text) {
    // Rhino
    try {
      var out = new java.io.BufferedWriter(new java.io.FileWriter(filename));
      out.write(text);
      out.close();
      return;
    } catch (e) {}
    // PhantomJS, via a method injected by phantomjs-testrunner.js
    try {
      __phantom_writeFile(filename, text);
      return;
    } catch (f) {}
    // Node.js
    try {
      var fs = require('fs');
      var fd = fs.openSync(filename, 'w');
      fs.writeSync(fd, text, 0);
      fs.closeSync(fd);
      return;
    } catch (g) {}
  }
1044229
def run_script(self, filename, wdir, args, debug, post_mortem,
                   current_client, clear_variables):
        """"""
        norm = lambda text: remove_backslashes(to_text_string(text))

        # Run Cython files in a dedicated console
        is_cython = osp.splitext(filename)[1] == '.pyx'
        if is_cython:
            current_client = False

        # Select client to execute code on it
        is_new_client = False
        if current_client:
            client = self.get_current_client()
        else:
            client = self.get_client_for_file(filename)
            if client is None:
                self.create_client_for_file(filename, is_cython=is_cython)
                client = self.get_current_client()
                is_new_client = True

        if client is not None:
            # Internal kernels, use runfile
            if client.get_kernel() is not None:
                line = "%s('%s'" % ('debugfile' if debug else 'runfile',
                                    norm(filename))
                if args:
                    line += ", args='%s'" % norm(args)
                if wdir:
                    line += ", wdir='%s'" % norm(wdir)
                if post_mortem:
                    line += ", post_mortem=True"
                line += ")"
            else: # External kernels, use %run
                line = "%run "
                if debug:
                    line += "-d "
                line += "\"%s\"" % to_text_string(filename)
                if args:
                    line += " %s" % norm(args)

            try:
                if client.shellwidget._executing:
                    # Don't allow multiple executions when there's
                    # still an execution taking place
                    # Fixes issue 7293
                    pass
                elif client.shellwidget._reading:
                    client.shellwidget._append_html(
                        _("<br><b>Please exit from debugging before trying to "
                          "run a file in this console.</b>\n<hr><br>"),
                        before_prompt=True)
                    return
                elif current_client:
                    self.execute_code(line, current_client, clear_variables)
                else:
                    if is_new_client:
                        client.shellwidget.silent_execute('%clear')
                    else:
                        client.shellwidget.execute('%clear')
                    client.shellwidget.sig_prompt_ready.connect(
                            lambda: self.execute_code(line, current_client,
                                                      clear_variables))
            except AttributeError:
                pass
            self.switch_to_plugin()
        else:
            #XXX: not sure it can really happen
            QMessageBox.warning(self, _('Warning'),
                _("No IPython console is currently available to run <b>%s</b>."
                  "<br><br>Please open a new one and try again."
                  ) % osp.basename(filename), QMessageBox.Ok)
467072
def execute(self, script):
	
		
		
		try:
			conn = self.__connect()
			conn.cursor().execute(script)
			conn.commit()
		finally:
			conn.close()
415878
def run_cgi(self):
        """"""
        path = self.path
        dir, rest = self.cgi_info

        i = path.find('/', len(dir) + 1)
        while i >= 0:
            nextdir = path[:i]
            nextrest = path[i+1:]

            scriptdir = self.translate_path(nextdir)
            if os.path.isdir(scriptdir):
                dir, rest = nextdir, nextrest
                i = path.find('/', len(dir) + 1)
            else:
                break

        # find an explicit query string, if present.
        i = rest.rfind('?')
        if i >= 0:
            rest, query = rest[:i], rest[i+1:]
        else:
            query = ''

        # dissect the part after the directory name into a script name &
        # a possible additional path, to be stored in PATH_INFO.
        i = rest.find('/')
        if i >= 0:
            script, rest = rest[:i], rest[i:]
        else:
            script, rest = rest, ''

        scriptname = dir + '/' + script
        scriptfile = self.translate_path(scriptname)
        if not os.path.exists(scriptfile):
            self.send_error(404, "No such CGI script (%r)" % scriptname)
            return
        if not os.path.isfile(scriptfile):
            self.send_error(403, "CGI script is not a plain file (%r)" %
                            scriptname)
            return
        ispy = self.is_python(scriptname)
        if self.have_fork or not ispy:
            if not self.is_executable(scriptfile):
                self.send_error(403, "CGI script is not executable (%r)" %
                                scriptname)
                return

        # Reference: http://hoohoo.ncsa.uiuc.edu/cgi/env.html
        # XXX Much of the following could be prepared ahead of time!
        env = copy.deepcopy(os.environ)
        env['SERVER_SOFTWARE'] = self.version_string()
        env['SERVER_NAME'] = self.server.server_name
        env['GATEWAY_INTERFACE'] = 'CGI/1.1'
        env['SERVER_PROTOCOL'] = self.protocol_version
        env['SERVER_PORT'] = str(self.server.server_port)
        env['REQUEST_METHOD'] = self.command
        uqrest = urllib_parse.unquote(rest)
        env['PATH_INFO'] = uqrest
        env['PATH_TRANSLATED'] = self.translate_path(uqrest)
        env['SCRIPT_NAME'] = scriptname
        if query:
            env['QUERY_STRING'] = query
        env['REMOTE_ADDR'] = self.client_address[0]
        authorization = self.headers.get("authorization")
        if authorization:
            authorization = authorization.split()
            if len(authorization) == 2:
                import base64, binascii
                env['AUTH_TYPE'] = authorization[0]
                if authorization[0].lower() == "basic":
                    try:
                        authorization = authorization[1].encode('ascii')
                        if utils.PY3:
                            # In Py3.3, was:
                            authorization = base64.decodebytes(authorization).\
                                            decode('ascii')
                        else:
                            # Backport to Py2.7:
                            authorization = base64.decodestring(authorization).\
                                            decode('ascii')
                    except (binascii.Error, UnicodeError):
                        pass
                    else:
                        authorization = authorization.split(':')
                        if len(authorization) == 2:
                            env['REMOTE_USER'] = authorization[0]
        # XXX REMOTE_IDENT
        if self.headers.get('content-type') is None:
            env['CONTENT_TYPE'] = self.headers.get_content_type()
        else:
            env['CONTENT_TYPE'] = self.headers['content-type']
        length = self.headers.get('content-length')
        if length:
            env['CONTENT_LENGTH'] = length
        referer = self.headers.get('referer')
        if referer:
            env['HTTP_REFERER'] = referer
        accept = []
        for line in self.headers.getallmatchingheaders('accept'):
            if line[:1] in "\t\n\r ":
                accept.append(line.strip())
            else:
                accept = accept + line[7:].split(',')
        env['HTTP_ACCEPT'] = ','.join(accept)
        ua = self.headers.get('user-agent')
        if ua:
            env['HTTP_USER_AGENT'] = ua
        co = filter(None, self.headers.get_all('cookie', []))
        cookie_str = ', '.join(co)
        if cookie_str:
            env['HTTP_COOKIE'] = cookie_str
        # XXX Other HTTP_* headers
        # Since we're setting the env in the parent, provide empty
        # values to override previously set values
        for k in ('QUERY_STRING', 'REMOTE_HOST', 'CONTENT_LENGTH',
                  'HTTP_USER_AGENT', 'HTTP_COOKIE', 'HTTP_REFERER'):
            env.setdefault(k, "")

        self.send_response(200, "Script output follows")
        self.flush_headers()

        decoded_query = query.replace('+', ' ')

        if self.have_fork:
            # Unix -- fork as we should
            args = [script]
            if '=' not in decoded_query:
                args.append(decoded_query)
            nobody = nobody_uid()
            self.wfile.flush() # Always flush before forking
            pid = os.fork()
            if pid != 0:
                # Parent
                pid, sts = os.waitpid(pid, 0)
                # throw away additional data [see bug #427345]
                while select.select([self.rfile], [], [], 0)[0]:
                    if not self.rfile.read(1):
                        break
                if sts:
                    self.log_error("CGI script exit status %#x", sts)
                return
            # Child
            try:
                try:
                    os.setuid(nobody)
                except os.error:
                    pass
                os.dup2(self.rfile.fileno(), 0)
                os.dup2(self.wfile.fileno(), 1)
                os.execve(scriptfile, args, env)
            except:
                self.server.handle_error(self.request, self.client_address)
                os._exit(127)

        else:
            # Non-Unix -- use subprocess
            import subprocess
            cmdline = [scriptfile]
            if self.is_python(scriptfile):
                interp = sys.executable
                if interp.lower().endswith("w.exe"):
                    # On Windows, use python.exe, not pythonw.exe
                    interp = interp[:-5] + interp[-4:]
                cmdline = [interp, '-u'] + cmdline
            if '=' not in query:
                cmdline.append(query)
            self.log_message("command: %s", subprocess.list2cmdline(cmdline))
            try:
                nbytes = int(length)
            except (TypeError, ValueError):
                nbytes = 0
            p = subprocess.Popen(cmdline,
                                 stdin=subprocess.PIPE,
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 env = env
                                 )
            if self.command.lower() == "post" and nbytes > 0:
                data = self.rfile.read(nbytes)
            else:
                data = None
            # throw away additional data [see bug #427345]
            while select.select([self.rfile._sock], [], [], 0)[0]:
                if not self.rfile._sock.recv(1):
                    break
            stdout, stderr = p.communicate(data)
            self.wfile.write(stdout)
            if stderr:
                self.log_error('%s', stderr)
            p.stderr.close()
            p.stdout.close()
            status = p.returncode
            if status:
                self.log_error("CGI script exit status %#x", status)
            else:
                self.log_message("CGI script exited OK")
1030773
function(url){

                var self    = this;
                var head    = document.querySelector('head') || document.querySelector('body');
                var async   = data.sync !== true;
                var script;

                if(!head){
                    throw new Error('Ok, wait a second, you want to load a script, but you don\'t have at least a head or body tag...');
                }

                script = document.createElement('script');
                script.async = async;
                script.src = url;
                script.onerror = function onScriptError(){
                    self.trigger('error', arguments);
                    head.removeChild(script);
                };
                script.onload = function onScriptLoad(){
                    self.trigger('success', arguments);
                };

                head.appendChild(script);
            }
537962
def main(argv=None):
  
  try:
    _name_of_script, filepath = argv
  except ValueError:
    raise ValueError(argv)
  print(filepath)
  make_confidence_report_bundled(filepath=filepath,
                                 test_start=FLAGS.test_start,
                                 test_end=FLAGS.test_end,
                                 which_set=FLAGS.which_set,
                                 recipe=FLAGS.recipe,
                                 report_path=FLAGS.report_path, batch_size=FLAGS.batch_size)
561130
function manipulatePage(page) {
        if (DEBUG && !page.phantom) inspectArgs("manipulatePage: ", page);

        if (timer !== undefined) {
            clearTimeout(timer);
        }

        // Inject an external script file.
        if (option["javascript-file"]) {
            page.injectJs(option["javascript-file"]);
        }

        // Inject an in-line script from the command line.
        if (option["inject-script"]) {
            var injectScript = option["inject-script"];
            injectScript = (typeof injectScript === "function") ?
                injectScript.toString() : `function() { ${injectScript} }`;
            page.evaluateJavaScript(injectScript);
        }

        if (option.waitcapturedelay) {
            setTimeout(function () { return page }, +option.waitcapturedelay);
        } else {
            return page;
        }
    }
610592
def main(event_loop=None):
    
    context, credentials = get_context_from_cmdln(sys.argv[1:])
    log.info("Scriptworker starting up at {} UTC".format(arrow.utcnow().format()))
    cleanup(context)
    context.event_loop = event_loop or asyncio.get_event_loop()

    done = False

    async def _handle_sigterm():
        log.info("SIGTERM received; shutting down")
        nonlocal done
        done = True
        if context.running_tasks is not None:
            await context.running_tasks.cancel()

    context.event_loop.add_signal_handler(signal.SIGTERM, lambda: asyncio.ensure_future(_handle_sigterm()))

    while not done:
        try:
            context.event_loop.run_until_complete(async_main(context, credentials))
        except Exception:
            log.critical("Fatal exception", exc_info=1)
            raise
212853
function getScript(url, async, cb) {
    if (typeof async === 'function') {
      cb = async;
      async = false;
    }

    var el = document.createElement('script');

    // Script attributes
    el.type = 'text/javascript';
    el.src = url;

    // Should the script be loaded asynchronously?
    if (async)
      el.async = true;

    // Defining callbacks
    el.onload = el.onreadystatechange = function() {
      if ((!this.readyState ||
            this.readyState == 'loaded' ||
            this.readyState == 'complete')) {
        el.onload = el.onreadystatechange = null;

        // Removing element from head
        artoo.mountNode.removeChild(el);

        if (typeof cb === 'function')
          cb();
      }
    };

    // Appending the script to head
    artoo.mountNode.appendChild(el);
  }
909365
def check_alert(self, text):
    

    try:
        alert = Alert(world.browser)
        if alert.text != text:
            raise AssertionError(
                "Alert text expected to be {!r}, got {!r}.".format(
                    text, alert.text))
    except WebDriverException:
        # PhantomJS is kinda poor
        pass
30249
function crawlScript($,result, script, callback) {

    var link = $(script).attr('src');
    var parentUrl = result.url;

    if (link) {
          var linkUri = URI.linkToURI(parentUrl, link);
          pm.crawlLink(parentUrl, linkUri, null, null, function(){
            addLinkToQueue(result, parentUrl, linkUri, null, null, callback);
          });
    }
    else {
      callback();
    }


}
710130
def _run_script(self, session, file_path):
        
        if file_path:
            # The 'run' command returns False in case of error
            # The 'execute' method returns False if the run command fails
            return self._shell.execute('run "{0}"'.format(file_path), session)

        return None
808949
function createPage(casper) {
    /*jshint maxstatements:20*/
    "use strict";
    var page = require('webpage').create();
    page.onAlert = function onAlert(message) {
        casper.log('[alert] ' + message, "info", "remote");
        casper.emit('remote.alert', message);
        if (utils.isFunction(casper.options.onAlert)) {
            casper.options.onAlert.call(casper, casper, message);
        }
    };
    page.onConfirm = function onConfirm(message) {
        if ('page.confirm' in casper._filters) {
            return casper.filter('page.confirm', message);
        }
        return true;
    };
    page.onConsoleMessage = function onConsoleMessage(msg) {
        // client utils casper console message
        var consoleTest = /^\[casper\.echo\]\s?([\s\S]*)/.exec(msg);
        if (consoleTest && consoleTest.length === 2) {
            casper.echo(consoleTest[1]);
            return; // don't trigger remote.message event for these
        }
        // client utils log messages
        var logLevel = "info",
            logTest = /^\[casper:(\w+)\]\s?([\s\S]*)/m.exec(msg);
        if (logTest && logTest.length === 3) {
            logLevel = logTest[1];
            msg = logTest[2];
            casper.log(msg, logLevel, "remote");
        } else {
            casper.emit('remote.message', msg);
        }
    };

    page.onCallback = function onCallback(data){
        casper.emit('remote.callback',data);
    };

    page.onError = function onError(msg, trace) {
        casper.emit('page.error', msg, trace);
    };
    page.onInitialized = function onInitialized() {
        casper.emit('page.initialized', page);
        if (utils.isFunction(casper.options.onPageInitialized)) {
            casper.log("Post-configuring WebPage instance", "debug");
            casper.options.onPageInitialized.call(casper, page);
        }
    };
    page.onLoadStarted = function onLoadStarted() {
        // in some case, there is no navigation requested event, so
        // be sure that browserInitializing is false to not block checkStep()
        casper.browserInitializing = false;
        casper.loadInProgress = true;
        casper.emit('load.started');
    };
    page.onLoadFinished = function onLoadFinished(status) {
        /*jshint maxstatements:20*/
        if (status !== "success") {
            casper.emit('load.failed', {
                status:      status,
                http_status: casper.currentHTTPStatus,
                url:         casper.requestUrl
            });
            var message = 'Loading resource failed with status=' + status;
            if (casper.currentHTTPStatus) {
                message += f(' (HTTP %d)', casper.currentHTTPStatus);
            }
            message += ': ' + casper.requestUrl;
            casper.log(message, "warning");
            casper.navigationRequested = false;
            casper.browserInitializing = false;
            if (utils.isFunction(casper.options.onLoadError)) {
                casper.options.onLoadError.call(casper, casper, casper.requestUrl, status);
            }
        }
        // local client scripts
        casper.injectClientScripts();
        // remote client scripts
        casper.includeRemoteScripts();
        // Client-side utils injection
        casper.injectClientUtils();
        // history
        casper.history.push(casper.getCurrentUrl());
        casper.emit('load.finished', status);
        casper.loadInProgress = false;
    };
    page.onNavigationRequested = function onNavigationRequested(url, type, willNavigate, isMainFrame) {
        casper.log(f('Navigation requested: url=%s, type=%s, willNavigate=%s, isMainFrame=%s',
                     url, type, willNavigate, isMainFrame), "debug");
        casper.browserInitializing = false;
        if (isMainFrame && casper.requestUrl !== url) {
            var currentUrl = casper.requestUrl;
            var newUrl = url;
            var pos = currentUrl.indexOf('#')
            if (pos !== -1) {
                currentUrl = currentUrl.substring(0, pos);
            }
            pos = newUrl.indexOf('#')
            if (pos !== -1) {
                newUrl = newUrl.substring(0, pos);
            }
            // for URLs that are only different by their hash part
            // don't turn navigationRequested to true, because
            // there will not be loadStarted, loadFinished events
            // so it could cause issues (for exemple, checkStep that
            // do no execute the next step -> infinite loop on checkStep)
            if (currentUrl !== newUrl)
                casper.navigationRequested  = true;

            if (willNavigate) {
                casper.requestUrl = url;
            }
        }
        casper.emit('navigation.requested', url, type, willNavigate, isMainFrame);
    };
    page.onPageCreated = function onPageCreated(popupPage) {
        casper.emit('popup.created', popupPage);
        popupPage.onLoadFinished = function onLoadFinished() {
            // SlimerJS needs this line of code because of issue
            // https://github.com/laurentj/slimerjs/issues/48
            // else checkStep turns into an infinite loop
            // after clicking on an <a target="_blank">
            casper.navigationRequested  = false;
            casper.popups.push(popupPage);
            casper.emit('popup.loaded', popupPage);
        };
        popupPage.onClosing = function onClosing(closedPopup) {
            casper.popups.clean(closedPopup);
            casper.emit('popup.closed', closedPopup);
        };
    };
    page.onPrompt = function onPrompt(message, value) {
        return casper.filter('page.prompt', message, value);
    };
    page.onResourceReceived = function onResourceReceived(resource) {
        http.augmentResponse(resource);
        casper.emit('resource.received', resource);
        if (utils.isFunction(casper.options.onResourceReceived)) {
            casper.options.onResourceReceived.call(casper, casper, resource);
        }
        casper.handleReceivedResource(resource);
    };
    page.onResourceRequested = function onResourceRequested(requestData, request) {
        casper.emit('resource.requested', requestData, request);
        if (requestData.url === casper.requestUrl) {
            casper.emit('page.resource.requested', requestData, request);
        }
        if (utils.isFunction(casper.options.onResourceRequested)) {
            casper.options.onResourceRequested.call(casper, casper, requestData, request);
        }
    };
    page.onUrlChanged = function onUrlChanged(url) {
        casper.log(f('url changed to "%s"', url), "debug");
        casper.navigationRequested = false;
        casper.emit('url.changed', url);
    };
    casper.emit('page.created', page);
    return page;
}
583556
function ScriptManager() {

  // child process
  this.ps = null;

  // script execution limit in milliseconds
  this._limit = 5000;

  // flag determining if a script is busy executing
  this._busy = false;

  // flag determining if script execution issued
  // any write commands
  this._written = false;

  // currently executing script name
  this._script = null;

  // injected reference to the command handlers
  this._commands = {};

  // script limit timeout listener
  this.onTimeout = this.onTimeout.bind(this);
}
849385
def main():
    """"""
    authenticator = prawcore.TrustedAuthenticator(
        prawcore.Requestor("prawcore_script_auth_example"),
        os.environ["PRAWCORE_CLIENT_ID"],
        os.environ["PRAWCORE_CLIENT_SECRET"],
    )
    authorizer = prawcore.ScriptAuthorizer(
        authenticator,
        os.environ["PRAWCORE_USERNAME"],
        os.environ["PRAWCORE_PASSWORD"],
    )
    authorizer.refresh()

    with prawcore.session(authorizer) as session:
        data = session.request("GET", "/api/v1/me/friends")

    for friend in data["data"]["children"]:
        print(friend["name"])

    return 0
1188508
def main(argv=None):
    """"""
    global Verbose, Mock
    if argv is None:
        argv = sys.argv

    if len(argv) < 5: die('Bad args')
    try:
        opts, argv = getopt.getopt(argv[1:], 'hs:p:mv',
          ['help', 'server=', 'port=', 'mock', 'verbose'])
    except getopt.GetoptError as err:
        # print help information and exit:
        print(err) # will print something like "option -a not recognized"
        die()

    serverEndpoint = DefaultServerEndpoint
    # TODO: Fix this
    for opt, val in opts:
        if opt   in ('-h', '--help'):    echo2(USAGE); sys.exit()
        elif opt in ('-s', '--server'):  serverEndpoint = val
        elif opt in ('-p', '--port'):    serverEndpoint = 'http://localhost:%s' % val
        elif opt in ('-m', '--mock'):    Mock = 1
        elif opt in ('-v', '--verbose'): Verbose = 1
        else: die(USAGE)

    cmd = argv[0]
    crawlId = argv[1]
    confId = argv[2]
    urlDir = argv[3]
    args = {}
    if len(argv) > 4: args = eval(argv[4])

    nt = Nutch(crawlId, confId, serverEndpoint, urlDir)
    nt.Jobs().create(cmd, **args)