I want to know if there is a way to send a dynamique table in HTML using JS to python.
I want to send the table to PostgreSQL but my application use python
Category: javascript
Category Added in a WPeMatico Campaign
What is the React way of adding a child element?
I have the below code:
<TreeView
aria-label="controlled"
defaultCollapseIcon={<ExpandMoreIcon />}
defaultExpandIcon={<ChevronLeftIcon />}
expanded={expanded}
selected={selected}
onNodeToggle={handleToggle}
onNodeSelect={handleSelect}
multiSelect
>
{
rows.data.map((item: IPTreeModel)=> {
return (
<TreeItem nodeId={item.id} label={item.subnet} onClick={item.has_child ? (e: MouseEvent)=> loadChildren(e, item.subnet) : ()=> ''}>
{/*here*/}
</TreeItem>
)
})
}
</TreeView>
And below is my function:
const loadChildren = (e: MouseEvent, id: number | string) => {
// fetch new data based on the ID parameter, and append the output as a TreeItem element.
}
Now I need to append a new <TreeItem> element to the last <TreeItem> in case user clicks on loadChildren function.
How is the react way of doing this?
How to scroll up a specific div element with Jquery?
I have a problem when I scroll up (else part of code).
Scroll first goes to the top of the page and then returns to the element. It should only go to the element .showPoints.
Where am I wrong in code?
if (value == "Show more") {
showPoints.show("slow");
showText.text("Show less");
setTimeout(() => {
$('html,body').animate({scrollTop: showText.offset().top - $(window).height() + showText.parent().height()}, 'fast');
}, 1000)
} else {
let count = 0
$("html, body").animate({ scrollTop: 0 }, "slow");
showPoints.slice(3).hide("slow");
$('html,body').animate({scrollTop: showText.offset().top}, 0, () => {
$('html,body').animate({scrollTop: showText.offset().top - $(window).height() + showText.parent().height()}, 0);
})
showText.text("Show more");
}
Node JS with Express API returning null instead undefined in array items
I have an API endpoint in my Node JS express app as below:
app.get('/src/static', (req, res) => {
res.send({ hello: [1, undefined, 2, 3] });
});
Which is returning the response as below when I call that endpoint:
{"hello":[1,null,2,3]}
In the response above, It should return the undefined in the array. but, It is returning the null.
Additional details:
Node JS: 14
"express": "^4.17.1"
What could be the problem?
How can I connect Firebase document with Firebase storage?
I m new with Firebase and i want to ask can I connect firebase document with firebase storage ?
I have a “place” collection and inside is documents with cities (street, post code, city). In input page I would also add more input field where i will add image and excel file for every city.
For example, If I add new documents (Miami and London), I want to add a image of Miami and excel file.
I want save two examples in firebase storage like this:
- “city/” + “Miami/” + excelFile and Image of Miami
- “city/” + “London/” + excelFile and Image of London
In my app, in google maps, when i click on “Miami” pin I display all data from Miami documents but how can I connect Miami folder (with image and excel file) in firebase storage with miami documents in Firestore databases ?
chart.js is not rendering after updating to 3.x version on wix velo
I am using this example of using chart.js npm with Wix Velo. When updating chart.js from 2.9.3 version to 3.x the custom element (the chart.js chart) is not rendering.
Any suggestions?
Thanks
How can i calculate the space between the start of my table header until the end dynamically?
I have the following table with thead and tbody
<table>
<thead>
<tr>
<td class="red">
col 1
</td>
<td class="red">
col 2
</td>
</tr>
</thead>
<tbody>
<tr>
<td style="width: 300px" class="blue">
John
</td>
<td style="width: 200px" class="blue">
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
<tr>
<td>
John
</td>
<td>
Peter
</td>
</tr> <tr>
<td>
John
</td>
<td>
Peter
</td>
</tr>
</tbody>
</table>
CSS
table {
border: 1px solid black;
height: 150px !important;
overflow: scroll;
display: block;
width: 400px;
}
td {
width: 150px;
}
.red {
border: 1px solid red !important;
}
.blue {
border: 1px solid blue;
}
JS
let table = document.querySelector('table');
table.addEventListener('scroll', (event) => {
console.log(event.target.scrollTop)
})
my table needs to be scrollable and the thead and tbody needs to be together in the same table. I am using such a table where for lazy loading, and everything works fine without the table header. When i incldue my table header my scrolling gets mixed up because than the scrollbar does not start from the beggining of the tbody but from the thead. I need to exclude somehow the scrolling from the thead or to calculate the difference between that start of the thead and it’s end so i will know the difference and i will adjust the scrollPosition bacis on that.
So if i know that that the difference is 50px and on scroll event i am getting 200px i will add 50px.
How can i do this ?
Can a URL have two question marks?
I am working on the site and I have a situation that I need to have two question marks in the URL.
For example, I have a URL which was initially abc.com/login?next=/product/abc&[email protected] and after successful login user was redirecting to next part i.e. abc.com/product/abc&[email protected] but this was giving error.
So I’d tried to write question mark instead of & so my URL becomes abc.com/login?next=/product/[email protected] after successful login which is working fine on Localhost but my question is that is it valid to have two question marks in the URL.?
Reactjs (Functional Component) Conditional Rending with OR statement
const App = () =>{
const condition1 = true
const condition2 = false
return (
<div>
{condition1 || condition2 && <h1>condition met</h1>}
</div>
)
}
The code above only cares about condition2, condition1 is ignored.
is there a way I can use the OR operator in my jsx?
Also I’ve tried looking through this https://reactjs.org/docs/conditional-rendering.html and I can’t find what I’m looking for.
discord bot на node js, когда пользователь пишет !профиль, при любом сетевом статусе пишет не в сети
discord bot на node js, человек пишет !профиль, и выводиться информация про его профиль, но при проверке сетового статуса, бот при любом сетевом статусе пишет не в сети
client.on('message', message =>{
if (message.author.bot) return;
if (message.content == '!профиль') {
let embed = new Discord.MessageEmbed()
.setTitle(message.author.username)
let status = ''
switch (message.author.presence.status) {
case 'online':
status = 'онлайн'; break;
case 'idle':
status = ':orange_circle:нет на месте'; break;
case 'offline':
status = 'нет в сети'; break;
case 'dnd':
status = ':red_circle:не беспокоить'; break;
}
embed.setDescription(`**Ваш дискорд айди: ${message.author.id}
Ваш статус: ${status}
Дата создания аккаунта: ${message.author.createdAt.toLocaleDateString()}
Дата входа на сервер: ${message.member.joinedAt.toLocaleDateString()}
**`)
.setColor('RANDOM')
.setThumbnail(message.author.avatarURL())
message.channel.send(embed)
}
})
How to create table with dynamically rows and columns with number in React-JS
let arr=[]
for(let i=2;i<=10;i=i+2){
arr[i]=[]
for(let j=1;j<=20;j=j+2){
arr[i][j]=i*j;
}
console.log(`n`);
}
console.table(arr);
https://stackoverflow.com/questions/ask#
**This Code Correct in JavaScript, But No Idea in React-JS
enter code here
is it possible to change the axios adapter
I am using axios "axios": "^0.25.0", in the google chrome exstension(manifest V3), because using fetch we should implement the interceptor by yourself. Now show when I run a post in google chrome extension shows this error message:
TypeError: adapter is not a function
at dispatchRequest (background.js:836:10)
at Axios.request (background.js:599:15)
at Axios.post (background.js:634:17)
at Function.wrap [as post] (background.js:1276:15)
at do_post (background.js:2418:50)
at handleTransImpl (background.js:2370:72)
at handleMessage (background.js:2551:94)
at background.js:2546:5
I searching from internet that found the axios using XHLHTTPRequest by defualt. Is it possible to make it using fetch by default. what should I do to make the axios support the google chrome extension?
Angular Filtering Multiple Unordered Words
In my code, I am trying to filter elements from a list and I’m trying to filter that element when I write multiple words at once. Right now, I can filter the element if I write the words in their correct order. For example; I can filter 'red book love' element if I write 'red book' but I also want to filter it when I write 'red love'. Here is my code, what should I do to achieve what I want?
HTML:
<mat-form-field appearance="outline" fxFlex="100" class="w-100-p pr-8">
<mat-label>Product</mat-label>
<input type="text" required matInput [(ngModel)]="product" name="product"
(input)="onProductSearchChange($event.target.value)" [matAutocomplete]="autoProductId">
<button mat-button matSuffix mat-icon-button aria-label="Clear" (click)="product = null" type="button">
<mat-icon>block</mat-icon>
</button>
<mat-autocomplete autoActiveFirstOption #autoProductId="matAutocomplete"
[displayWith]="displayProduct.bind(this)" (optionSelected)="filterProduct($event.option.value)">
<mat-option *ngFor="let prm of productList" [value]="prm">
{{prm?.StockIntegrationCode +' '+ prm?.ProductName}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
TS:
onProductSearchChange(search: string) {
let filterValue = (search as any).toLocaleLowerCase("tr");
if (
this._adminService.products &&
this._adminService.products.length > 0
) {
this.productList = this._adminService.products.filter(
(x) =>
x.StockIntegrationCode.indexOf(filterValue) >= 0 ||
(x.ProductName as any)
.toLocaleLowerCase("tr")
.indexOf(filterValue) >= 0
);
}
if (!search) {
this.product = null;
this.productList = this._adminService.products;
}
}
displayProduct(product: IProduct): string | undefined {
return product
? product.StockIntegrationCode + " - " + product.ProductName
: "";
}
Error on sendMail no refresh token is set
On hitting send on webpage of a react contact form, mail doesn’t send and the error No refresh token is set is returned in the terminal
require ('dotenv').config();
const express = require("express")
const app = express()
const cors = require("cors")
const nodemailer = require('nodemailer');
const { google } = require('googleapis');
const CLIENT_ID = process.env.CLIENT_ID
const CLIENT_SECRET = process.env.CLIENT_SECRET
const REDIRECT_URI = process.env.REDIRECT_URI
const REFRESH_TOKEN = process.env.REFRESH_TOKEN
const oAuth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });
// the below code didn't fix problem, hence commented
// oAuth2Client.refreshAccessToken(function(err, tokens){
// console.log(tokens)
// oAuth2Client.credentials = {access_token : tokens.access_token}
// callback(oAuth2Client);
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
app.use(cors())
app.get('/', cors(), async (req, res) =>{
res.send("this is working")
})
app.post("/send_mail", cors(), async (req, res) => {
res.send('ok')
const output = `
<p>You have a new contact request</p>
<h3>Contact Details</h3>
<ul>
<li>Name: ${req.body.name}</li>
<li>Email: ${req.body.email}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
async function sendMail() {
try {
const accessToken = await oAuth2Client.getAccessToken();
const transport = nodemailer.createTransport({
service: 'gmail',
auth: {
type: 'OAuth2',
user: process.env.USERNAME,
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
refreshToken: REFRESH_TOKEN,
accessToken: accessToken
},
});
const mailOptions = {
from: '"Web name" <[email protected]>',
to: '[email protected]',
subject: 'Hello from gmail using API',
text: 'Hello from gmail email using API',
html: output
};
const result = await transport.sendMail(mailOptions);
return result;
} catch (error) {
return error;
}
}
sendMail()
.then((result) => console.log('Email sent...', result))
.catch((error) => console.log(error.message));
})
app.listen(7000, () => console.log('Server started...'));
Email sent... Error: No refresh token is set.
[0] at OAuth2Client.getAccessTokenAsync (D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapinode_modulesgoogle-auth-librarybuildsrcauthoauth2client.js:214:23)
[0] at OAuth2Client.getAccessToken (D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapinode_modulesgoogle-auth-librarybuildsrcauthoauth2client.js:207:25)
[0] at sendMail (D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapiserver.js:52:44)
[0] at D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapiserver.js:82:1
[0] at Layer.handle [as handle_request] (D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapinode_modulesexpresslibrouterlayer.js:95:5)
[0] at next (D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapinode_modulesexpresslibrouterroute.js:137:13)
[0] at cors (D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapinode_modulescorslibindex.js:188:7)
[0] at D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapinode_modulescorslibindex.js:224:17
[0] at originCallback (D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapinode_modulescorslibindex.js:214:15)
[0] at D:UsersUser NameDocumentswebdev 1. PROJECTSxxxapinode_modulescorslibindex.js:219:13
Reduce array based on common values on object level
I have an array such as
let array = [
{
id: 1,
name: "Name A",
expenseAmount: 100
},
{
id: 1,
name: "Name A",
expenseAmount: 50
},
{
id: 3,
name: "Name B",
expenseAmount: 10
},
{
id: 3,
name: "Name B",
expenseAmount: 20
}
];
And I am looking for a solution, which condenses that array in such a manner, that all objects with the same id and name get summed by their expenseAmount, so that it results in:
let array_goal = [
{
id: 1,
name: "Name A",
expenseAmount: 150
},
{
id: 3,
name: "Name B",
expenseAmount: 30
}
];
Could you please help? Thanks!