Flask SocketIO Not Emitting Real-Time Updates from Nmap Scan

I’m working on a Flask web application that is supposed to run an Nmap scan and provide real-time updates to the client via Flask-SocketIO. However, I’m encountering an issue where the Nmap scan doesn’t seem to be executing, and no real-time data is being sent to the client. The Flask server doesn’t show any errors, and the WebSocket connection appears to be established correctly, but the start_nmap_scan event doesn’t seem to trigger the Nmap scan.

Here’s my Flask app setup (app.py):

from flask import Flask, render_template
from flask_socketio import SocketIO
import subprocess
import threading

app = Flask(__name__)
socketio = SocketIO(app)

@app.route('/')
def index():
    return render_template('index.html')

def run_nmap_realtime(url):
    def emit_output(proc):
        for line in iter(proc.stdout.readline, b''):
            socketio.emit('nmap_output', {'data': line.decode()})

    proc = subprocess.Popen(["nmap", "-sC", "-sV", url], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    threading.Thread(target=emit_output, args=(proc,)).start()

@socketio.on('start_nmap_scan')
def handle_nmap_scan(json):
    run_nmap_realtime(json['url'])

if __name__ == '__main__':
    socketio.run(app, debug=True)

And here’s my JavaScript (scripts.js):

var socket = io.connect('http://' + document.domain + ':' + location.port);

socket.on('connect', function() {
    console.log('WebSocket connected!');
});

function performSearch() {
    var url = document.getElementById('url-input').value;
    socket.emit('start_nmap_scan', {url: url});
}

socket.on('nmap_output', function(msg) {
    document.querySelector('.recons-box').innerText += msg.data;
});

// Code to handle content change omitted for brevity

I’ve confirmed that the WebSocket connection is established, but when I click the “Search” button to start the Nmap scan, nothing happens. No data is emitted back to the client, and there are no errors in the Flask log.

I can only make it work if I don’t use WebSocket in general, but the output from Nmap shows up after the scan is complete which is not ideal.

Appium inspector error Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 70

I am trying to connect my real device with apppium inspector. I am using following capabilities
{
“platformName”: “iOS”,
“appium:automationName”: “XCUITest”,
“appium:platformVersion”: “16.7”,
“appium:udid”: “”,
“appium:noReset”: true,
“appium:deviceName”: “Admin’s iPhone”,
“appium:app”: “/Users/admin/Downloads/app.ipa”,

}
appium inspector shows error “Failed to create session. An unknown server-side error occurred while processing the command. Original error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 70. This usually indicates an issue with the local Xcode setup or WebDriverAgent project configuration or the driver-to-platform version mismatch. ”
And on appium logs I can see error Closing the connection
[DevCon Factory] Cached connections count: 0
[XCUITestDriver@adb6 (5da55870)] Not clearing log files. Use clearSystemFiles capability to turn on.
[iProxy@63340fb9:8100] The connection has been closed
[AppiumDriver@38cd] Event 'newSessionStarted' logged at 1706311999116 (04:33:19 GMT+0500 (Pakistan Standard Time))
[AppiumDriver@38cd] Encountered internal error running command: Error: Unable to launch WebDriverAgent because of xcodebuild failure: xcodebuild failed with code 70. This usually indicates an issue with the local Xcode setup or WebDriverAgent project configuration or the driver-to-platform version mismatch. Consider setting 'showXcodeLog' capability to true in order to check the Appium server log for build-related error messages.. Make sure you follow the tutorial at https://github.com/appium/appium-xcuitest-driver/blob/master/docs/real-device-config.md. Try to remove the WebDriverAgentRunner application from the device if it is installed and reboot the device.
[AppiumDriver@38cd] at quitAndUninstall (/Users/admin/node_modules/appium-xcuitest-driver/lib/driver.js:794:15)
[AppiumDriver@38cd] at /Users/admin/node_modules/appium-xcuitest-driver/lib/driver.js:880:13
[AppiumDriver@38cd] at wrapped (/Users/admin/node_modules/appium-xcuitest-driver/node_modules/asyncbox/lib/asyncbox.js:93:13)
[AppiumDriver@38cd] at retry (/Users/admin/node_modules/appium-xcuitest-driver/node_modules/asyncbox/lib/asyncbox.js:66:13)
[AppiumDriver@38cd] at retryInterval (/Users/admin/node_modules/appium-xcuitest-driver/node_modules/asyncbox/lib/asyncbox.js:103:10)
[AppiumDriver@38cd] at /Users/admin/node_modules/appium-xcuitest-driver/lib/driver.js:819:7
[HTTP] <-- POST /session 500 34035 ms - 1812

Including Bootstrap script

So, i have a page with a Bootstrap navbar included using PHP function

include_once('navbar.php');

and on that I have included already the Bootstrap CSS file but i need also to add the script for using dropdown menu. I tried to put it at the end of the body section but (I guess) because of some PHP in the middle of the page when I try to insert this code before PHP section:

<div class="container">
    <div class="row">
        <div class="col"></div>
    </div>
</div>

I cannot see anymore the PHP generation. Is there any idea of why this happens? I cannot find the correlation between this two things … .

I tried to put the script in the nevbar file, but It didn’t worked, I tried to put it at the beginning of the body section, after PHP includes but It didn’t worked. I am curious to see the reason of this problem … .

How to create a React UI library where, when installed, let programmers launch it with a terminal command (npm script), similar to Storybook

I’m creating a UI project, similtar to Storybook. After npm install, run “npm run PROJECT_NAME -p 5000” to launch the UI on port 5000. I need guidance on this functionality. How can I research it? Thank you!

I attempted to create a .bin/script_file to expose the run command (similar to the Storybook command), but it proved unsuccessful.

How to add style to a parent div only if it’s child div content is empty?

How can I add CSS style using Jquery, to a parent div only if the parent’s child div content is empty?

Example:

 <div class="parentDivClass">
    <div class="theContent">          
        <div class="subContent"></div>
    </div>
</div>
<div class="parentDivClass">
    <div class="theContent">          
        <div class="subContent">some text</div>
    </div>
</div>
<div class="parentDivClass">
    <div class="theContent">          
        <div class="subContent"></div>
    </div>
</div>

So if there is no text inside a subContent class, then I want to add padding-bottom: 20px to parentDivClass. If there is text inside subContent, then no CSS to be added on parentDivClass.

I approached it like this but for some reason it is not adding style to parentDivClass if subContent has no text:

if( $('.subContent').is(':empty') )
{
    $('.parentDivClass').css({'padding-bottom': '20px'});
}

Is my logic going wrong some where?

Extra lines in plotlyjs Plot Bug

basically I’m creating a plot using plotlyjs so that i can use it in a react app, but for some reason when I visualize the lines on my plot i can see an extra line that doesn’t correspond to any data that line appears for every line on my plot, apart from that when i hover on them they don’t show any value

enter image description here

the extra lines are the straight ones, there’s one that got created with the red one and one created with the blue one (the line at the top of the plot), does anyone know why I’m getting this behaviour?

this is my plot definition:

          const data2 = [
            {
              type: "scatter",
              mode: "lines",
              x: outflowSensitivityCurveXValues.flat(),
              y: outflowSensitivityCurveYValues.flat(),
              line: {
                color: "00008b",
              },
              name: "Outflow Sensitivity Curve",
            },
            {
              type: "scatter",
              mode: "lines",
              x: iprSensitivityCurveXValues.flat(),
              y: iprSensitivityCurveYValues.flat(),
              line: {
                color: "red",
              },
              name: "IPR Sensitivity Curve",
            },
          ];

          const layout2 = {
            autosize: true,
            barmode: "stack",
            hovermode: "closest",
            legend: {
              orientation: "h",
              x: 0.3,
              xanchor: "center",
              y: -0.2,
            },
            title: "Pressure Vs. Production [Prediction]",
            xaxis: {
              title: "Liquid Rate (m3/day)",
              side: "bottom",
              autorange: true,
              linewidth: 1.5,
              rangemode: "nonnegative",
              showgrid: false,
              showline: true,
              tickformat: "f",
              ticks: "outside",
              titlefont: {
                size: 12,
              },
              zeroline: false,
              zerolinewidth: 2,
            },
            yaxis: {
              title: "Pressure (Kpag)",
              linewidth: 1.5,
              rangemode: "nonnegative",
              showgrid: true,
              showline: true,
              side: "left",
              tickformat: "f",
              ticks: "outside",
              titlefont: {
                size: 12,
              },
              zeroline: false,
              zerolinewidth: 2,
            },
          };

How can I make a web app that can be compiled and launched from desktop without having an external server

I am starting to develop an application. It is only needed on one computer and hosting the application on AWS or similar isn’t an option for numerous reasons.

What I want to do ideally is make the project like I normally would but make it a compiled app that can be launched which spins up the web stuff in the background on the client’s computer, so effectively the client is hosting the web app themselves, but without them having to use a development server. Is this possible at all?

I am mainly a Java developer and use Angular for frontend work normally, although I am willing to learn something new if that is the better option. I have never attempted something like this before, all my previous projects have just been hosted on cloud services, so if I am going about this all wrong, please tell me.

I have looked into making a native desktop app instead, but all the frameworks for Java that I keep coming across look very dated, and I like the flexibility the JS gives me.

Integrate Chrome Extension with Twilio API

I would like to know if there is a way of using twilio message API from a chrome extension. I think it is not posible because I imagine that I would need to download some sort of Twilio library and I haven’t found any CND on internet.
What I think I could do is to send a request from my extension to a hosted page and then send from there a request for the Twilio API, is that the only solution to do this?

VueJS application is not rendering

I’m new to VueJS. I have initial files i.e. index.html and index.js(I should not add more files).

index.html:

<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Password strength indicator</title>
    <link rel='stylesheet' href='css/all.css'>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>
<div id="app" class="container">
       <h1>Vue Password Strength Indicator</h1>
       <label class="frmLabel" for="password">Password</label>
       <input placeholder="Enter your password" name="password" class="frmField" 
        type="password" @input="" v-model="password" />
        <p class="frmValidation" :class="{'frmValidation--passed' : message.length > 
         7}">
        <i class="frmIcon fas" :class="message.length > 7 ? 'fa-check' : 'fa-times'"> 
        </i>
        Longer than 7 characters
        </p>
        <p class="frmValidation" :class="{'frmValidation--passed' :has_uppercase }">
        <i class="frmIcon fas" :class="has_uppercase ? 'fa-check' : 'fa-times'"></i>
        Has a capital letter
        </p>
        <p class="frmValidation" :class="{'frmValidation--passed' :has_lowercase }">
        <i class="frmIcon fas" :class="has_lowercase ? 'fa-check' : 'fa-times'"></i>
        Has a lowercase letter
        </p>
        <p class="frmValidation" :class="{'frmValidation--passed' : has_number }">
        <i class="frmIcon fas" :class="has_number ? 'fa-check' : 'fa-times'"></i>
        Has a number
        </p>
        <p class="frmValidation" :class="{'frmValidation--passed' : has_special }">
        <i class="frmIcon fas" :class="has_special ? 'fa-check' : 'fa-times'"></i>
        Has a special character
        </p>
        </div><!-- #app  -->
        <script type="module" src="index.js"></script>
    </body>
