How i pass a media query or fix width and height using onclick event?

So i convert html page to pdf by using onclick event

My code is:-
function generatePDF() {
var element = document.getElementById(‘invoice’);

var doc = {

filename: ‘myfile.pdf’,
image: { type: ‘jpeg’, quality: 1 },
html2canvas: { dpi:192, letterRendering : true, scale: 2, text Align: ‘center’, },
jsPDF: { unit: ‘pt’, format: ‘letter’, orientation: ‘portrait’, format: ‘a4’ },

};

html2pdf().set(doc).from(element).save();

}

By using onclick event the page will be downloaded successfully but the alignment of the content
is changed.
I want to give fix size so the content alignment is not change and also in mobile view the page will be downloaded at that defined fix size.

Javascript – Remove array elements if all elements are null

Cosider the following array:

let array = [
 {Product Title: "Milk", Product Variant: "2L", Quantity: "3"},
 {Product Title: "Water", Product Variant: "", Quantity: "3"},
 {Product Title: "Pepsi", Product Variant: "", Quantity: ""},
 {Product Title: "", Product Variant: "", Quantity: ""}
 {Product Title: "", Product Variant: "", Quantity: ""}
]

How do I remove elements from the array, if all the elements have no value?

What I’ve tried:

let contents = []

for (let i in array) {
  Object.keys(array[i]).forEach((k) => array[i][k] == "" && delete array[i][k])
  contents.push(array[i])
}

console.log(contents)

but this returns:

0: {Product Title: "Milk", Product Variant: "2L", Quantity: "3"},
1: {Product Title: "Water", Quantity: "3"},
2: {Product Title: "Pepsi"},
3: {}
4: {}

While I would want:

0: {Product Title: "Milk", Product Variant: "2L", Quantity: "3"},
1: {Product Title: "Water", Product Variant: "", Quantity: "3"},
2: {Product Title: "Pepsi", Product Variant: "", Quantity: ""}

Iterating String.split() working differently than I expected [duplicate]

I am writing a simple javascript code to parse, and verify a chess position written in Forsyth–Edwards Notation (FEN).

The default chess position in this notation is given by,

const defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";

There are 6 components, I split the components by whitespace using String.split(” “), I now want to further split the first element of the resulting array by “/”, which will give the state of each rank.

Running this code gives me an unintuitive result…

const defaultFEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
const locations = defaultFEN.split(" ")[0];

for (let rank in locations.split("/")) {
   console.log(rank);
}

I expected the output to be 8 Strings, delimited by “/”, in the first portion of the defaultFEN string. Instead I get the numbers 0-7 printing out.

Interestingly, If I manually access this array, console.log(locations.split("/")[i]), for any number i in the interval [0-7], I see the result I intended.

Why are the numbers 0-7 printing out when using the iterative loop, but it works exactly as intended if I use a normal index based for loop?

Chnage script attr with js – reading ‘setAttribute’ error

I am trying to add a custom data-attr to a script by getting the value after hash from the URL, so when the script is executed at the end of the page it already has the data-segment attr populated.

For example, if the URL is https://domain/#the-hash-tag then the data-segment should be equal to the-hash-tag

var afterHashtag = window.location.hash.substr(1);
//console.log(afterHashtag)

document.getElementById('widget').setAttribute('data-segment', afterHashtag);

<script id="widget" type="text/javascript" src="https://domain/sdk.js" data-segment=""></script>

I am also getting this error

Uncaught TypeError: Cannot read properties of undefined (reading 'setAttribute')

Researching I have found this thread How to change the attributes of the <script> tag, but can’t find what can I do in my case.

Trying to solve Lowest common ancestor

var lowestCommonAncestor = function(root, p, q) {
  // return the path to the node
  let path = []
  const search = (node, target) => {
    if (node === null) return false
    
    path.push(node)
    
    if (node === target) return true
    
    const leftSearched = search(node.left, target)
    
    if (leftSearched) return true
    
    const rightSearched = search(node.right,target)
    
    if (rightSearched) return true
    
    path.pop()
  }
  
  search(root, p)
  const pathP = path
  path = []
  search(root, q)
  const pathQ = path
  
  let result
  while(pathP.length > 0 && pathQ.length > 0 && pathP[0] === pathQ[0]) {
    result = pathP[0]
    pathP.shift()
    pathQ.shift()
  }

  return result
};


console.log(lowestCommonAncestor([3,5,1,6,2,0,8,null,null,7,4],5,1));

Iam getting following error message
const leftSearched = search(node.left, target)
^
TypeError: Cannot read property ‘left’ of undefined

