I am making a webpage where you need to input data and it gets stored in a database on the webpage host (replit). can i get help on how to store html javascript variables in some database which wont get deleted once i close my browser
Category: javascript
Category Added in a WPeMatico Campaign
Test the lifecycle methods of a connected component + ReactJs + Jest
I am trying to test the componentWillRecieveProps of a connected component. Since I can’t shallow render the component as it needs to be wrapped in a Provider, I am updating the props by setProps method of the child component.
setProps() usually will call the component lifecycle methods but since the testing here is on the child component, setProps() is not re rendering the wrapper and thus I am unable to test componentWillRecieveProps with new Props.
Any suggestions to test the connected component lifecycle methods?
test('calls componentWillReceiveProps', () => {
const willReceiveProps = jest.fn();
const props = {
title: "Order",
history,
ordersStatus: true,
status: 'loaded',
dispatch: jest.fn()
}
const newProps = {
...props,
status: 'failed'
}
wrapper = mount(<Provider store={store}><MyComponent {...props} /></Provider>)
wrapper.setProps({ children: <MyComponent {...newProps} /> });
// New props are updated from above, expect componentWillReceiveProps to be called here
OrderpickupDashboard.prototype.componentWillReceiveProps = willReceiveProps;
wrapper.update();
expect(willReceiveProps).toBeTruthy();
// expect(willReceiveProps).toBeCalled();
// This statement isn't working as the lifecycle method isn't called, how can we make the
test call componentWillReceiveProps
});
How to run more than one Pomodoro timer in one page built in JavaScript?
I am new to web development. What I am trying to do is run more than one Pomodoro timer built with JavaScript in parallel. The problem is when I click on the second start button the first timer stops working.
The goal is each timer should work separately and should show different times when I press the start button.
Sorry for bad css style it is not responsive!
Can anyone help me to find the solution?
const p_Tag = document.querySelectorAll('.text');
p_Tag.forEach(a => {
if (a.textContent === "Next Correction") {
a.parentNode.classList.add("isTimer")
}
})
const getTimerContainer = document.querySelectorAll(".item");
let hasclass = false;
getTimerContainer.forEach(check => {
if (check.classList.contains('isTimer')) {
hasclass = true;
const timerContainer = document.createElement("div");
timerContainer.classList.add("timer");
check.append(timerContainer)
}
});
if (hasclass === true) {
let id = 0;
const timer = document.querySelectorAll(".timer");
let settedTime = '02:⏰';
const place = "beforeend";
timer.forEach(t => {
const timerElm = `
<figure class="clock">
<div class="numberContainer">
<p class="mins" id="hr${id}">00</p>
<p>:</p>
<p class="secs" id="min${id}">00</p>
<br>
<p class="settedTime">${settedTime}</p>
</div>
<audio
src="bell.mp3"
></audio>
<svg class="progress-ring" height="200" width="200">
<circle
class="progress-ring__circle2"
stroke-width="10"
fill="transparent"
r="80"
cx="100"
cy="100"
/>
<circle
class="progress-ring__circle"
stroke-width="15"
fill="transparent"
r="80"
cx="100"
cy="100"
id="${id}"
/>
</svg>
</figure>
<div class="btn-group">
<button class="start" id="s${id}">Start</button>
<button class="reset" id="r${id}">Reset</button>
<button class="halt" id="h${id}">Pause</button>
</div>
</div>
`;
t.insertAdjacentHTML(place, timerElm);
id++
})
};
const bell = document.querySelectorAll("audio");
const minutes = document.querySelectorAll(".mins");
const secondes = document.querySelectorAll(".secs");
const startBtn = document.querySelectorAll(".start");
const pauseBtn = document.querySelectorAll(".halt");
const clockframe = document.querySelectorAll(".progress-ring__circle2");
let initial, totalsecs, perc, paused, mins, seconds;
const circleUp = document.querySelectorAll(".progress-ring__circle")
const circle = document.querySelector(".progress-ring__circle");
const radius = circle.r.baseVal.value;
const circumference = radius * 2 * Math.PI;
let idOfSec = null;
let idOfStartBtn=0;
function setId(t){
t.forEach(tId=>{tId.addEventListener("click",(e)=>{
const item= e.target;
const isId = parseInt(item.id.split("").pop())
idOfStartBtn = isId
})
})
}
const dasharray = circle.style.strokeDasharray = circumference;
const dashoffset= circle.style.strokeDashoffset = circumference;
//console.log("this is the dasharray: ", dasharray);
//console.log("this is the dashoffset: ", dashoffset);
function setProgress(percent) {
const offset = circumference - (percent / 100) * circumference;
//console.log("this is the offset ", offset)
//circleUp.forEach(offset1 => offset1.style.strokeDashoffset= offset)
circle.style.strokeDashoffset = offset ;
}
document.getElementById("s" + idOfStartBtn).addEventListener("click", () => {
setId(startBtn)
mins = 1;
seconds = mins * 60;
totalsecs = mins * 60;
setTimeout(decremenT(idOfStartBtn), 60);
//startBtn.style.transform = "scale(1)";
paused = false;
})
document.getElementById("r" + idOfStartBtn).addEventListener("click", () => {
//startBtn.style.transform = "scale(1)";
clearTimeout(initial);
setProgress(0);
document.getElementById("hr"+idOfStartBtn).textContent = '00';
document.getElementById("min"+idOfStartBtn).textContent = '00';
});
document.getElementById("h" + idOfStartBtn).addEventListener("click", () => {
if (paused === undefined) {
return;
}
if (paused) {
paused = false;
initial = setTimeout(`decremenT(${idOfStartBtn})`, 60);
pause.textContent = "Pause";
pause.classList.remove("Resume");
} else {
clearTimeout(initial);
pause.textContent = "Resume";
pause.classList.add("resume");
paused = true;
}
})
function decremenT(takeId) {
//console.log("this is variable from decremenT:",takeId)
let sec = document.getElementById(`hr${takeId}`).textContent = Math.floor(seconds / 60).toString().padStart(2, "0");
document.getElementById(`min${takeId}`).textContent = seconds % 60 > 9 ? seconds % 60 : `0${seconds % 60}`;
if (circle.classList.contains("danger")) {
circle.classList.remove("danger");
//minutes.classList.remove("beep");
//secondes.classList.remove("beep");
}
if (seconds > 0) {
perc = Math.ceil(((totalsecs - seconds) / totalsecs) * 100);
setProgress(perc);
seconds--;
initial = window.setTimeout(`decremenT(${idOfStartBtn})`, 1000);
if (seconds < 45) {
circle.classList.add("danger");
//minutes.classList.add("beep");
//secondes.classList.add("beep");
}
} else {
mins = 0;
seconds = 0;
bell.play();
}
}
*{
margin:0;
padding:0;
}
body {
background-color: #D9AFD9;
background-image: linear-gradient(0deg, #D9AFD9 0%, #97D9E1 100%);
font-family: 'Microsoft PhagsPa';
height: 100vh;
color: hsl(210, 10%, 10%);
text-shadow: 0 1px 1px hsl(0deg 0% 100% / 50%);
}
.item {
border-radius: 15px;
filter: brightness(95%);
background-size: 450px;
margin: 40px;
box-shadow: 4px 4px 13px rgba(0,0,0,0.3), inset 10px 9px 18px rgba(0,0,0,0.55);
background-color: rgba(255, 255, 255, .15);
backdrop-filter: blur(5px);
}
.item:hover {
color: rgb(77, 74, 137);
opacity: 1;
cursor: pointer;
font-size: 2rem;
box-shadow: 6px 6px 15px rgba(0,0,0,0.3), inset 12px 11px 20px rgba(0,0,0,0.55);
}
#sortable li {
position:relative;
margin: 30px 30px 30px 0px;
padding: 1px;
width: 450px;
height: 458px;
font-size: 2em;
text-align: center;
}
#sortable {
display: flex;
flex-wrap: wrap;
list-style: none;
justify-content: center;
min-height: 200px;
padding-bottom:100px;
}
.clock {
padding: 3px;
display: flex;
justify-content: center;
align-items: center;
font-weight: bold;
height: 18vh;
width:18vh;
font-size: 24px;
}
.progress-ring {
position: absolute;
top: 10vh;
left: 5vw;
transform: translate(-50%, -50%);
}
.progress-ring__circle {
transition: 0.5s;
transform: rotate(-90deg);
transform-origin: 50% 50%;
stroke: rgba(142, 68, 173,1);
}
.progress-ring__circle2 {
transition: 0.5s;
transform: rotate(-90deg);
transform-origin: 50% 50%;
stroke: rgb(189, 195, 199);
}
.btn-group {
display: flex;
justify-content: start;
align-items: start;
height: 10%;
position: relative;
top: 10vh;
right: 50px;
z-index:1;
}
.timer {
height: 212px;
width: 212PX;
position: relative;
top: 200px;
left:200px;
}
.start {
background: rgb(48, 33, 253);
color: white;
margin-right: 5px;
padding: 2px;
width: 60px;
}
.break {
background: rgb(0, 199, 116);
color: #000000;
margin-right:5px;
padding:2px;
}
.reset {
background: rgb(250, 69, 109);
color: #000000;
margin-right: 5px;
padding: 2px;
width: 60px;
}
.halt {
background: rgb(253, 143, 17);
padding: 2px;
width: 60px
}
.resume {
background: rgb(131, 10, 252);
color: white;
width: 60px;
}
.danger {
stroke: rgba(243, 17, 28, 1);
animation: pulse 0.9s ease-in-out infinite;
}
.beep {
color: rgba(192, 57, 43,1.0);
animation: beep 0.9s infinite;
border-radius:50%;
}
.settedTime {
position: absolute;
top: 70px;
font-size: 14px;
align-items: center;
text-align: center;
padding-top: 0px;
opacity:.5;
}
.numberContainer {
display: inline-flex;
justify-content: center;
}
@keyframes pulse {
0%,100% {
transform: rotate(-90deg) scale(1);
}
50% {
transform: rotate(-90deg) scale(1.04);
box-shadow: 0 0 0 3px rgba(243, 17, 28, 0.8);
}
75% {
transform: rotate(-90deg) scale(1.01);
}
}
@keyframes beep {
0% {
transform: scale(0.9);
box-shadow: 0 0 0 0 rgba(192, 57, 43,0.2);
}
70% {
transform: scale(1);
box-shadow: 0 0 0 20px rgba(192, 57, 43,0);
}
100% {
transform: scale(0.9);
}
}
.text {
position: absolute;
top: 412px;
text-align: center;
/*border-top: solid;*/
-webkit-user-select: none;
left: 0px;
width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timer</title>
</head>
<body>
<ul id="sortable" class="row itemContainer">
<li class="item col-xs-4 col-sm-2 col-md-1">
<p class="text">Next Correction</p>
<div class="inner"><div class="resize"></div></div>
</li>
<li class="item col-xs-4 col-sm-2 col-md-1 ">
<p class="text">Next Correction</p>
<div class="inner"><div class="resize"></div></div>
</li>
<li class="item col-xs-4 col-sm-2 col-md-1 " >
<p class="text">Next Correction</p>
<div class="inner"><div class="resize"></div></div>
</li>
</ul>
</body>
</html>
How do I scan a QRCode from a base64 image in react native?
The application consists of, through a link of a pdf, reading a QRcode and presenting its information.
For this, I put the pdf in base64 through the blob, and now I needed to go to base64 and scan the QRCode.
For this, I’m using the ‘rn-qr-generator’ library.
If you find a solution with this or another library, I would appreciate it!
if (base64) {
// Detect QR code in image
RNQRGenerator.detect({
base64: `${base64}`,
})
.then((response) => {
const { values } = response; // Array of detected QR code values. Empty if nothing found.
setQRCode(values);
})
.catch((error) => console.log("Cannot detect QR code in image", error));
}
Return the error:
Cannot detect QR code in image TypeError: Cannot read properties of undefined (reading ‘detect’)
can’t connect to websocket (Mixed Content)
so i was trying to make web socket server
node js
const WebSocket = require("ws");
var porth = process.env.PORT || 80;
const wss = new WebSocket.Server({port:porth})
wss.on("connection", ws => {
console.log("nowe połączenie");
ws.on("message", data => {
console.log(data.toString());
});
ws.send("hej");
ws.on("close", () =>
{
console.log("rozłączenie");
});
})
app.js
ws.addEventListener("open", () => {
console.log("połączono")
ws.send("test");
ws.addEventListener("message", data => {
console.log(data.data)
})
})
and when i host it on my pc it works but
when i upload it to github pages it keeps
sending me error:
Mixed Content: The page at ‘https://*****.github.io/’ was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint ‘ws://****.herokuapp.com/’. This request has been blocked; this endpoint must be available over WSS.
and i dont know what should i do about it
Redux toolkit filter() not working when wanting to display new array at the same time
I am currently building a clothing shop in which you can add products to the cart, and delete each one of them as you like and it makes the cart re-render and display a new cart without that product within it.
so I’ve made a Slice for cart in redux. the ‘addProduct’ part works fine, but the ‘deleteProduct’ reducer which uses filter() doesn’t work. (when i click my delete button nothing happens, and no changes in difference in Redux Devtools)
my slice:
const selectedProductsSlice = createSlice({
name:'selectedProducts',
initialState:{
productList:[],
checkoutPrice:0,
},
reducers: {
addProduct:(state,{payload}) => {
state.productList.push(payload)
state.checkoutPrice += payload.price
},
deleteProduct:(state,{payload}) => {
state.productList.filter((foundProduct) => foundProduct.id !== payload.id)
}
}});
my button and handleDelete:
<button className="btn-delete" onClick={handleDelete(product)}>Delete</button>
function handleDelete(p) {
console.log(p)
dispatch(deleteProduct(p.product))
}
Laravel DataTables Unexpected End of Input error when clicking a button to update record
I am facing an issue with some buttons in Laravel when using ajax to update a record using DataTables and ajax.
This is the Scripts within the blade file
<script>
$(function() {
var table=$('#roll-table').DataTable({
autoWidth: false,
processing: true,
serverSide: true,
stateSave: true,
ajax: '{{ route('getCurrentRoll') }}',
columns: [
{ data: 'action', name: 'action', orderable: false, searchable: false, "width": "25%"},
{ data: 'member.membership_number'},
{ data: 'member.first_name'},
{ data: 'member.last_name'},
{ data: 'rollstatus.status'},
{ data: 'account', render: $.fn.dataTable.render.number(',', '.', 2, '$')},
],
});
})
function updateStatus(id, status){
$.ajax({
url: '{{ route('updateStatus') }}',
type: 'POST',
data: {id: id, status: status},
datatype: 'JSON',
success: function(response){
if(response.success){
$('#roll-table').DataTable().ajax.reload();
toastr.success(response.message);
}
else{
toastr.error(response.message);
}
}
});
}
</script>
This is the controller
public function rollstatus(Request $request)
{
$r = Roll::find($request->id);
$points = Pointsmaster::where('Reason', '=', 'Attendance')->value('Value');
$member = Roll::where('id', '=', $request->id)->value('member_id');
$year = Carbon::parse(now())->year;
$rollid = RollMapping::latest()->value('id');
$status = $request->status;
switch ($status) {
// Define variables for member paying using account and check balance
case 'V':
// Check Account Balance and back out if account balance is too low
if($r->member->Accounts->sum('amount') < 10)
{
Alert()->error("Error", "Insufficient Account Balance")->autoclose(1500);
return redirect(action('RollController@index'));
}
$paid = 'Y';
$title = 'Member Present';
$message = 'Member paid using account balance';
// Add Voucher use record
$voucher = new Accounts();
$voucher->member_id = $r->member_id;
$voucher->Reason = 'Weekly Subs';
$voucher->amount = -10;
$voucher->user = Auth::user()->username;
$voucher->save();
break;
// Define variables for member who didn't pay
case 'P':
$paid = 'N';
$title = "Member Present";
$message = "Member has not paid";
break;
// Define variables for member who is online
case 'O':
$paid = 'N';
$title = "Member Online";
$message = "Member marked as present online";
break;
// Define variables for member who paid cash
case 'C':
$paid = "Y";
$title = "Member Present";
$message = "Member paid by Cash";
break;
default:
Alert()->error("Error", "System Error has occured")->autoclose(1500);
return redirect(action('RollController@index'));
}
$r->status = $status;
if($paid != 'N')
{
$r->paidrollid = $rollid;
}
$r->save();
if (config('global.Squadron_Points') != 'N')
{
$p=new Points();
$p->member_id = $member;
$p->value = $points;
$p->year = $year;
$p->reason = "Squadron Night Attendance";
$p->save();
}
alert()->success($title, $message)->autoclose(1500);
return response()->json($request->id);
}
public function getCurrentRoll(Request $request)
{
$rollid = RollMapping::latest()->value('id');
$roll = Roll::with(array('member' => function($q) {
return $q->orderby('rank');
}))
->where('roll_id', '=', $rollid)->orderby('status')
->with ('rollstatus')
->get();
return DataTables::of($roll)
->addColumn('account', function($roll) {
return $roll->member->Accounts->sum('amount');
})
->addColumn('action', function($row){
$btn = '<a href="'.action('MembersController@show', $row->member_id).'" target="_blank" title="View" class="btn btn-round btn-info"><i class="fa fa-info"></i></a>';
if ($row->status == 'A')
{
$btn .= '<a href="javascript:void(0)" data-toggle="tooltip" title="Paid Cash" class="btn btn-round btn-success" onClick="updateStatus('.$row->id.', "C")><i class="fa fa-check"></i></a>';
$btn .= '<a href="'.action('RollController@rollstatus', [$row->id, 'P']).'" class="btn btn-round btn-danger" title="Not Paid"><i class="fa fa-times"></i></a>';
$btn .= '<a href="'.action('RollController@rollstatus', [$row->id, 'V']).'" class="btn btn-round btn-warning" title="Account Payment"><i class="fa fa-money"></i></a>';
}
return $btn;
})
->make(true);
}
public function index_test()
{
//
$rollid = RollMapping::latest()->value('id');
$rolldate = RollMapping::latest()->value('roll_date');
$members = Roll::with(array('member' => function($q) {
return $q->orderby('rank');
}))
->where('roll_id', '=', $rollid)->orderby('status')->get();
$online = Settings::where('setting', 'Online Meetings')->value('value');
return view('roll.index_test', compact('members', 'rolldate', 'rollid', 'online'));
}
rollstatus is the function I wish to call when updating the record
index_text loads the view
getCurrentRoll builds the DataTable
- Please note I have only updated the first button when after checking the status
if ($row->status == 'A')
{
$btn .= '<a href="javascript:void(0)" data-toggle="tooltip" title="Paid Cash" class="btn btn-round btn-success" onClick="updateStatus('.$row->id.', "C")><i class="fa fa-check"></i></a>';
Once this one is working I can update the others.
The issue I am facing is that when I click on the Paid Cash button, I get a
Uncaught SyntaxError: Unexpected end of input error in my console
What I am trying to do is pass the Row ID and “P” for paid into the controller
I have the following for my Route
Route::post('post/roll/updateStatus', 'RollController@rollstatus')->name('updateStatus');
I would like to know where I have gone wrong, also if I can have the record updated without refreshing the whole table (so if I have a searched filter, this remains but the record is updated)
Thanks
openid at_hash values do not match, but are similar
I’m using this openid client for implementing an SSO flow.
The error that I’m getting is that at_hash values do not match.
Example:
what the client is expecing: AIRY7ahdicSipVPIZtciog
what the client is getting from the JWT in the SSO flow: AIRY7ahdicSipVPIZtciog==
I know the problem is in the base64 encoding. I know that what I’m using is compliant with the standard.
What should I do? I was digging around the client code and I know what I have to change in order to “make it work”. It’s the first few lines in this file, but I’m not doing that. I think the problem is in the way the third party has their SSO flow configured and I don’t think I can convince them to change that.
js integer monupulation. manipulate this serial
myNnumbers function return numbers 1,2,3,4,5 on every onclick. how do I manipulate this serial
if (myNnumbers) == 50 {
50 = 1
51 = 2
52 = 3
}
audioplayer is not working in laravel and vue
I have an Issue where my Audioplayer i created is working in Mozilla but not in Chrome it causes that error
app.js:24303 The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page.
setAnalyzer @ app.js:24303
app.js:24303 The AudioContext was not allowed to start. It must be resumed (or created) after a user gesture on the page.
setAnalyzer @ app.js:24303
app.js:10456 [Vue warn]: Unhandled error during execution of mounted hook
at <LineAnimation line-color="#fed700" can-width=350 can-height=150 ... >
at <TrackCenter>
at <RouterView>
at <Tracks onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< Proxy > >
at <RouterView>
at <Seasons>
at <App>
warn @ app.js:10456
app.js:24305 Uncaught (in promise) DOMException: Failed to execute 'createMediaElementSource' on 'AudioContext': HTMLMediaElement already connected previously to a different MediaElementSourceNode.
at Proxy.setAnalyzer (https://URL/js/app.js:24305:29)
at Proxy.mounted (https://URL/js/app.js:24473:10)
at callWithErrorHandling (https://URL/js/app.js:10573:22)
at callWithAsyncErrorHandling (https://URL/js/app.js:10582:21)
at Array.hook.__weh.hook.__weh (https://URL/js/app.js:13082:29)
at flushPostFlushCbs (https://URL/js/app.js:10771:47)
at flushJobs (https://URL/js/app.js:10816:9)
i already tryed to use the diffeent webkits for the AudioContext but nothing is goind to work or maybe i need to patch that in some other way in my App?
i wrote something like this
const Plugin = {}
Plugin.install = function (Vue) {
window.AudioContext = window.AudioContext || window.webkitAudioContext || window.mozAudioContext || window.msAudioContext
window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.msRequestAnimationFrame
Vue.component(LineAnimation.name, LineAnimation)
}
and instaled it like this to my App.
const app = createApp({
components: {
Seasons,
Player,
Plugin,
routes,
},
})
app.use(Plugin)
app.use(router)
app.mount("#app")
Where i parse in the AudiContext is in here.
setAnalyzer: function () {
this.audioCtx = this.audioCtx || new AudioContext()
this.analyzer = this.analyzer || this.audioCtx.createAnalyser()
const src = this.audioCtx.createMediaElementSource(this.audio)
src.connect(this.analyzer)
this.analyzer.fftSize = this.fftSize
this.analyzer.connect(this.audioCtx.destination)
},
If somebody has an Idea how to solve this i would be really glad. If you need more of the code to get more information just ask!
Is there a way to run an ahk file from Javascript?
So I have an ahk file which converts a key into a series of other keyboard inputs.
But does anybody know a way to run an ahk script via JS?
Vue.JS Firefox and Safari don’t hides scrollbar when Chrome and Edge do
Im doing a bit of frontend development via Vue.JS and Vuetify. My goal was it to archive a hidden scrollbar (through i know i cannot delete it ^^) and i know that the code snippet shown below should do the job, they are located in the index.html that is used as a template for vue-cli to build the website:
<style>
html::-webkit-scrollbar { display: none; }
html { -ms-overflow-style: none; }
</style>
On Chrome and MS Edge these works flawlessly but on for example Safari and Firefox it doesn’t do a thing – even if its shown in the Developer tools it seems to be just ignored completely. If I put it into each App.vue (I got an Multi Page Project) it seems to work but why? And is there a solution to this Problem?
Greetings
Unexpected token ‘?’ using, Discord.js SlashComamnd handler
I’m new to 13v of discord.js, and I’m trying to settle in with it, I followed the 13v DSJ guide but still failed to make a slash commands handler, when I try to register my commands I get this error with a long weird code, the code has some kind of meaning, but it’s hard to understand as I’m not a really good developer, here is my error:
~/Test$ node deploy-commands.js
/home/runner/Test/node_modules/@discordjs/rest/dist/index.js:1
var Re=Object.create;var A=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var ye=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,we=Object.prototype.hasOwnProperty;var Ee=(r,e,t)=>e in r?A(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var te=r=>A(r,"__esModule",{value:!0});var Le=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Se=(r,e)=>{for(var t in e)A(r,t,{get:e[t],enumerable:!0})},se=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of ye(e))!we.call(r,i)&&(t||i!=="default")&&A(r,i,{get:()=>e[i],enumerable:!(s=be(e,i))||s.enumerable});return r},W=(r,e)=>se(te(A(r!=null?Re(ve(r)):{},"default",!e&&r&&r.__esModule?{get:()=>r.default,enumerable:!0}:{value:r,enumerable:!0})),r),xe=(r=>(e,t)=>r&&r.get(e)||(t=se(te({}),e,1),r&&r.set(e,t),t))(typeof WeakMap!="undefined"?new WeakMap:0);var l=(r,e,t)=>(Ee(r,typeof e!="symbol"?e+"":e,t),t),ie=(r,e,t)=>{if(!e.has(r))throw TypeError("Cannot "+t)};var u=(r,e,t)=>(ie(r,e,"read from private field"),t?t.call(r):e.get(r)),E=(r,e,t)=>{if(e.has(r))throw TypeError("Cannot add the same private member more than once");e instanceof WeakSet?e.add(r):e.set(r,t)},g=(r,e,t,s)=>(ie(r,e,"write to private field"),s?s.call(r,t):e.set(r,t),t);var re=Le((Oe,De)=>{De.exports={name:"@discordjs/rest",version:"0.3.0",description:"The REST API for discord.js",scripts:{build:"tsup && tsc --emitDeclarationOnly --incremental",test:"jest --pass-with-no-tests --collect-coverage",lint:"prettier --check . && eslint src __tests__ --ext mjs,js,ts",format:"prettier --write . && eslint src __tests__ --ext mjs,js,ts --fix",docs:"typedoc --json docs/typedoc-out.json src/index.ts && node scripts/docs.mjs",prepublishOnly:"yarn build && yarn lint && yarn test",changelog:"git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/rest/*'"},main:"./dist/index.js",module:"./dist/index.mjs",typings:"./dist/index.d.ts",exports:{import:"./dist/index.mjs",require:"./dist/index.js"},directories:{lib:"src",test:"__tests__"},files:["dist"],contributors:["Crawl <[email protected]>","Amish Shah <[email protected]>","SpaceEEC <[email protected]>","Vlad Frangu <[email protected]>","Antonio Roman <[email protected]>"],license:"Apache-2.0",keywords:["discord","api","rest","discordapp","discordjs"],repository:{type:"git",url:"git+https://github.com/discordjs/discord.js.git"},bugs:{url:"https://github.com/discordjs/discord.js/issues"},homepage:"https://discord.js.org",dependencies:{"@discordjs/collection":"^0.4.0","@sapphire/async-queue":"^1.1.9","@sapphire/snowflake":"^3.0.1","discord-api-types":"^0.26.1","form-data":"^4.0.0","node-fetch":"^2.6.5",tslib:"^2.3.1"},devDependencies:{"@babel/core":"^7.16.12","@babel/plugin-proposal-decorators":"^7.16.7","@babel/preset-env":"^7.16.11","@babel/preset-typescript":"^7.16.7","@discordjs/ts-docgen":"^0.3.4","@types/jest":"^27.4.0","@types/node-fetch":"^2.5.10","@typescript-eslint/eslint-plugin":"^5.10.0","@typescript-eslint/parser":"^5.10.0","babel-plugin-const-enum":"^1.2.0","babel-plugin-transform-typescript-metadata":"^0.3.2",eslint:"^8.7.0","eslint-config-marine":"^9.3.2","eslint-config-prettier":"^8.3.0","eslint-plugin-prettier":"^4.0.0",jest:"^27.4.7",nock:"^13.2.2",prettier:"^2.5.1",tsup:"^5.11.11",typedoc:"^0.22.11",typescript:"^4.5.5"},engines:{node:">=16.9.0"},publishConfig:{access:"public"}}});var $e={};Se($e,{ALLOWED_EXTENSIONS:()=>F,ALLOWED_SIZES:()=>P,ALLOWED_STICKER_EXTENSIONS:()=>G,CDN:()=>U,DefaultRestOptions:()=>L,DefaultUserAgent:()=>C,DiscordAPIError:()=>S,HTTPError:()=>_,REST:()=>de,RESTEvents:()=>j,RateLimitError:()=>D,RequestManager:()=>K,RequestMethod:()=>N});var ne=require("discord-api-types/v9"),ae=re(),C=`DiscordBot (${ae.homepage}, ${ae.version})`,L={agent:{},api:"https://discord.com/api",cdn:"https://cdn.discordapp.com",headers:{},invalidRequestWarningInterval:0,globalRequestsPerSecond:50,offset:50,rejectOnRateLimit:null,retries:3,timeout:15e3,userAgentAppendix:`Node.js ${process.version}`,version:ne.APIVersion,hashSweepInterval:144e5,hashLifetime:864e5,handlerSweepInterval:36e5},j=(m=>(m.Debug="restDebug",m.InvalidRequestWarning="invalidRequestWarning",m.RateLimited="rateLimited",m.Request="request",m.Response="response",m.HashSweep="hashSweep",m.HandlerSweep="handlerSweep",m))(j||{}),F=["webp","png","jpg","jpeg","gif"],G=["png","json"],P=[16,32,64,128,256,512,1024,2048,4096];var U=class{constructor(e=L.cdn){this.base=e}appAsset(e,t,s){return this.makeURL(`/app-assets/${e}/${t}`,s)}appIcon(e,t,s){return this.makeURL(`/app-icons/${e}/${t}`,s)}avatar(e,t,s){return this.dynamicMakeURL(`/avatars/${e}/${t}`,t,s)}banner(e,t,s){return this.dynamicMakeURL(`/banners/${e}/${t}`,t,s)}channelIcon(e,t,s){return this.makeURL(`/channel-icons/${e}/${t}`,s)}defaultAvatar(e){return this.makeURL(`/embed/avatars/${e}`)}discoverySplash(e,t,s){return this.makeURL(`/discovery-splashes/${e}/${t}`,s)}emoji(e,t){return this.makeURL(`/emojis/${e}`,{extension:t})}guildMemberAvatar(e,t,s,i){return this.dynamicMakeURL(`/guilds/${e}/users/${t}/avatars/${s}`,s,i)}icon(e,t,s){return this.dynamicMakeURL(`/icons/${e}/${t}`,t,s)}roleIcon(e,t,s){return this.makeURL(`/role-icons/${e}/${t}`,s)}splash(e,t,s){return this.makeURL(`/splashes/${e}/${t}`,s)}sticker(e,t){return this.makeURL(`/stickers/${e}`,{allowedExtensions:G,extension:t??"png"})}stickerPackBanner(e,t){return this.makeURL(`/app-assets/710982414301790216/store/${e}`,t)}teamIcon(e,t,s){return this.makeURL(`/team-icons/${e}/${t}`,s)}dynamicMakeURL(e,t,{forceStatic:s=!1,...i}={}){return this.makeURL(e,!s&&t.startsWith("a_")?{...i,extension:"gif"}:i)}makeURL(e,{allowedExtensions:t=F,extension:s="webp",size:i}={}){if(s=String(s).toLowerCase(),!t.includes(s))throw new RangeError(`Invalid extension provided: ${s}
SyntaxError: Unexpected token '?'
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/runner/Test/deploy-commands.js:2:18)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
Here is my code from “deploy-commands.js”:
const fs = require('fs');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, guildId, token } = require('./config.json');
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
rest.put(Routes.applicationGuildCommands(clientId, guildId), { body: commands })
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error);
Info:
Discord.js: "^13.6.0",
Node: "^16.13.2",
Host: "Replit",
run = "npm start",
start: "node ."
need jsPDF and html2pdf to create pdf and download it but no response
I need to create a function that turns webpages into a pdf file, then download it after a click function.
My function is
$('<script src="/webroot/help/jspdf.min.js"></script>').appendTo('head');
$('<script src="/webroot/help/html2pdf.js"></script>').appendTo('head');
var jsPDF = window.jspdf.jsPDF;
var pdf = new jsPDF('1','pt','a4');
pdf.canvas.height=72*11;
pdf.canvas.width = 72*8.5;
html2pdf($("div[widgetname=DC]"),pdf,function(pdf){
pdf.save('file.pdf');
});
I checked no downloads nor errors msg.
Why can’t I include articles in the category in node js ? findidandupdate Is a problem?
exports.storeArticle = async (req, res) => {
const Allcategory = await Category.find({});
let category = req.body.category ? req.body.category : null;
const newArticle = await Article.create({
title: req.body.title,
slug: req.body.slug,
summary: req.body.summary,
description: req.body.description,
body: req.body.body,
category: category,
parent: parent,
categories: Allcategory,
});
const articleCategoriesID = req.body.category;
```
findidandupdate Is a problem?
“`
Category.findByIdAndUpdate(
{ _id: articleCategoriesID },
{
$push: { articles: newArticle._id },
},
{ new: true, useFindAndModify: false }
);
console.log(req.body);
try {
res.redirect(/dashboard/categories/);
} catch (err) {
res.render(“admin/categories/new”, {
category: new Category(),
pageTitle: “ساخت دسته بندی”,
path: “/admin/create-category”,
layout: “./layouts/dashLayout”,
fullname: req.user.fullname,
errorArr: err,
});
console.log(err.message);
}
};