Failed to load resources status: 404 javascript with django - javascript

i am running javascript frontend with django backend.
Here is the structure
-app
--templates
---index.html
--static
---index.js
---haarcascade_frontalface_alt.xml
---style.css
--views.py
--urls.py
I can see css style in my index.html page. But the index.js file is unable to pick haarcascade_frontalface_alt.xml.
The code is as follow
const HAARCASCADE_URI = "haarcascade_frontalface_alt.xml"
this.classifier = new cv.CascadeClassifier();
let faceCascadeFile = "haarcascade_frontalface_alt.xml";
if (!this.classifier.load(faceCascadeFile)) {
await this.createFileFromUrl(faceCascadeFile, this.classifierPath);
this.classifier.load(faceCascadeFile)
}
but it say
Failed to load haarcascade_frontalface_alt.xml status: 404

Related

React Native get real path of file on Android

I'm using react-native-document-picker to select a file and react-native-fs to upload the file.
try {
const res = await DocumentPicker.pick({
type: [DocumentPicker.types.allFiles],
copyToCacheDirectory: false
});
I'm getting the uri as - content://com.android.providers.media.documents/document/image%3A24
Then I'm converting this to actual path using react-native-get-real-path.
RNGRP.getRealPathFromURI(res[0].uri)
.then(filePath =>{
realFilePath = filePath
console.log("real-path-->"+filePath)
ToastAndroid.show(filePath, ToastAndroid.SHORT);
})
The above method gives the path as /storage/emulated/0/Download/output-onlinepngtools.png but this working for few files, for others I'm getting null as the real-path.
This is the error I see while uploading the file - [Error: Socket is closed]

Trying to use AXIOS for get request, error "require is not defined" [duplicate]

This question already has answers here:
Client on Node.js: Uncaught ReferenceError: require is not defined
(11 answers)
Closed 11 months ago.
My code is below. This is my first time using NodeJS and axios.
I have installed NodeJS on Windows using the downloadable installer. I then installed Axios using npm install axios in powershell as admin.
I'm obviously copy/pasting the boilerplate nodejs code for an axios get request.
I've tested the php file using a curl get request from command line (installed actual curl, not the windows shortcut to another program.) So the PHP is accepting get requests and serving json back properly.
The issue I'm stuck on is how to setup axios and node js properly so that my js file runs the get request properly.
This is my code
const loginForm = document.getElementById("login-form");
const loginButton = document.getElementById("login-form-submit");
const loginErrorMsg = document.getElementById("login-error-msg");
const vanillaUrl = "localhost:8081/hospital/php/addapt.php";
const getUrl = "localhost:8081/hospital/php/getpatientappt.php?PatientID=1";
const axios = require('axios')
//get request to get appt for patient id1
axios
.get(geturl)
.then(res => {
console.log(`statusCode: ${res.status}`)
console.log(res)
alert(res)
})
.catch(error => {
console.error(error)
})
loginButton.addEventListener("click", (e) => {
e.preventDefault();
const username = loginForm.username.value;
const password = loginForm.password.value;
if (username === "user" && password === "1") {
alert("You logged in!");
location.reload();
} else {
loginErrorMsg.style.opacity = 1;
}
}
)
These are the errors I'm getting in chrome from the javascript console
Uncaught ReferenceError: require is not defined
at login-page.js:7:15
DevTools failed to load source map: Could not load content for chrome-extension://hnfanknocfeofbddgcijnmhnfnkdnaad/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT
DevTools failed to load source map: Could not load content for http://localhost:8081/hospital/login/requestProvider.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
When I run incognito I get
Uncaught ReferenceError: require is not defined
at login-page.js:7:15
there is no file requestProvider.js.map or content.js.map
This is all being hosted on localhost with xampp. I'm not sure if that affects anything.
I'm not sure what this error is. Got stuck googling it. And I'm not sure how to integrate this code properly.
seems like you're running this code in browser, browser implementation of Javascript doesn't have require function

Node.js 'fs' throws an ENOENT error after adding auto-generated Swagger server code

Preamble
To start off, I'm not a developer; I'm just an analyst / product owner with time on their hands. While my team's actual developers have been busy finishing off projects before year-end I've been attempting to put together a very basic API server in Node.js for something we will look at next year.
I used Swagger to build an API spec and then used the Swagger code generator to get a basic Node.js server. The full code is near the bottom of this question.
The Problem
I'm coming across an issue when writing out to a log file using the fs module. I know that the ENOENT error is usually down to just specifying a path incorrectly, but the behaviour doesn't occur when I comment out the Swagger portion of the automatically generated code. (I took the logging code directly out of another tool I built in Node.js, so I'm fairly confident in that portion at least...)
When executing npm start, a few debugging items write to the console:
"Node Server Starting......
Current Directory:/mnt/c/Users/USER/Repositories/PROJECT/api
Trying to log data now!
Mock mode: disabled
PostgreSQL Pool created successfully
Your server is listening on port 3100 (http://localhost:3100)
Swagger-ui is available on http://localhost:3100/docs"
but then fs throws an ENOENT error:
events.js:174
throw er; // Unhandled 'error' event
^
Error: ENOENT: no such file or directory, open '../logs/logEvents2021-12-24.log'
Emitted 'error' event at:
at lazyFs.open (internal/fs/streams.js:277:12)
at FSReqWrap.args [as oncomplete] (fs.js:140:20)
Investigating
Now normally, from what I understand, this would just mean I've got the paths wrong. However, the file has actually been created and the first line of the log file has been written just fine
My next thought was that I must've set the fs flags incorrectly, but it was set to 'a' for append:
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
Removing Swagger Code
Now here's the weird bit: if I remove the Swagger code, the log files write out just fine and I don't get the fs exception!
This is the specific Swagger code:
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
When I comment out this code, the log file writes out just fine.
The only thing I can think that might be happening is that somehow Swagger is modifying (?) the app's working directory so that fs no longer finds the same file?
Full Code
'use strict';
var path = require('path');
var fs = require('fs');
var http = require('http');
var oas3Tools = require('oas3-tools');
var serverPort = 3100;
// I am specifically tried using path.join that I found when investigating this issue, and referencing the app path, but to no avail
const __logdir = path.join(__dirname,'./logs');
//These are date and time functions I use to add timestamps to the logs
function dateNow(){
var dateNow = new Date().toISOString().slice(0,10).toString();
return dateNow
}
function rightNow(){
var timeNow = new Date().toTimeString().slice(0,8).toString();
return "["+timeNow+"] "
};
console.info("Node Server Starting......");
console.info("Current Directory: " + __dirname)
// Here I create the WriteStreams
var logsFile = fs.createWriteStream(__logdir+"/logEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Log File to location: %s \nWith error description: %s',__logdir, err);
});
var errorsFile = fs.createWriteStream(__logdir+"/errorEvents"+dateNow()+'.log',{flags: 'a'},(err) =>{
console.error('Could not write new Error Log File to location: %s \nWith error description: %s',__logdir, err);
});
// And create an additional console to write data out:
const Console = require('console').Console;
var logOut = new Console(logsFile,errorsFile);
console.info("Trying to log data now!") // Debugging logging
logOut.log("========== Server Startup Initiated ==========");
logOut.log(rightNow() + "Server Directory: "+ __dirname);
logOut.log(rightNow() + "Logs directory: "+__logdir);
// Here is the Swagger portion that seems to create the behaviour.
// It is unedited from the Swagger Code-Gen tool
// swaggerRouter configuration
var options = {
routing: {
controllers: path.join(__dirname, './controllers')
},
};
var expressAppConfig = oas3Tools.expressAppConfig(path.join(__dirname, '/api/openapi.yaml'), options);
var app = expressAppConfig.getApp();
// Initialize the Swagger middleware
http.createServer(app).listen(serverPort, function () {
console.info('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort);
console.info('Swagger-ui is available on http://localhost:%d/docs', serverPort);
}).on('error',console.error);
In case it helps, this is the project's file structure . I am running this project within a WSL instance in VSCode on Windows, same as I have with other projects using fs.
Is anyone able to help me understand why fs can write the first log line but then break once the Swagger code gets going? Have I done something incredibly stupid?
Appreciate the help, thanks!
Edit: Tried to fix broken images.
Found the problem with some help from a friend. The issue boiled down to a lack of understanding of how the Swagger module works in the background, so this will likely be eye-rollingly obvious to most, but keeping this post around in case anyone else comes across this down the line.
So it seems that as part of the Swagger initialisation, any scripts within the utils folder will also be executed. I would not have picked up on this if it wasn't pointed out to me that in the middle of the console output there was a reference to some PostgreSQL code, even though I had taken all reference to it out of the main index.js file.
That's when I realised that the error wasn't actually being generated from the code posted above: it was being thrown from to that folder.
So I guess the answer is don't add stuff to the utils folder, but if you do, always add a bunch of console logging...

How to load data from init-db.js in docker-compose

I am using docker to containerize a Flask API. The Flask API is accessing MongoDB using the "links" keyword in the docker-compose.yml file shown below:
app:
build: .
command: python -u app.py
ports:
- "5000:5000"
volumes:
- .:/app
#Linking db.
links:
- db
db:
image: mongo:latest
hostname: test_mongodb
environment:
- MONGO_INITDB_DATABASE=Exploit_Resources
- MONGO_INITDB_ROOT_USERNAME=root
- MONGO_INITDB_ROOT_PASSWORD=pass
# Data provider.
volumes:
- ./init-db.js:/docker-entrypoint-initdb.d/init-db.js:ro
ports:
- 27017:27017
The link is working fine, and the file given under volumes (init-db.js) is supposed to provide the Mongo container with data. Here is my init-db.js file:
db = db.getSiblingDB("Exploit_Resources");
db.EDB.drop();
db.EDB.insertMany([
// Insert data here.
]);
The data I want to provide MongoDB comes from a remote csv file. I tried using PapaParse to access and feed the data, but I was having some difficulties importing it.
I tried this code inside the insertMany method:
const {StringStream} = require("scramjet");
const request = require("request");
request.get("https://srv.example.com/main.csv") // fetch csv
.pipe(new StringStream()) // pass to stream
.CSVParse() // parse into objects
.consume(object => console.log("Row:", object)) // do whatever you like with the objects
.then(() => console.log("all done"))
I got the code from here. It did not work because a ReferenceError was thrown, saying that 'require' is not defined.
Is there a way to fix this code or another way to get data from a remote csv file and provide it to the MongoDB container from the init-db.js?

error: (-215) !empty() in function detectMultiScale in Opencv.JS

I have checked and tried these solutions here but none is helping
error: (-215) !empty() in function detectMultiScale
OpenCV.js - detectMultiScale "This Exception cannot be caught"
I also read elsewhere that the problem could be because the file needs to be served via an Http request and so I decided to use ngrok but I still found the same error. Currently am using python http.server
Here is the section of the code:
let classifier = new cv.CascadeClassifier();
let utils = new Utils('errorMessage'); //use utils class
let faceCascadeFile = "http://localhost:8000/docs/haarcascade_frontalface_default.xml";
//let faceCascadeFile = "D:\Code\Fit-to-Interact-web\docs\haarcascade_frontalface_default.xml"
//let faceCascadeFile = "https://0979da552cb5.ngrok.io/docs/haarcascade_frontalface_default.xml"; // path to xml
// use createFileFromUrl to "pre-build" the xml
//Make sure to run it in a webserver because it has to do XMLHTTPRequests.
utils.createFileFromUrl(faceCascadeFile, faceCascadeFile, () => {
classifier.load(faceCascadeFile); // in the callback, load the cascade from file
});
console.log(classifier.empty())
Worse when I use the absolute/relative file path I get this error Not allowed to load local resource or sometimes the same error:
Exception: OpenCV(4.4.0) /build/master-contrib_docs-lin64/opencv/modules/objdetect/src/cascadedetect.cpp:1689:
error: (-215:Assertion failed) !empty() in function 'detectMultiScale'

Categories

Resources