Could someone help me to fix this issue

Why regex test is returning different results for same command [duplicate]

I’m facing a weird behavior by the regex test.

I have the below codes.

const pattern = /[A-Z]/g;
const str = "BehNam";
console.log(pattern.test(str)); //returns true
console.log(pattern.test(str)); //returns true
console.log(pattern.test(str)); //returns false

The first and the second logs return true and the third one returns false.
After a lot of tests, I figured out that this is because I have two Uppercase letters in my string.
Does anyone have any idea why these regex tests lead to different results while I am repeating the same code? And if yes what is the fix?

you can also find the codes here.

How to use mongodb charts javascript SDK with a flask app?

I currently have a flask app that runs and works fine (testing on my local machine), however I am trying to using the javascript SDK for mongodb charts and when i try to use the javascript script it just returns a Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/plain" in the web browser console. I have set type=”module” same error and cant seem to find any working fixes online.

I followed the documentation to set up the SDK which was to do npm install @mongodb/charts…, however, I’ve never really used javascript / npm before, and I am not sure if I have done this correctly.

So if anyone has a full guide on how to get the js SDK for mongodb charts working with a Flask/Python application or if they can spot the error, that would be great.

init.py (run from flask run)

from flask import Flask
from .main.routes import main
from .extensions import mongo
import os
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())

def create_app():
    app = Flask(__name__)
    
    # Load config from secret file (.env)
    app.config['MONGO_URI'] = os.environ.get("MONGO_URI")
    
    # Load the pymongo extension
    mongo.init_app(app)
    
    # Register blueprint
    app.register_blueprint(main)
    
    print("App created")
    return app

index.js (file giving the error)

import EmbedSDK from "@mongodb-js/charts-embed-dom";

// Generate a new SDK with base url
const sdk = new EmbedSDK({
    baseUrl = "https://charts.mongodb.com/charts-project-0-ginzr"
});

// Generate a new chart with the sdk
const chart1 = sdk.createChart({ 
    chartId: "6945269f-84ef-489a-93b2-b0c4018586cf" ,
    width: 640,
    height: 480,
    theme: "dark"
});

// Render the chart to html
chart1.render(document.getElementById("chart1"));

index.html (main page)

{% extends "layout.html" %}
{% block content %}
    <title>Home</title>

    <section id="reviews">
        <div class="review-box-container">
            <!-- Get all the data from mongodb database-->
            {% for review in reviews %}
            <div class="review-box">
                <div class="box-top">

                    <div class="profile">
                        <div class="profile-img">
                            <img src="{{ url_for('static', filename='images/Lincoln-Logo.png') }}" width="50" height="50" alt="profile">
                        </div> 
                        <div class="name-user">
                            <strong>{{ review.User }}</strong>
                            <span>Datetime</span>
                        </div>
                    </div>

                    <div class="review-content">
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="far fa-star"></i> <!-- Holo star -->

                    </div>
                </div>

                <div class="review-comment">
                    <p>{{ review.Review_Summary}}</p>
                </div>
            </div>
            {% endfor %}
        </div>
    </section>

    <!--TO DO::-->
    <!--1. Include the mongodb charts (watch liked video)-->
    <div id="chart1" class="chart"></div>
    <script type="module" src="{{ url_for('static', filename='index.js') }}"></script>

{% endblock content %}

How is this array joining a string?

Question about delimiter :

console.log(Array(2).join('a'));
console.log(['', '', ''].join('a'));

Why does the above code only return:

a
aa

instead of:

aa
aaa

Array(2) creates an array with two empty or undefined elements in an array [undefined, undefined], so shouldn’t it output aa?

How can I display an Image without downloading it from a url in NodeJS?

In NodeJS I used package named node-fetch, also for taking JSON Response, but how about an Image response? How can I do that? In my current codes, It does only save the image not showing like PIL from python.

var tr = "https://i.picsum.photos/id/866/200/300.jpg?hmac=rcadCENKh4rD6MAp6V_ma-AyWv641M4iiOpe1RyFHeI"

export async function get_image() {
    const get_url = await fetch(tr)
    const image = get_url.body.pipe(fs.createWriteStream('./image.png'))
}

await get_image();

Cannot parse html with js with vanilla js

I am trying to add my html website code from data-prototype:

