How to convert Luxon DateTime format into string or numbers?

I am using the following code to set up a Luxon clock for my project use.

import { DateTime } from 'luxon';
import React, { useEffect, useState } from 'react';

interface IProps {
  timezone: string;
  format: string;
  calendar?: string;
  daysOffset?: number;
}

const LiveDateTime: React.FC<IProps> = ({
  timezone,
  daysOffset,
  format,
  calendar,
}) => {
  const [timeLive, setTimeLive] = useState<DateTime>(DateTime.local());

  useEffect(() => {
    const interval = setInterval(() => {
      setTimeLive(
        DateTime.local()
          .setZone(timezone)
          .reconfigure({ outputCalendar: calendar })
          .plus({ days: daysOffset })
      );
    }, 1000);

    return () => clearInterval(interval);
  }, [timezone]);

  return <span>{timeLive?.toFormat(format)}</span>;
}; 
export default LiveDateTime;

Now, I am using this component in another place to define the month# of the current date.

const month = <LiveDateTime timezone={place?.timezone} format="M" />; // This returns '12' as a number in the UI (for December)
console.log(month)
getData(month); //this functions is supposed to return some data based on the given month.
//I get an error instead on this line that says, 'Argument of type 'Element' is not assignable to parameter of type 'number'.

When I print this in the console, I get an entire react.element object. I need to be able to use ’12’ as a number (for December) in getData()for the month variable. How can I covert this object into a number type or string type if necessary?
P.S. I tried using pareInt(). doesn’t work.

Html2Pdf JS – Rendering PDF while using a dark mode

I’m using the library Html2Pdf which works really well to allow my app’s users to download as PDF their invoices displayed in HTML. The problem encountered is when anyone need to download his/her invoice while using dark mode.

Switching from light to dark mode and reverse works by adding/removing a “disabled” attribute to the link tag :

<link href="path/to/css/app.css" rel="stylesheet" type="text/css" id="light" />
<link href="path/to/css/app-dark.css" rel="stylesheet" type="text/css" id="dark" disabled="disabled" />

Both files have the same css rules, only colours change.

If someone is using dark mode and need to download a PDF, html2pdf.js will print it exactly as it shown based on current css rules, therefore with black/gray backgrounds/fonts which isn’t really ideal for an invoice !

I already tried to change styles dynamically in the function which render the PDF after click, but of course the change is clearly visible to the user since it affects the whole page.

Therefore, my question is the following : How could I tell the function html2pdf() which css rules using without affecting the page itself ?

Is there a way to trim an array without creating a new array? [closed]

I want to use trim() to remove the white spaces from an array but I dont want to create a new array nor do I want to use map().

I have multiple random arrays that I want to iterate through and modify the existing array.

I have arrays that look like this.

var arr = [
   {
      "title": "sally",
      "animals": {
        "type":
           [
              [" dog"],
              [" cat "]
           ]
       }
  },
  {
      "title": "bob",
      "animals": {
        "type":
           [
              [" cow "],
              [" bald eagle "]
           ]
       }
  }     
]

but I want them to look like this:

var arr = [
   {
      "title": "sally",
      "animals": {
        "type":
           [
              ["dog"],
              ["cat"]
           ]
       }
  },
  {
      "title": "bob",
      "animals": {
        "type":
           [
              ["cow"],
              ["bald eagle"]
           ]
       }
  }     
]

I am using the split() function which is causing the values to add a space.

How to use Object.defineProperty for getters in Typescript?

I have used an implementation as given below in JavaScript.

class Base {
    installGetters() {
        Object.defineProperty(this, 'add', {
            get() {
                return 5;
            }
        });
    }
}

class New extends Base {
    constructor() {
        super();
        this.installGetters();
    }

    someAddition() {
        return 10 + this.add;
    }
}

I have defined the getter property add in the function of the parent class – Base and used that property in child class New after calling the installGetters() function in the child class constructor. This works for JavaScript, but this.add is throwing an error in case of Typescript. Any help would be much appreciated.

async fetch function returning promise pending [duplicate]

So i have a fetch function that should return me a url from a api that i created. It kinda works, but the issue is instead of returning the URL it returns promise pending. I’ve used async-await so I don’t know what could be causing the issue

   const getUser = async (id) => {
       let url = `http://127.0.0.1:8000/api/user/${id}/`
       const response = await fetch(url)
       const data = await response.json()
       return data.avatar
   }

    console.log(getUser(1))

