I was solving a problem in leet code, Solution I came up with made all test cases passed except for one. Input of that test case is an array = [6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]. so I have convert the array into a number add 1 to entire number and then convert it back to array format with result, in my solution one step before final statement, I have used parseInt(“6145390195186705543”)+1 then I convert to string and split and then convert to number.
but during parseInt(), this in-built method is not able to convert after 15th digits, im getting output as [6145390195186705000], sending 0’s after 15 digits, so does anyone has any idea on how to convert a string of number length more than 16 to Number
P.S: I have tried bigInt() method, techincally it would work but for the problem bigInt() is not working and output isnt working
Category: javascript
Category Added in a WPeMatico Campaign
How to display instagram photos on my website?
How I can display Instagram posts on my website without WordPress an standard Instagram embed ?
I am stuck how to make my autogenerated code display inside an input field and increase by 1 on page load…any help please
My code generates a random last digit code when executed. When I want it to give a specific code.
$(document).ready(function() {
function invoiceid() {
var d = new Date().getTime();
var uuid = 'GA00444x'.replace(/[xy]/g, function(c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
};
function shortInvoiceId() {
return invoiceid().substr(0, 18);
}
$('#invoiceid').on('load', function() {
$('#uuid').html(shortInvoiceId());
});
$('#uuid').html(shortInvoiceId());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="uuid"></div>
Tooltip in rc-slider
I need to add a Tooltip to the slider
In React
I try to add according to the site but without success.
I use this package
https://slider-react-component.vercel.app/
const Slider = require('rc-slider');
const createSliderWithTooltip = Slider.createSliderWithTooltip;
const Range = createSliderWithTooltip(Slider.Range);
Anyone know a way to do this?
emit function from client side to all room only once, socket.io
I am a newbie with socket.io and I have a hard time figuring out how to correctly use server and client. So, I have a function on my client side that listens to the server to get an array of questions.
The idea is to create a room with several clients connected, and to emit to one room a function from the client side (only once, as I want to display the information to all the room). I really need this function on my client side as I have approximately 100 lines of code that concerns the front. Also my server needs to emit its array to the client.
My problem is, since it is client side, when I emit it to the server it will be emitted x times the number of clients inside the room. And I wish to emit it only once.
To have a concrete example : My server has an object of array which is passed to the clients in a room so they can display it. Here is the function in the client :
//I have shorten the function so it is not too much but you can still grasp how I need it in my client
socket.on('getNewQuestion', (currentQuestion) => {
init();
questionNumber.innerHTML = "Question " + countQuestion;
questionParams.id = currentQuestion.questionId;
questionParams.questionTxt = currentQuestion.question;
questionParams.reponse = JSON.parse(currentQuestion.reponse);
questionParams.lien = currentQuestion.lien;
questionParams.type = currentQuestion.type;
//Display question text
questionTxt.innerHTML = currentQuestion.question;
//Display different informations according to the question's type
switch (currentQuestion.type) {
case "enigme":
var getReponseLength = JSON.parse(currentQuestion.reponse)[0].length;
questionType.innerHTML = "find the answer to this question with " + getReponseLength + " letters";
break;
case "anagramme":
questionType.innerHTML = "find a word usign all these letters :";
const html = [];
//Parse string to create array of chars
var questionParse = JSON.parse(currentQuestion.question);
//Gets the characters of the string and shuffles it
for (let i = questionParse.length - 1; i >= 0; i--) {
const randLetters = Math.floor(Math.random() * (i + 1));
[questionParse[i], questionParse[randLetters]] = [questionParse[randLetters], questionParse[i]];
html.push(`<div>${questionParse[i]}</div>`);//display letter
}
currentQuestion.question = questionParse;
questionTxt.innerHTML = html.join(" ");
break;
}
countQuestion++;
});
Then I emit it in my server to get the object of question
socket.on('callGetNewQuestion', (roomCode) => {
//Get a random question from the object
const questionCalled = questions.getQuestionsList(roomCode)[Math.floor(Math.random() * questions.getQuestionsList(roomCode).length)];
io.in(roomCode).emit('getNewQuestion', questionCalled); //emit the random question to the client
questions.removeQuestion(questionCalled.questionId); //remove it so it doesn't appear twice
});
And I am emitting back in my client (which I am not sure if it is good practice but I don’t have any idea on how to listen to the object otherwise)
socket.on('startGame', () => {
socket.emit('callGetNewQuestion', userParams.roomCode);
timerCountdownGame();
});
The problem with this code is : as it is called from the client side, if there is two clients in the room it is called twice, if there are three clients, it is called three times, so when I start the game it will pass from question 1 to question 3 (if number of clients is three).
I hope what I am saying makes sense, if not do not hesitate to tell me
Does anyone know how I can correct it ?
Query to do indepth search for a regex is not working properly
I’m having one query to do indepth search for a regex in mongoDB. I’m using JS function inside the query like this –
db.collection.find(
{$where: function() {
function deepIterate(obj, value) {
var new_value = new RegExp("^"+value, "i");
for (var field in obj) {
if (obj[field] == new_value){
return true;
}
var found = false;
if ( typeof obj[field] === 'object' ) {
found = deepIterate(obj[field], new_value)
if (found) { return true; }
}
}
return false;
};
return deepIterate(this, "[A-Ba-b0-9]*60.51[A-Ba-b0-9]*")
}}
)
It doesn’t return any values, output is Fetched 0 record(s) in 4ms. But I’m having one string in my database – 192.108.60.51. That record is not getting returned.
Help!!!
React map method return currentElement.name where name inside another array
Hi i just want to render a table where name column name and its value dynmamically fetch from an api ..
and I store column value in an new array ;
I want to return rows value that link with column name in a row
const element = [ "ENDURANCE", "SPEED", "AGILITY", "STRENGTH" ] // this is my column name
api data of rows value
[{
AGILITY: 1
ENDURANCE: 1
SPEED: 1
STRENGTH: 1
_id: "62c53266b631f27c54db8d89"
date: "7/6/2022"
},
{
AGILITY: "4"
ENDURANCE: "4"
SPEED: "6"
STRENGTH: "2"
_id: "62c5a047a053c4ebb5de8c10"
date: "7/6/2022"
},
{
AGILITY: "8"
ENDURANCE: "6"
SPEED: "5"
STRENGTH: "10"
_id: "62c5a053a053c4ebb5de8c14"
date: "7/6/2022"
}]
I just map this value in table dynamically
this is my code ….
<table className="table">
<thead>
<tr>
<th>/</th>
<th>Date</th>
{props.data.map((cur, i) => {
element.push(cur[0]) //store all column names
return <th key={i}>{cur[0]}</th>;
})}
</tr>
</thead>
<tbody>
{props.stdata.map((curr, index) => {
console.log(element);
return (
<>
<tr>
<td>{index+1}</td>
<td>
{curr.date} // date element is same in every api data
</td>
<td>{
curr[element] // may be this is wrong
}</td>
</tr>
</>
);
})}
</tbody>
</table>
Prevent document save button from being triggered after webpage refresh
I am quite new to React and facing the following challenge.
Current state: I have a react application which upon pressing page refresh or back button, triggers an uploaded document to be saved even before I click on the Save document button.
Expected: What I want is to press upload button, document uploads, ‘Save document’ button appears, then press refresh or back button, page refreshes but does not save the document.
I’m new to debugging using DevTools but I have an idea after following this tutorial. Also read through these issues
- Detect Back/Next/Refresh BUTTON click on Chrome
- How to use event listener on chrome dev tool for page load
Using Event Listener Breakpoints, I’ve selected Mouse -> click and Load -> load but this hasn’t helped me identify why this is happening.
How can I fix this?
Browser version: Chrome Version 101.0.4951.54 (Official Build) (64-bit)
OS: Windows 10 Enterprise
chart.js (3.8.0) line chart not showing
I’m trying to add a chart to my website to show the prices of cryptocurrencies, which the user selects, by taking them from an endpoint on my website. After taking the data from the endpoint I add it to the array with the graph data via a push and then I update the graph with the update function, all performed within a setInterval every 5 seconds. Even if inside the arrays I find both the data and the labels that I insert, the graph is not shown.
The part of the code shown is inside a PHP file.
Where am I doing wrong?
<div>
<canvas class="realTimeGraph" id="realTimeGraph"></canvas>
</div>
<script type="text/javascript">
var ctx = document.getElementById("realTimeGraph").getContext('2d');
const BaseUrl = "http://localhost:3000/CryptoSite/php/dbEndpoint.php?crypto="
let chartCryptoData = [];
let data = {
labels: [],
dataset: [{
label: "Crypto price",
data: [],
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
}]
};
const config = {
type: 'line',
data : data,
options : {}
};
function getPriceData__(url, callback)
{
const xhttp = new XMLHttpRequest();
xhttp.open("GET", url, true);
xhttp.responseType = 'json';
xhttp.send();
xhttp.onload = () => {
var status = xhttp.status;
if (status === 200) {
callback(null, xhttp.response);
} else {
callback(status, xhttp.response);
}
};
}
async function getPriceData() {
let cryptoForGraph = "<?php echo $_SESSION['cryptoForGraph']?>";
let url = BaseUrl + cryptoForGraph
await getPriceData__(url,
function (err, data) {
if (err !== null) {
console.log('Something went wrong: ' + err);
}
chartCryptoData.push({
x: data['timestamp'],
y: data['price']
});
});
}
function setLabels(labels, timestamp) {
labels.push(timestamp);
labels.shift();
}
function setData(data, price) {
data.push(price);
data.shift();
}
document.getElementById("showCryptoGraph").onclick = () => {
console.log("button press");
var myLineChart = new Chart(ctx, config);
setInterval( () => {
getPriceData();
let currentData = chartCryptoData.pop();
if(currentData !== undefined)
{
setData(config.dataset[0].data, currentData.y);
setLabels(config.labels, currentData.x);
myLineChart.update();
console.log("end intervall");
}
}, 5000);
};
</script>
How to use custom blocks in image movement in blockly
I’m trying to make block programming modules on one of my pages in blockly, but it doesn’t work for me. I managed to make custom blocks, but I need to somehow move the figure forward with the block or turn left or right. I tried using css animation or simply changing the position normally, but it doesn’t work for me. Could someone give me some advice on how to do it in blockly, there aren’t many tutorials on the internet, thank you in advance.
HTML Code:
<script src="{{ url_for('static', filename='js/blockly/customblocks.js') }}"></script>
<div class="row">
<div id="blocklyDiv" class="main blockly-panel" style="height: 500px; width: 700px;"></div>
<div id="visualization" class="main output-panel" style="height: 500px; width: 700px;">
<img class="cat" src="static/images/blockly/Blockly_img_test.png" width="105px" height="119,5px">
</div>
</div>
<div onclick="executeBlockCode()" id="playButton" class="play-button-blockly3 material-icons"><i
class="bi bi-play-fill"> Run</i></div>
<xml id="toolbox" style="display: none">
<block type="move_forward"></block>
<block type="turn_right_left"></block>
</xml>
<script>
var workspace = Blockly.inject('blocklyDiv',
{
toolbox: document.getElementById('toolbox'),
zoom: {
controls: true,
}
});
Blockly.Xml.domToWorkspace(document.getElementById('startBlocks'), workspace);
function executeBlockCode() {
window.LoopTrap = 10;
Blockly.JavaScript.INFINITE_LOOP_TRAP =
'if (--window.LoopTrap == 0) throw "Infinite loop.";n';
var code = Blockly.JavaScript.workspaceToCode(workspace);
Blockly.JavaScript.INFINITE_LOOP_TRAP = null;
try {
eval(code);
} catch (e) {
alert(e);
}
}
Customblocks.js code:
Blockly.Blocks['move_forward'] = {
init: function () {
this.appendDummyInput()
.appendField("move forward");
this.setInputsInline(false);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setColour(210);
}
};
Blockly.Blocks['turn_right_left'] = {
init: function () {
this.appendDummyInput()
.appendField("turn")
.appendField(new Blockly.FieldDropdown([["left", "L"], ["right", "R"]]), "position");
this.setInputsInline(false);
this.setPreviousStatement(true, null);
this.setNextStatement(true, null);
this.setColour(330);
}
};
Blockly.JavaScript['turn_right_left'] = function (block) {
var dropdown_position = block.getFieldValue('position');
var cat = document.getElementsByClassName("cat")[0];
if (dropdown_position == 'L') {
} else if (dropdown_position == 'R') {
}
return code;
};
Blockly.JavaScript['move_forward'] = function (block) {
var cat = document.getElementById("cat");;
var code = cat.style.transitionProperty = "width";
var code = cat.style.transitionDuration = "1000ms";
return code;
};
export bunch of QR Code From a Table to a single Document file like “PDF Or Word” React js
look at the code below:
import QRCode from "react-qr-code";
return (
<div className="container">
<table
className="table table-bordered mt-3 table-hover text-center "
id="collapse1"
>
<thead>
<tr>
<th scope="col">#</th>
</tr>
</thead>
<tbody>
{unScannedProduction.map((x) => (
<tr key={x.ProductionWorksheetId}>
<th scope="row">
<QRCode
value={x.ProductionWorksheetId}
}
/>
</th>
</tr>
))}
</tbody>
</table>
</div>
);
as you can see I render a table with the QR Code where I get its’s value from a map method and here is the result :
now i want to have a “button” that download all this Generated QR Code From the Table To A single File like PDF OR Word
Detect calling multi requests at same time to server
I have a problem about Http requests: I want to detect calling multi requests (to same url) at same time to prevent from calling it.
For example, I have a bug code – a infinite loop (client-side). This code is calling so many requests at same time to server. I want to prevent that.
I don’t know that someone has resolved this problem yet.
Someone can give me some ideas or algorithms for this problem.
Thanks a lot!
Map Method not returning data on Nextjs
I’m trying to do a simple Map Method, the data 1,2,3,4,5 can be successfully shown in console.log, but not showing on the website.
import React from 'react'
export default function secretStashScreen() {
const numbers = [1, 2, 3, 4, 5];
return (
<div>
{numbers.map((number)=>{<div>{number}</div>})
}
</div>
)
}
Warning code after compiled:
warn - Fast Refresh had to perform a full reload. Read more: https://nextjs.org/d
Error: Aborted because ./pages/secret-stash.js is not accepted
Update propagation: ./pages/secret-stash.js -> ./node_modules/next/dist/build/webp at applyHandler (http://localhost:3000/_next/static/chunks/webpack.js?ts=16572
at http://localhost:3000/_next/static/chunks/webpack.js?ts=1657263030521:564:2
at Array.map (<anonymous>)
Is there anything I did wrong?
How to use BigCommerce utils.api.productAttributes.optionChange
How to use utils.api.productAttributes.optionChange on a React functional component and also when you don’t have access to $form.serialize()
I tried to manually create a formData like this but it does not work.
const addOption = () => {
const formData = new FormData();
formData.append("action", "add");
formData.append("product_id", "459");
formData.append("optionValue", "12213");
formData.append("attribute", "25331");
console.log(formData);
utils.api.productAttributes.optionChange(
459,
formData,
(err, response) => {
const attributesData = response.data || {};
console.log("err: ", err);
console.log("res: ", response);
// I just copied this from the documentation but where do I get these methods?
this.updateProductAttributes(attributesData);
this.updateView(attributesData);
}
);
};
Create React App ERROR : export ‘Header’ (imported as ‘Header’) was not found in ‘react’
I was downloading the chatbot web application code from [GitHub][1] and practicing it.
When I execute this project using npm start command in terminal, follow errors occured.
[enter image description here][1]
How can I fix this error? Please help me 🙁
The codes below are the files where the error occurred.
App.js
# App.js
import {
BrowserRouter as Router,
Switch,
Route,
} from "react-router-dom";
import React from 'react';
import ChatPageRobot from "./ChatPageRobot";
import ChatPageGlobal from "./ChatPageGlobal";
import Home from "./Home"
import Authed from './Authed'
import Unauthed from './Unauthed'
import Login from "./Login";
import Logout from "./Logout";
import Page404 from "./Page404";
import Signup from "./Signup"
import Profile from './Profile'
function App() {
return (
<Router basename={process.env.PUBLIC_URL}>
<Switch>
<Unauthed path="/login" exact component={Login}/>
<Unauthed path="/signup" exact component={Signup}/>
<Authed path="/" exact component={Home}/>
<Authed path="/profile" exact component={Profile}/>
<Authed path="/gpt" exact component={ChatPageRobot}/>
<Authed path="/global" exact component={ChatPageGlobal}/>
<Authed path="/logout" exact component={Logout}/>
<Route component={Page404}/>
</Switch>
</Router>
);
}
export default App;
Authed.js
# Authed.js
import { Redirect, Route } from 'react-router-dom';
import { Header, Shell, Footer } from 'react';
import { isLoggedIn, isLoggedJWTPoll } from './SessionLogic'
export default function Authed ({component: Component, hasFooterHeader, ...rest}) {
const authed = isLoggedIn();
let page = null;
if (hasFooterHeader) {
page = (
<div>
<Header />
<Shell>
<Component {...rest} />
</Shell>
<Footer />
</div>
);
} else {
page = <Component {...rest} />;
}
return (
<Route
{...rest}
render={(props) => authed === true
? page
: (isLoggedJWTPoll()
? page
: <Redirect to={{pathname: '/login', state: {from: props.location}}} />)}
/>
)
}
Unauthed.js
# Unauthed.js
import {Redirect, Route} from 'react-router-dom';
import {Header, Shell, Footer} from 'react';
import { isLoggedIn } from './SessionLogic'
function Unauthed ({component: Component, hasFooterHeader, ...rest}) {
const authed = isLoggedIn();
let page = null;
if (hasFooterHeader) {
page = (
<div>
<Header />
<Shell>
<Component {...rest} />
</Shell>
<Footer />
</div>
);
} else {
page = <Component {...rest} />;
}
return (
<Route
{...rest}
render={(props) => authed === false
? page
: <Redirect to={{pathname: '/', state: {from: props.location}}} />}
/>
)
}
export default Unauthed;