<div id="accordion" data-prototype='
<div class="card-body">
    <textarea id="solution_answers___name___content" name="solution[answers][__name__][content]" required="required"></textarea>

    <script type="text/javascript">
        var CKEDITOR_BASEPATH = "/bundles/fosckeditor/";
    </script>
    <script type="text/javascript" src="/bundles/fosckeditor/ckeditor.js"></script>
    <script type="text/javascript">
        if (CKEDITOR.instances["solution_answers___name___content"]) { 
            CKEDITOR.instances["solution_answers___name___content"].destroy(true); 
            delete CKEDITOR.instances["solution_answers___name___content"]; 
        }

            CKEDITOR.addTemplates("my_templates", {"templates":[{"title":"My 
            Template","description":"My awesome template","html":"<p>Crazy template :) 
            </p>"}]});

    </script>
</div>'></div>

As you can see, there is also some js code from ckeditor.

When I try to add it with jquery:

let el = document.querySelector('#accordion');
let template = el.dataset.prototype;
let $root = $(el);

$root.append(template);

Everything works fine, I mean there is no erros in console.

When I try to add it with vanilla js:

let el = document.querySelector('#accordion');
let template = el.dataset.prototype;
const scriptEl = document.createRange().createContextualFragment(template);
el.append(scriptEl);

In dev console, I am getting error:

Uncaught ReferenceError: CKEDITOR is not defined

If I execute the same script one more time, the error is gone, and everything works as expected.

Does someone know, why I am getting that error?

Here is the content of /bundles/fosckeditor/ckeditor.js

unable to access config variables

server.js

const dotenv = require("dotenv");
const connectDatabase = require("./config/database");
const cloudinary = require("cloudinary");

// Handling uncaught errors
process.on("uncaughtException", (err) => {
  console.log(`Error: $(err.message)`);
  console.log("Shutting down server due to uncaught exception");

  process.exit(1);
});

//config

dotenv.config({ path: "backend/config/config.env" });

//connecting to database
connectDatabase();
cloudinary.config({
  cloud_name: process.env.CLOUDINARY_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
});

const server = app.listen(process.env.PORT, () => {
  console.log(`server is working on ${process.env.PORT}`);
});

//unhandled promise rejection

process.on("unhandledRejection", (err) => {
  console.log(`Error: ${err.message}`);
  console.log("Shutting down server due to unhandled promise rejection");
  server.close(() => {
    process.exit(1);
  });
});

databse.js

const { connect } = require("net");

const connectDatabase = () => {
  mongoose
    .connect(process.env.DB_URI, {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    })
    .then((data) => {
      console.log(`Mongodb connected with server ${data.connection.host}`);
    });
};

module.exports = connectDatabase;

config.env

PORT=4000
DB_URI = "mongodb://localhost:27017/Ecommerce"

process.env.PORT is coming undefined instead of 4000. The same problem is coming for DB_URI and other process.env variables. If I write 4000 instead of process.env.PORT and “mongodb://localhost:27017/Ecommerce” instead of process.env.DB_URI it works fine. Below is the Error in my terminal.

server is working on undefined
Error: The uri parameter to openUri() must be a string, got “undefined”. Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string.
Shutting down server due to unhandled promise rejection

How can I resolve this issue?

JS. Check the string for such a view 120/80

Please tell me, is it possible to check the string (in JavaScript) for such a view (exaple below). So that the first digit is two or three digits, then a slash (/) and then a two or three digit number.

Like this 100/10 or 20/30 or 200/500 or 40/500

Thanks in advance.

TypeError: statevalue is undefined

I am making a comments component wherein I get data from a local stored json file. I import the data in the variable data and set its corresponding fields to my state values. But when I pass the data through the context, it says that it is undefined.

data.json

{
  "currentUser": {
    "image": { 
      "png": "./images/avatars/image-juliusomo.png",
      "webp": "./images/avatars/image-juliusomo.webp"
    },
    "username": "juliusomo"
  },
  "comments": [
    {
      "id": 1,
      "content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
      "createdAt": "1 month ago",
      "score": 12,
      "user": {
        "image": { 
          "png": "./images/avatars/image-amyrobson.png",
          "webp": "./images/avatars/image-amyrobson.webp"
        },
        "username": "amyrobson"
      },
      "replies": []
    }
  ]
}

this is how I store and pass data
context.js

import data from "./data";

const AppContext = React.createContext();

const AppProvider = ({ children }) => {
  const { comments, setComments } = useState(data.comments);
  const { currUser, setCurrUser } = useState(data.currentUser);
  return (
    <AppContext.Provider value={{ comments, currUser }}>
      {children}
    </AppContext.Provider>
  );
};

this is where I get the error
App.js

import { useGlobalContext } from "./context";
const App = () => {
  const { comments, currUser } = useGlobalContext();
  ...
}

this is the error exactly