This is the response from the API

{
    "id": 1,
    "email": "[email protected]",
    "username": "somewhattastydonut",
    "avatar": "https://somebucketname.s3.amazonaws.com/default.jpg"
}

I want it to return just the URL from the avatar but i don’t know what I’m doing wrong for it to return promise pending

Android WebView Deeplinking with Javascript Web app

I have a javascript web app that is being installed on android. I want to enable deep linking for this app, but not sure how to incorporate it into. I have actually completed what the android docs recommended, but after that I am lost. Here is what I have done –

Inside AndroidManifest.xml

<intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <category android:name="android.intent.category.LAUNCHER" />
        <data
            android:host="some url"
            android:scheme="https" />
    </intent-filter>

Inside FullscreenActivity.kt

// Read data from incoming intents - Deep linking
        val action: String? = intent?.action
        val data: Uri? = intent?.data

setContentView(webView)

if(data != null) {
            webView.loadUrl(data.toString())
        } else {
            webView.loadUrl(defaultUrl)
        }

So as you can see I have a hard coded url at the moment that the WebView just loads. Can someone explain to me how I could have deep linking work with my javascript app and android web view?

URL blocked ( Access-Control-Allow-Origin – Missing Header) while I am trying to get the data from Bluehost to react website app

I am creating a website using (react for website) that I wanted to get the data from my server in blueHost using php as a backend and react (JavaScript) as front-end

I have an issue that I am not able to load the data case of my file.php has blocked because of Access control allow Origin

any idea how can solve this issue?

here is my code app.js (react)

    const getData = async () => {
    fetch(URL,{
      mode:'cors',
      headers : {
        'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8',
  'Access-Control-Allow-Origin': '*',
    'Access-Control-Allow-Origin': 'http://localhost:3004',
    'Access-Control-Allow-Methods': 'GET',
    'Content-type': 'application/json; charset=UTF-8',
    'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept',
    'Access-Control-Request-Headers': 'x-token'
    }
    })
    .then((response) => response.json())
    .then((json) => console.log(json.flags))
    .catch((error) => console.log(error))
    .finally(() => console.log(false));

}

and here is my file.php

 <?php
include 'DBConfig.php';
 
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");

$json = file_get_contents('php://input');
$obj = json_decode($json, true);

if ($conn->connect_error) {
 
 die("Connection failed: " . $conn->connect_error);
}
 
$sql = "SELECT * FROM `Transactions`";
 
$result = $conn->query($sql);
 
if ($result->num_rows >0) {
 
 
 while($row[] = $result->fetch_assoc()) {
 
 $tem = $row;
 
 $json = json_encode($tem);
 
 
 }
} else {
    $json = json_encode("false");

}
 echo $json;
$conn->close();
?>

any idea how can I solve this issue?

Vanilla JS equivalent to JQuery function $.on

Here is some sample code of a ton of the exact same function in the project.

$('#psi').on('change', function() {
  if($(this).is(":checked")) {
    $('.psiOptions').removeClass('hidden-1');
  } else {
    $('.psiOptions').addClass('hidden-1');
  }
});

I’m trying to upgrade this to not rely on JQuery. What is the most correct way to do this in Vanilla JS besides assigning onclick=”someFunction()” 20 different times for 20 different cases?

POST Request from JS to FastAPI geting “422 Unprocessable Entity”

I’m starting to work on a project with React and FastAPI.

On the server side:

from fastapi import APIRouter, Request, Depends, Response, encoders
import typing
import datetime

from app.db.session import get_db
from app.db.crud import (
    create_lead,
)
from app.db.schemas import LeadCreate


leads_router = r = APIRouter()


@r.post("/leads", response_model=LeadCreate)
async def lead_create(
    # request: Request,
    lead: LeadCreate,
    db=Depends(get_db),
):
    lead.datetime_insert = datetime.datetime.now()
    return create_lead(db, lead)
from pydantic import BaseModel
import datetime


class LeadCreate(BaseModel):
    email: str
    source: str
    datetime_insert: datetime.datetime

    class Config:
        orm_mode = True
from sqlalchemy import Boolean, Column, Integer, String, DateTime

from .session import Base


class Lead(Base):
    __tablename__ = "lead"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String)
    source = Column(String)
    datetime_insert = Column(DateTime)

