I want to build a web based traffic simulator that uses API so users can interact with it and set the speed of vehicles, place traffic light at junctions etc… The purpose of this project is to build an app that can simulate real like traffic scenarios. So, I want the app to generate the map of the area I’m living and model the roads. I have come across SUMO and TraCI, but I am not sure how to use them to complete this project. At the moment I have little to no knowledge of coding in python and have basic to intermediate web development knowledge. But I am ready to learn and can work for 4-5 hours daily to complete this project eventhough I have to finish the project within 4-5 months(maybe 6 if I’m lucky). I would really appreciate if you could build a learning objective roadmap for me and guide me on how to complete the project. I would also appreciate any advice regarding this project idea.
Category: javascript
Category Added in a WPeMatico Campaign
popup.js can`t receive messages from background based on the action passed Chrome extension
I’m building a chrome extension that gets an auth_token from another url and stores it in chrome storage which works fine. The availability of this token is supposed to trigger a change in display of button A to button B. However, when i send a response from the background of send the token to the popup.js, i’m getting this error:
Promise[[PromiseState]]: “fulfilled”[[PromiseResult]]: Objecterror: “Unknown action”.
Below is the neccessary part :
chrome.runtime.onMessage.addListener(async function (
message,
sender,
sendResponse
) {
if (message.action == "getToken") {
try {
const response = await chrome.storage.local.get("authToken");
const storedToken = response.authToken;
console.log(storedToken);
console.log("String", JSON.stringify(storedToken));
sendResponse({ action: "getToken", token: storedToken });
console.log("executed successfully");
} catch (error) {
console.error("Error retrieving token:", error);
sendResponse({ action: "getToken", error: error.message });
}
}
});
This is the popup.js part:
document.addEventListener("DOMContentLoaded", async function () {
const signInBtn = document.getElementById("signInButton");
const startExportButton = document.getElementById("startExportButton");
const getToken = () => {
try {
const response = chrome.runtime.sendMessage({ action: "getToken" });
console.log("Retrieved response:", response);
if (response.token) {
// Update UI based on retrieved token
console.log("Retrieved token:", response?.token);
startExportButton.style.display = "block";
signInBtn.style.display = "none";
} else {
// Handle case where no token is retrieved
console.log("No token found.");
}
} catch (error) {
console.error("Error retrieving token:", error);
// Handle error here (e.g., display an error message to the user)
}
};
getToken();
signInBtn.addEventListener("click", openSignInPage);
});
Why can’t I run expo client with React native app (I used create-react-native-app)?
I did:
npm install -g create-react-native-app
create-react-native-app MyApp
cd ./MyApp
npm start
s
but there’s an error:

I did:
npm install -g create-react-native-app
create-react-native-app MyApp
cd ./MyApp
npm start
s
openfl canvas toDataUrl() return blank image
I am trying to capture a screenshot of this game but when I try it simply return a blank image.
var data = document.getElementsByTagName("canvas")[0].toDataURL('image/png');
var out = document.createElement('img');
out.id = "sc";
out.src = data;
var link = document.createElement("a");
link.download = "sc.png";
link.href = out.src;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
The image downloads perfectly fine but it is simply blank.
I have tried a number of other methods including just printing the base64 to the console with console.log(document.querySelector("#openfl-content > canvas").toDataURL("image/png").split(',')[1]); but when I put it into a decoder its blank once again.
css format input date 2403//2023 to 24/03/2023
Now I’m adjusting my css to format input date time, which now it’s in this format: 2403//2023. I want it to display like this: 24/03/2023. I’ve tried to adjust it, but it won’t let me. Right between the slash
<template>
<div class="row align-items-center g-3 mt-1">
<div class="col-md-1 col-12 text-md-end">
<label class="col-form-label">วันที่</label>
</div>
<div class="col-md-4 col-12">
<input
type="date"
id="datepicker"
class="form-control"
v-model="InputActivityCCTV.dtp_date"
@change="Change_Date()"
required
/>
</div>
</div>
</template>
<style scoped>
input[type="date"]::-webkit-datetime-edit-fields-wrapper {
background-color: black;
display: flex;
color: #fff;
padding: 0 20px 0 4px;
}
input[type="date"]::-webkit-datetime-edit-text {
background-color: gray;
}
input[type="date"]::-webkit-datetime-edit-day-field {
order: -1;
background-color: red;
}
input[type="date"]::-webkit-datetime-edit-month-field {
order: 0;
background-color: blue;
}
input[type="date"]::-webkit-datetime-edit-year-field {
order: 1;
background-color: yellow;
}
</style>
Function for finding multiple values from an array and replace data in a specific coloumn based on the matching IDs?
I have a simple function that can find a text on another sheet based on a ID column and replace the text in one specific column of this same sheet. But I would need this function to be able to get multiple values and replace them all at once after clicking a buttom. Can anyone help me please? This is the code for only one value.
function saveRecord7(){
const ss = SpreadsheetApp.getActiveSpreadsheet()
const formWS = ss.getSheetByName('Dashboard')
const dataWS = ss.getSheetByName('Static_VDatabase_UID')
const idCell = formWS.getRange('G7')
const fieldRange =["AB7"]
const clearcell = formWS.getRange('AB7')
const id = idCell.getValue()
if(id== ''){
//createNewRecord()
return
}
const cellFound = dataWS.getRange("A:A")
.createTextFinder(id)
.matchCase(true)
.matchEntireCell(true)
.findNext()
if(!cellFound) return
const row = cellFound.getRow()
const fieldValues = fieldRange.map(f => formWS.getRange(f).getValue())
fieldValues.unshift()
dataWS.getRange(row,20,1,fieldValues.length).setValues([fieldValues])
clearcell.clearContent();
}
Can’t log JSON data from nodejs + express when serving static files with express use but can see it when I call only get JSON data and not the statics
I’m trying to learn how to send data from nodejs + express server to front-end static files, where javascript (allScripts.js) will be used to process it. Currently I’m trying to at least log it to console to see if I’m correctly sending it to the front-end.
Initially I wanted to send data from sqlite database to front-end, however due to lack of knowledge I reduced it to sending a simple array of objects as JSON using nodejs and displaying it in browser console for now. Unfortunately, it’s resulting in
Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Here is the server code:
const express = require('express');
const app = express();
const PORT = 3000;
app.use(express.static('public'));
app.get('/', (req,res) => {
const users = [
{id:'123',
name:'Shaun'},
{id:'234',
name:'Bob'},
{id:'345',
name:'John'},
{id:'456',
name:'Oliver'},
]
res.json(users);
});
app.listen(PORT, () => {
console.log("Server running on port ",PORT)
});
Removing app.use, however, is allowing me to see the users table like this:
Here is the static javascript (allScripts.js) snippet to print the data:
fetch('../').then(response => response.json())
.then(users => console.log(users));
Here is the directory structure:
/ —-nodejs server file
—-public —- index.html
----style.css
----allScripts.js
I will edit the question to provide any further details if required.
Error when trying to install Nebular into my Angular App
I’m really new to angular and I’m trying to install Nebular using: ng add @nebular/theme. Unfortunately, I get an error.
After inputing the command into my terminal, I get this error:
? Which Nebular theme do you want to use: cosmic
? Use customizable scss themes? Yes
? Set up browser animations for Nebular? Yes
UPDATE package.json (1426 bytes)
✔ Packages installed successfully.
UPDATE package.json (1426 bytes)
✔ Packages installed successfully.
Could not read Angular module file: /src/null.ts
I’m confused why I’m getting an error! I created the app with ng new myapp and everything went smoothly with that. Already tried sudo, and creating a new app just in case but same error.
why am I getting error while adding sass support in rollup
I am trying to add sass support using sass plugin to my project which uses rollup but I am getting below error.
[!] RollupError: src/components/RangeInput/RangeInputStyles.scss (1:10): Expected ';', '}' or <eof> (Note that you need plugins to import files that are not JavaScript)
src/components/RangeInput/RangeInputStyles.scss (1:10)
1: $slider-bg: #cfa8f3;
^
2: $slider-color: #5d04aa;
3: $slider-height: 10px;
RollupError: Expected ';', '}' or <eof>
Here is my rollup.config.js file.
import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import typescript from "@rollup/plugin-typescript";
import dts from "rollup-plugin-dts";
import terser from "@rollup/plugin-terser";
import peerDepsExternal from "rollup-plugin-peer-deps-external";
import scss from "rollup-plugin-scss";
const packageJson = require("./package.json");
export default [
{
input: "src/index.tsx",
output: [
{
file: packageJson.main,
format: "cjs",
sourcemap: true,
},
{
file: packageJson.module,
format: "esm",
sourcemap: true,
},
],
plugins: [
peerDepsExternal(),
resolve(),
commonjs(),
typescript({ tsconfig: "./tsconfig.json" }),
terser(),
scss(),
],
external: ["react", "react-dom"],
},
{
input: "src/index.tsx",
output: [{ file: "dist/types.d.ts", format: "es" }],
plugins: [dts.default()],
},
];
And here is my package.json file.
{
"name": "smart-ui",
"version": "1.0.0",
"description": "",
"main": "dist/cjs/index.js",
"module": "dist/esm/index.js",
"types": "dist/index.d.ts",
"scripts": {
"rollup": "rollup -c --bundleConfigAsCjs",
"test": "echo "Error: no test specified" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-node-resolve": "^15.2.3",
"@rollup/plugin-terser": "^0.4.4",
"@rollup/plugin-typescript": "^11.1.6",
"@types/react": "^18.2.69",
"react": "^18.2.0",
"rollup": "^4.13.0",
"rollup-plugin-dts": "^6.1.0",
"rollup-plugin-peer-deps-external": "^2.2.4",
"rollup-plugin-postcss": "^4.0.2",
"rollup-plugin-scss": "^3.0.0",
"sass": "^1.72.0",
"tslib": "^2.6.2",
"typescript": "^5.4.3"
}
}
What am I missing here and how can I fix it?
Inserting data from an array of objects into Postgres table from Node JS
So I’ve been trying to work with this JSON data and Postgres all day and cannot figure out what I’m doing to cause this.
This is what my data set looks like, the full set is about 1000 objects:
{
avgHighPrice: null,
highPriceVolume: 0,
avgLowPrice: 1633,
lowPriceVolume: 1,
id: '267'
},
{
avgHighPrice: 3581,
highPriceVolume: 1,
avgLowPrice: 3501,
lowPriceVolume: 290,
id: '269'
},
{
avgHighPrice: 800,
highPriceVolume: 1,
avgLowPrice: null,
lowPriceVolume: 0,
id: '272'
}, ...
I am trying to add the id, avgHighPrice, avgLowPrice to the following Postgres table
CREATE TABLE ticker_summary (
id INT PRIMARY KEY references items,
open_high INT,
open_low INT,
high_price INT,
low_price INT,
high_vol INT,
low_vol INT,
last_update INT
);
I am doing this from Node using the following code
await db.query("INSERT INTO ticker_summary (id, open_high, open_low) SELECT x.id, x.avgHighPrice, x.avgLowPrice FROM json_to_recordset($1) AS x (avgHighPrice INT, highPriceVolume INT, avgLowPrice INT, lowPriceVolume INT, id INT);", [JSON.stringify(array)]);
Where array is the array of objects.
When I do this the code successfully executes but it only inserts the id values and everything else is null which I assume means it is not matching the fields with the defined names but I have no idea why.
Any ideas?
Postgres Test debug code
INSERT INTO ticker_summary (id, open_high, open_low)
SELECT x.id,
x.avgHighPrice,
x.avgLowPrice
FROM json_to_recordset('[{"avgHighPrice":153,"highPriceVolume":61308,"avgLowPrice":151,"lowPriceVolume":11252,"id":"2"},{"avgHighPrice":194920,"highPriceVolume":1,"avgLowPrice":182001,"lowPriceVolume":1,"id":"6"},{"avgHighPrice":187121,"highPriceVolume":4,"avgLowPrice":178642,"lowPriceVolume":2,"id":"10"}]')
AS x (avgHighPrice INT, highPriceVolume INT, avgLowPrice INT, lowPriceVolume INT, id INT);
I need the 3 values extracted from each object in the array and but into its own row in Postgres.
Can MathJax be imported to a JS file used by a local HTML document?
On the MathJax homepage, we find the code to import the tex-mml-chtml configuration directly into an HTML document, without any need for a server. Attempting to modify the example on jsbin below the boilerplate slightly, I separated the import statement into JS and HTML files on my local machine:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>MathJax example</title>
<script id="main"
type="module"
src="main.js">
</script>
</head>
<body>
<p>
When (a ne 0), there are two solutions to (ax^2 + bx + c = 0) and they are
[x = {-b pm sqrt{b^2-4ac} over 2a}.]
</p>
</body>
</html>
main.js
import * as jax from "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js";
I get the following errors:
and a warped output, although it does still make an attempt:
I am not sure if this outcome is because we simply cannot use MathJax in this manner (the proper manner being a call in the source HTML document, or via a server), or rather because I am missing some JS, or because I am calling the wrong configuration, etc.
If this is not possible, an explanation of why not (perhaps some CORS machinery? using JS modules incorrectly? MathJax simply not designed that way?) would be appreciated!
Web3 decentralized App Set-Up and Installation
I need a support regarding the Web3 decentralized app.I tried to install and setup to practice on Web3.
After I followed the instruction that I found online, and when I type dfx start in Visual studio, it gives me: Error: Cannot find dfx configuration file in the current working directory. Did you forget to create one?.
Is there anyone who can help with fixting error.
Note: I installed dfx in ubuntu and when I finished the configuration, it does not give a line for: info: Installed “a path location”. I could not find the reason why I don’t receive a path location.
I type dfx start in Visual studio, it gives me: Error: Cannot find dfx configuration file in the current working directory. Did you forget to create one?.
Aldo I installed dfx in ubuntu and when I finished the configuration, it does not give a line for: info:
Installed “a path location”.
I could not find the reason why I don’t receive a path location.
How Export a table with js PDF and Filter incluided
I have this users table whit a input for filter and a button for to generate PDF document.
<input type="text" id="filtrar_usuarios" onkeyup="filtrar_usuarios();">
<button onclick="javascript:generar_PDF()">PDF</button>
<div id="net_users">
<table id="users_table" >
<thead>
<tr>
<th>Nº</th>
<th>NOMBRE</th>
<th>APELLIDO</th>
<th>NOTA</th>
</tr>
</thead>
<tbody id="users">
<tr>
<td>1</td>
<td>Andrea</td>
<td>Torres</td>
<td>Habilitada</td>
</tr>
<tr>
<td>2</td>
<td>Gabriela</td>
<td>Cruz</td>
<td>Habilitada</td>
</tr>
<tr>
<td>3</td>
<td>Claudia</td>
<td>Fernández</td>
<td>Nuevo</td>
</tr>
<tr>
<td>4</td>
<td>Wendy</td>
<td>Pérez</td>
<td>Habilitada</td>
</tr>
<tr>
<td>5</td>
<td>Jose</td>
<td>Luis</td>
<td>Habilitado</td>
</tr>
</tbody>
</table>
</div>
This script is for filter the table
<script>
function filtrar_usuarios(){
var input, filter, table, tbody, tr, td, i;
input = document.getElementById("filtrar_usuarios");
filter = input.value.toUpperCase();
tbody = document.getElementById("users");
tr = tbody.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
var tds = tr[i].getElementsByTagName("td");
var flag = false;
for(var j = 0; j < tds.length; j++){
var td = tds[j];
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
flag = true;
}
}
if(flag){
tr[i].style.display = "";
}
else {
tr[i].style.display = "none";
}
}
}
</script>
And this script for to export the table at PDF using jsPDF library
<script type="text/javascript">
function generar_PDF() {
var pdf = new jsPDF('l', 'pt', 'letter');
source = $('#net_users')[0];
specialElementHandlers = {
'#bypassme': function(element, renderer) {
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 40,
width: 522
};
pdf.fromHTML(
source,
margins.left,
margins.top, {
'width': margins.width,
'elementHandlers': specialElementHandlers
},
function(dispose) {
pdf.save('net_users.pdf');
}
, margins);
}
</script>
</body>
When I apply the filter, the PDF generated display alls the table rows. That is to say, I apply the filter whit the “Habilitada” criteria, and the table display three rows, but when I generated the pdf, all the rows are in the document.
How to make for the PDF generated display the visible rows after the filter only?
Thank you.
Blocked days in date-picker based on dropdown selected
I have a list of outlets dropdown and a date-picker. My scenario is, I need to disable the days based on the outlet selected. For example, Outlet C closed on Monday, so I need to disable the day Monday in my calendar. My code doesn’t reflects any error but it does not working. Please help :/
<input type="date" name="form-field-date">
<select id="preferred-outlet">
<option value="">Choose an option</option>
<option value="Outlet A">Outlet A</option>
<option value="Outlet B">Outlet B</option>
<option value="Outlet C">Outlet C</option>
</select>
<script>
document.addEventListener("DOMContentLoaded", function() {
var outletSelect = document.getElementById('preferred-outlet');
var dateInput = document.querySelector('input[type="date"]');
// Function to disable specific days based on selected outlet
function updateDisabledDays(selectedOutlet) {
var disabledDays = [];
switch (selectedOutlet) {
case 'Outlet A':
// Open everyday
break;
case 'Outlet B':
// Open everyday
break;
case 'Outlet C':
// Close on Monday
disabledDays.push(1); // Monday
break;
default:
// Default case: outlets closed on Sunday
disabledDays.push(0); // Sunday
break;
}
// Set the min attribute of the date input to today
var dtToday = new Date();
var month = dtToday.getMonth() + 1;
var day = dtToday.getDate();
var year = dtToday.getFullYear();
if (month < 10)
month = '0' + month.toString();
if (day < 10)
day = '0' + day.toString();
var minDate = year + '-' + month + '-' + day;
dateInput.setAttribute('min', minDate);
// Initialize datepicker with disabled days
$(dateInput).datepicker({
beforeShowDay: function(date) {
if (disabledDays.includes(date.getDay())) {
return [false, ''];
}
return [true, ''];
}
});
}
// Event listener for changes in the outlet selection
outletSelect.addEventListener('change', function() {
var selectedOutlet = outletSelect.value;
console.log(selectedOutlet);
updateDisabledDays(selectedOutlet);
// Reset the date input
dateInput.value = '';
});
// Initial call to update disabled days based on the initial outlet selection
updateDisabledDays(outletSelect.value);
});
</script>```
How can I validate users with state (or nonce) when using OpenID with Steam
As I understand so far there is no way to pass a state and get it back when creating an OAuth 2.0 flow with OpenID + Steam. But in the return url I’m getting a auto-generated nonce value which is encoded and encrypted (I think). I can’t also pass a nonce value with the same param name so I wasn’t able to find a way to pass a value with auth url and get it back with return url.
But I’m also not sure about: then why do we get a auto-generated nonce back? I think there should be a way to use it and verify the session/user somehow to prevent replay attacks etc.
Here is an example response from openid after authentication in Steam:
openid.ns=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0
openid.mode=id_res
openid.op_endpoint=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Flogin
openid.claimed_id=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561199054560800
openid.identity=https%3A%2F%2Fsteamcommunity.com%2Fopenid%2Fid%2F76561199054560800
openid.return_to=https%3A%2F%2Foauthdebugger.com%2Fdebug
openid.response_nonce=2024-03-24T02%3A01%3A42Z4f5eZhfY9R8MEqGpO0Fl5vogAsw%3D
openid.assoc_handle=1234567890
openid.signed=signed%2Cop_endpoint%2Cclaimed_id%2Cidentity%2Creturn_to%2Cresponse_nonce%2Cassoc_handle
openid.sig=uM417bEOsfKgyc%2B4fKKdZsLlZyk%3D
*In the return url I have these params
So how do I handle the verification of oauth flow with these values?
I have tried to pass a state and nonce but were not able to get it back with the response.