</html>

index.js:

import { createApp } from 'vue'

const app = createApp({
   data() {
     return {
     password: '',
    };
   },
  computed: {
    message() {
      return this.password.length > 7;
    },
    has_uppercase() {
      return /[A-Z]/.test(this.password);
    },
    has_lowercase() {
      return /[a-z]/.test(this.password);
    },
    has_number() {
      return /d/.test(this.password);
    },
    has_special() {
      return /[!@#$%^&*(),.?":{}|<>]/.test(this.password);
    }
  },
});

app.mount('#app')

The problem is that, the content of the application is not rendering i.e. the content of <div id="app"></div>.

I have following warnings in console:

[Vue warn]: Component provided template option but runtime compilation is not supported in this build of Vue. Configure your bundler to alias “vue” to “vue/dist/vue.esm-bundler.js”.
at

and

Feature flags VUE_OPTIONS_API, VUE_PROD_DEVTOOLS, VUE_PROD_HYDRATION_MISMATCH_DETAILS are not explicitly defined. You are running the esm-bundler build of Vue, which expects these compile-time feature flags to be globally injected via the bundler config in order to get better tree-shaking in the production bundle

Como solucionar un error de modulo no encontrada? [closed]

Luego de la instalación de la dependencia “npm install -g bitcore-node” requiero con el siguiente scrip “bitcore-node create mynode” crear un nodo para poder inicializar el desarrollo https://github.com/Open-Food-Chain/insight-ui-bgc.git al correr este script por consola resulta el siguiente error.

enter image description here

Probe soucionarlo mediante la desinstalación e instalacion de la dependencia y seguia arrojando el mismo error

How to pre-select dropdowns with a subset array of objects but have a superset array of object options

I have a subset list of chosen operations, currentOps. i have another superset list of all operations, jsonOperations, that contains all chosen operations. i want to display each item in currentOps as pre-selected in its own dropdown, but the user can change each value of currentOps to any item from jsonOperations using each dropdowns’ lists.

My attempt so far:

<template>
  <div  :key="componentKey">
    <tbody>
      <tr v-for="(currentOp, index) in currentOps" :key="currentOp">
        <td>
          <b-form-select name="status" class="fields-dropdown" v-model="currentOps[index]"> 
            <option v-for="(jsonOperation, optionIndex) in jsonOperations" :key="optionIndex" :value="jsonOperation">
                {{ jsonOperation.name }}: {{ jsonOperation.type }} - {{ jsonOperation.active ? 'active' : 'inactive' }}
            </option>
          </b-form-select>
        </td>
      </tr>
    </tbody>
  </div>
</template>
<script>
data() {
    return {
      componentKey: 0,

      bCard: {
        title: "Form Operations",
        subTitle: ""
      },

      jsonOperations: [],

      formOp: {},
      deleteOpId: -1,

      currentOps: [],
      opSteps: 0,
    }
  },
</script>

currentOps array of objects, followed by an object item in jsonOperations array:
structure

What it looks like right now:
what it looks like right now

What I want it to look like upon loading page:
What I want it to look like upon loading page

Any help would be appreciated. Thank you

Cannot read properties of undefined (reading ‘use’). I Defined the app

Uncaught TypeError TypeError: Cannot read properties of undefined (reading 'use')
    at <anonymous> (e:Responsive_WebPageserverindex.js:22:4)
    at run (internal/modules/esm/module_job:218:25)
    --- await ---
    at runMainESM (internal/modules/run_main:105:21)
    at executeUserEntryPoint (internal/modules/run_main:138:5)
    at <anonymous> (internal/main/run_main_module:28:49)

this is the code :

import express from "express";
import bodyParser from "body-parser";
import mongoose from "mongoose";
import cors from "cors";
import dotenv from "dotenv";
import multer from "multer";
import helmet from "helmet";
import morgan from "morgan";
import path from "path";  
import { fileURLToPath } from "url"; 

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
dotenv.config();
const app = express();
app.use(express.json()).
app.use(helmet());
app.use(helmet.crossOriginResourcePolicy({policy:"cross-origin"}));
app.use(morgan("common"));
app.use(bodyParser.json({limit: "30mb", extended : true}));
app.use(bodyParser.urlencoded({limit:"30mb", extended:true}));
app.use(cors()) //Cross Orign Resource Policies. 
app.use("/assets", express.static(path.join(__dirname, 'public/assets')));

How to use jest.advanceTimersByTime()

I’m trying to use jest fake timers to test my stopwatch timer but it’s not returning the correct result.

    it('Stop button should show 1 second on timer after waiting', async() => {
        const {queryByTestId} = render(<App></App>);
        const startButton = queryByTestId("start-button");
        fireEvent.click(startButton);
        act(()=>{
            jest.advanceTimersByTime(1000);    
        })
        const stopButton = screen.queryByTestId("stop-button");
        fireEvent.click(stopButton);
        expect(queryByTestId('stopwatch-time').textContent).toContain("0:00:01:00");
    });

This is the useState which I am trying to test:

    useEffect(()=>{
        let interval: ReturnType<typeof setTimeout>;
        if (start) {
            //Increments stopwatch
            interval = setInterval(()=> setTime(time+1), 10);
        }
        return () => clearInterval(interval);
    }, [start, time]);

Anyone know what I’m doing wrong? I put jest.useFakeTimers(); at the start of the test page.

Here is the test result:

  ● Stopwatch Tests › Stop button should show 1 second on timer after waiting                                                                                                                                   
                                                                                                                                                                                                                
    expect(received).toContain(expected) // indexOf

    Expected substring: "0:00:01:00"
    Received string:    "0:00:00:01"

Thanks!

Error when deploying express socket.io to server

I am having trouble deploying a web game to a server. I have a node.js server and vanilla javascript client which are communicating with socket.io and express. I’ll paste the key bits of code below.

My problem is:

  • It works fine when testing on my laptop. I open up index.html, which loads server.js, which immediately connects to localhost:8080. Meanwhile I have node ./server.js running in Terminal, where I see all the correct console logs. The game plays as intended.
  • When I go to deploy it on the server, I have problems. I’m pretty sure that the destinations are correct, as the server displays error messages when I navigate to the client HTML. It is obvious that the client is sending something to the server, but for whatever reason it isn’t getting through. When I run the server with NODE_DEBUG=cluser,net,http,fs,tlk,module,timers nodemon server.js I get the errors shown below.

The ‘HPE_INVALID_METHOD’ error seems pretty vague. I have tried googling it with no luck. I would be happy even for any tips on how to better dig in to exactly what is going wrong / how to get better debug messages.

Thanks in advance. 🙂

// Client side
let SERVER = window.location.origin;
if (SERVER == "file://") {
    // developing locally
    SERVER = "http://localhost:8080";
} else {
    // deployed
    SERVER = // server address
}
var connectionOptions =  {
        "force new connection" : true,
        "reconnectionAttempts": "Infinity", //avoid having user reconnect manually in order to prevent dead clients after a server restart
        "timeout" : 10000, //before connect_error and connect_timeout are emitted.
        "transports" : ["websocket"]
    };
let SOCKET = io(SERVER,connectionOptions);
// Server Side
const http = require("http");
const express = require("express");
const app = express();
const socketIo = require("socket.io");
const fs = require("fs");
const os = require("os");
const server = http.Server(app).listen(8080);
const io = socketIo(server);
io.on("connection", function(socket) {
  // do stuff
}

And here are the errors I see in the server terminal:

NET 3337164: onconnection
NET 3337164: _read
NET 3337164: Socket._handle.readStart
HTTP 3337164: SERVER new http connection
HTTP 3337164: SERVER socketOnParserExecute NaN
HTTP 3337164: parse error [Error: Parse Error: Invalid method encountered] {
  bytesParsed: 0,
  code: 'HPE_INVALID_METHOD',
  reason: 'Invalid method encountered',
  rawPacket: <Buffer 16 03 01 02 00 01 00 01 fc 03 03 30 52 c2 a5 c7 4b 37 8d 09 f6 0f 56 9c 52 58 d7 d1 57 04 09 ed 1f 25 9d f7 f6 b7 dd 37 a9 c5 40 20 e8 04 2e 17 b8 92 ... 467 more bytes>
}
NET 3337164: destroy
NET 3337164: close
NET 3337164: close handle
NET 3337164: has server
NET 3337164: SERVER _emitCloseIfDrained
NET 3337164: SERVER handle? true   connections? 1
NET 3337164: emit close
HTTP 3337164: server socket close
NET 3337164: _onTimeout
NET 3337164: destroy
NET 3337164: close
NET 3337164: close handle
NET 3337164: has server
NET 3337164: SERVER _emitCloseIfDrained
NET 3337164: SERVER handle? true   connections? 0
NET 3337164: emit close
HTTP 3337164: server socket close

and the error in the browser inspect:

socket.io.js:1562 WebSocket connection to 'wss://<address>/socket.io/?EIO=4&transport=websocket' failed: 

Why Does Using a Variable for the Index Work in This Selection Sort Algorithm in JavaScript?

I’m trying to understand why using a variable to assign the index works fine, instead of directly using the index itself in the following code snippet of the selection sort algorithm using JavaScript.

What I Tried:
I attempted to use the index of the minimum element directly (j):

let myArray = [7, 9, 4, 16, 2, 0, 4, -18];

function selectionSortAlgorithm(anArray) {
    for (let i = 0; i < anArray.length - 1; i++) {
        let min = anArray[i];

        for (let j = i + 1; j < anArray.length; j++) {
            if (min > anArray[j]) {
                min = anArray[j];
            }
        }
        let temp = anArray[i];
        anArray[i] = min;
        anArray[j] = temp;
    }
    return anArray;
}

console.log(selectionSortAlgorithm(myArray));

The Correct Code:
I found that using a new variable for the minimum element (minIndex) corrects the issue:

let myArray = [7, 9, 4, 16, 2, 0, 4, -18];

function selectionSortAlgorithm(anArray) {
    for (let i = 0; i < anArray.length - 1; i++) {
        let min = anArray[i];
        let minIndex = i;

        for (let j = i + 1; j < anArray.length; j++) {
            if (min > anArray[j]) {
                min = anArray[j];
                minIndex = j;
            }
        }
        let temp = anArray[i];
        anArray[i] = min;
        anArray[minIndex] = temp;
    }
    return anArray;
}

console.log(selectionSortAlgorithm(myArray));