In frontend side:

export const create_lead = async (email: string, source: string) => {
    if (!(email.length > 0)) {
        throw new Error('Email was not provided');
    }

    const d = {"email": email,
               "source": source,
               "datetime_insert": "",}

    const request = new Request('/api/v1/leads', {
        method: 'POST',
        body: JSON.stringify(d),
    });

    const response = await fetch(request);

    if (response.status === 500) {
        throw new Error('Internal server error');
    }

    const data = await response.json();

    if (response.status > 400 && response.status < 500) {
        if (data.detail) {
          throw data.detail;
        }
        throw data;
    }

    return data;
};

However, I’m getting the following error in the backend log:
"POST /api/v1/leads HTTP/1.0" 422 Unprocessable Entity

I have already tried to use FormData. I think it is related to the data structure, where the frontend side is sending something different than the expected by server-side.

Poblem with embed message discord js

Hello everyone I have a problem with embed messages in discord js.
I have a variable which is storing text “.addField(“text”, “text”, false)” and I want to use this stored text in the embed message

Example

var fields = ".addField("text", "text", false).addField("text", "text", false);
const embedmessage = new Discord.MessageEmbed()
.setTitle("title")
.setDescription("description")
.setColor("#f2320c")

and I want to add this variable named fields to the end of this embed message. How can i do it?

Sorry for my english but I hope it isn’t a problem ;/

Disable scrolling without jumpy behaviour, or without it stoping dead on it’s tracks

Hello and good evening.

I’m trying to make scrolling impossible upon reaching a certain div, and making it possible again after another. Problem is between those I want to move between divs through anchors.

Let’s say this is my html:

<div id="plano1" class="plano">
<div id="plano2" class="plano">
<div id="plano3" class="planoslide"><a href="#plano4"><button onclick="enableScroll()"><a>
<div id="plano4" class="planoslide"><a href="#plano5"><button onclick="enableScroll()"><a>
<div id="plano5" class="plano">

I want to make scrolling disabled upon entering the class .planoslide. I have two functions which add or remove the class .stop-scrolling which has the usual height:100% and overflow:hidden. The funcion disableScroll is activated upon entering the planoslide class but it stops dead in its tracks either mid heigh, or if I scroll to much even after it. So I had to animate it almost upon entering the div so that offsets to the right place. Right now this is my code:

function disableScroll() {
$('body').addClass('stop-scrolling');
$('body').bind('touchmove', function(e){e.preventDefault()})
}

function enableScroll() {
$('body').removeClass('stop-scrolling');
$('body').unbind('touchmove');
}

$(window).bind('scroll', function() {
  if($(window).scrollTop() >= ($('.planoslide').offset().top + $('.planoslide').outerHeight() - window.innerHeight)*0.1) {
    disableScroll();
    $('html,body').animate({
      scrollTop: $(".planoslide").offset().top},
      2000);
  }
}); 

Problem is when i use the button with onclick to enable the scroll again nothing happens.
I wished it would not only enable the scroll back again but navigate to the supposed ID I send it to.

Also the first enableScroll should enable it and disable again upon entering the new .planoslide, but that one I haven’t gotten to yet.

Help would be much aprecciated.

Best regards.

Creating a server like pusher using websocket nodejs

I have a big question regarding Websocket.

Well, let’s go..
What am I needing? I need to add in my application a way to notify my user in real time about things that happen in the backend, for example, let’s say that some administrator has updated the user’s data, then that same user needs to receive a notification saying that the data has changed.

Challenges in this process.
1st – I need to save a unique ID of the user connected to the websocket, for that I’m using the “getUniqueID” function that I’ve seen in other posts, the question in this case would be, could I save the id that was generated in the database referring to the logged in user? is it a good alternative?

2nd I need that when the registry is updating send the message to the user, in case I need to trigger the notification coming from the Controller, the question is, how do I access the WSS variable once it was instantiated when the server was turned on?

Below I’m putting my 2 files that I’m using to turn on the server.

appSocket.js

import WebSocket from "ws";
import { Server } from "socket.io";

function onError(ws, err) {
    console.error(`onError: ${err.message}`);
}

function onMessage(ws, data) {
    console.log(`onMessage: ${data}`);
    ws.send(`recebido!`);
}

function onConnection(ws, request) {     
    ws.on('message', data => onMessage(ws, data));
    ws.on('error', error => onError(ws, error));
    ws.id = request.headers['sec-websocket-key']; 
    console.log("WS ID = "+ws.id)
}

export default (server) => {
    // const wss = new Server(server);
    const wss = new WebSocket.Server({
        server
    });

    wss.getUniqueID = function () {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
        }
        return s4() + s4() + '-' + s4();
    };
    
    wss.on('connection', onConnection);

    console.log(`App Web Socket Server is running!`);
    return wss;
}

My App.js

// import app from './app';
import appWs from './app-socket';
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import dotenv from 'dotenv';
import {i18n} from './i18n';
import routes from './routes';
import bodyParser from 'body-parser';

var multer = require('multer');
var upload = multer();
const path = require('path');
dotenv.config();

class App {
    constructor() {
      this.express = express();
  
      this.database();
      this.middlewares();
      this.routes();
    
      const server = this.express.listen(process.env.PORT || 3000, () => {
        console.log(`Welcome to  => PORT ${process.env.PORT || 3000}`);
      });

      appWs(server);
    }
  
    database() {
      //      
    }
  
    middlewares() {
      this.express.use(cors({ origin: process.env.CORS_ORIGIN || '*' }));
      this.express.use(helmet());      
      this.express.use(morgan('dev'));
      this.express.use(express.json());      
      this.express.use(express.static(path.join(__dirname,'public')));
      // for parsing application/json
      this.express.use(bodyParser.json()); 
      // for parsing application/xwww-
      this.express.use(bodyParser.urlencoded({ extended: true })); 
      //form-urlencoded
      // for parsing multipart/form-data
      this.express.use(upload.array()); 

      let appExpress = this.express;
      i18n.init({ appExpress });     
    }
  
    routes() {
      this.express.use(routes);
    }
  }
  export default new App().express;

Trying to make a function that prints an array range. I’m given the start, stop and step values. I keep getting an infinite loop

I am trying to write a function that returns a list of integers from a ‘start’ value (inclusive) to a ‘stop’ value (exclusive) and am given the ‘step’ (or number to increment by…).

The function is supposed to be able to handle different amount of arguments passed in. I believe I have the function most of the way completed but I seem to be getting an infinite loop and am unsure why or how to proceed.

Here is the code I have written so far…

function range(start, stop, step) {
    if (arguments.length===1) {
        start = 0;
        stop = arguments[0];
        step = 1;
    } else if (arguments.length===2) {
        start = arguments[0];
        stop = arguments[1];
        step = 1;
    } else if (arguments.length===3) {
        start = arguments[0];
        stop = arguments[1];
        step = arguments[2];
    }
    // define result array
    let result = [];
    // create a for-loop
    for (start; start < stop; start + step) {
        result.push(start);
    }
    return result;
}

And here are some example calls and their expected outputs…

range(10); -> [0,1,2,3,4,5,6,7,8,9]
range(1,11); -> [1,2,3,4,5,6,7,8,9,10]
range(0,30,5); -> [0,5,10,15,20,25]
range(0,-10,-1); -> [0,-1,-2,-3,-4,-5,-6,-7,-8,-9]

The function is also supposed to be able to do negative ranges with negative ‘step’ values as well.

Could someone explain to me why I seem to be getting an infinite loop?

How to fill an empty nested object with existed one [closed]

The question maybe simple, but i’m stuck with this for half a day,
I have an object like this:

{
    "loginStatus": false,
    "data": {}
}

Now i recieve some data like this

{
    "id": 1,
    "firstname": "Le",
    "Last name": " Quoc Khanh",
    "username": "[email protected]",
    "password": 12345678
}

How can i put this data to above object , the result be like

{
     "loginStatus": false,
     "data": 
      {
        "id": 1,
        "firstname": "Le",
        "Last name": " Quoc Khanh",
        "username": "[email protected]",
        "password": 12345678
      }
 }

How remove specific text from option

i need remove text “+ 0 Kč” from this options via Jquery, can you help me? Thx

 <option value="177" data-surcharge-final-price="0" data-surcharge-additional-price="0">Ginger +0 Kč</option>
 <option value="180" data-surcharge-final-price="0" data-surcharge-additional-price="0">Taupe +0 Kč</option>
 <option value="183" data-surcharge-final-price="0" data-surcharge-additional-price="0">Mocca +0 Kč</option>