Cannot read properties of undefined (reading ‘forEach’) when no Array

I got this error :

Cannot read properties of undefined (reading ‘forEach’)

if(response.Response) {
      $('#list').html('');
      response.Search.forEach(function(movie) {        
        var movieContent;
        if(movie.Poster === 'N/A') {
          movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year}</li>`;
        } else {
          movieContent = `<li class="list-group-item">${movie.Title} - ${movie.Year} <a href="${movie.Poster}" class="btn btn-xs btn-primary" id="poster-link">Poster</a></li>`;
        }
        $('#list').append(movieContent).hide().fadeIn(); 
      });
    }
  });

The error comes when I put less than 3 letters in my search input and the output is

{Response: ‘False’, Error: ‘Too many results.’}

otherwise, from 3 letters the response is correct

{Search: Array(2), totalResults: ‘2’, Response: ‘True’}

I understand that this is because there is no Array in the response but how can I prevent this error?

on function after load jquery

Please tell me, there are 2 pages: index.html, load.html.

There is a script that is included in index.html which contains the $('div').on() function for elements that are on the load.html page.
After calling the $('.el').load('load.html') function, the events stop working. How beautifully can you make the events fire even after updating the page with elements?

P.S. hanging a function on an element and loading a script in the load.html page is not suitable, the script is the same on the index.html page.

How to give TypeORM Datasource from middleware to Nestjs

I have a middleware that create a connection from TypeORM to the database wanted, at each request to the api.

I would like to link the created Datasource connexion to Nestjs and use the Datasource from the Nestjs injections like :

@InjectDatasource()

The only things I could have done was to pass the TypeORM Datasource has a part of request so the controllers could use it.

Is there a way to do it from the Nestjs injection directly ? It would be better and easier for the developpers.

Thanks in advance.

node.js Readable process?

i’m studying node.js stream module

and there’s one problem i can’t solve by myself.

const fs = require('fs')
const {Readable} = require('node:stream')

const rs = new Readable({
  read(size) {
    if(this.count < 3){
      console.log('read: ', this.count)
      this.push(`data${this.count + 1}t`)
      this.count++
    }else{
      console.log('read: null')
      this.push(null)
    }
  }
});
const ws = fs.createWriteStream('./big.txt')
rs.count = 0
rs.on('data', (c) => console.log('[data event]'))
rs.pipe(ws);

and big.txt is like this as i expected

data1 data2 data3

but the console.log is like this and this is not what i expected

read: 0
read: 1
[data event]
read: 2
[data event]
read: null
[data event]

i expected this

read: 0
[data event]
read: 1
[data event]
read: 2
[data event]
read: null

why is it different?
can anybody let me know? thanks

Triggering MOUSEDOWN event across all elements within container in JavaScript

I am making a sketchpad (Etch-a-sketch) that colors the blocks within the grid as you click and drag the cursor over them. For that, I used the mousedown event.

The problem I face is that even though I have applied the event to all the elements using a for loop, the mousedown events do not carry over to the other elements within the sketchpad container.

HTML

  <body>
    <header>
      <h1>Sketchpad 1.0</h1>
    </header>

    <main id="main">
        <div class="settings-panel">
          <button id="grid-size">CREATE GRID</button>
          <button class="hidden" id="pencil">PENCIL</button>
          <button class="hidden" id="rainbow">RAINBOW</button>
          <button class="hidden" id="eraser">ERASER</button>
          <button class="hidden" id="reset">RESET</button>
        </div>

        <div class="sketchpad">
        </div>
      </div>
    </main>

    <footer>
      <a href="https://www.linkedin.com/in/guchierrez/" target="_blank">
        <img src="./icons/linkedin.png">
      </a>
      <a href="https://github.com/guchierrez/etch-a-sketch" target="_blank">
        <img src="./icons/github.png">
      </a>
    </footer>
  </body>

JavaScript

/*========================================
======5. DRAWING BUTTON FUNCTIONALITY=====
=======PENCIL, RAINBOW AND ERASER=========
========================================*/

pencilButton.addEventListener("click", function () {
  const blocks = document.querySelectorAll(".block");
  for (i = 0; i < blocks.length; i++) {
    const blocks2 = document.getElementById(`block-${i}`);
    blocks2.addEventListener("mousedown", function () {
      for (i = 0; i < blocks.length; i++) {
        blocks2.style.backgroundColor = "black";
      }
    });
  }
});

const colors = [
  "#9400D3",
  "#4B0082",
  "#0000FF",
  "#00FF00",
  "#FFFF00",
  "#FF7F00",
  "#FF0000",
];

rainbowButton.addEventListener("click", function () {
  const blocks = document.querySelectorAll(".block");
  for (i = 0; i < blocks.length; i++) {
    const blocks2 = document.getElementById(`block-${i}`);
    blocks2.addEventListener("mousedown", function () {
      for (i = 0; i < blocks.length; i++) {
        let randomColors = colors[(colors.length * Math.random()) | 0];
        blocks2.style.backgroundColor = randomColors;
      }
    });
  }
});

eraserButton.addEventListener("click", function () {
  const blocks = document.querySelectorAll(".block");
  for (i = 0; i < blocks.length; i++) {
    const blocks2 = document.getElementById(`block-${i}`);
    blocks2.addEventListener("mousedown", function () {
      for (i = 0; i < blocks.length; i++) {
        blocks2.style.backgroundColor = "white";
      }
    });
  }
});

It works as intended with mouseover, but it colors indefinitely. I would like to be able to color only when the click button is pressed.

Set Button Uppy React File Input as SVG Image

I want to change the button of Uppy File input from string text to svg image, and this is my code :

import { DeleteOutlined } from '@ant-design/icons';
import Uppy from '@uppy/core';
import { FileInput } from '@uppy/react';

function MyComponent() {
  const [uppy, setUppy] = useState(null);

  function handleMount() {
    const uppyInstance = Uppy({
      autoProceed: true,
      restrictions: {
        maxFileSize: 1000000, // example restriction
      },
    });

    setUppy(uppyInstance);
  }

  function handleUnmount() {
    uppy.close(); // close the uppy instance when the component is unmounted
  }

  const fileInputProps = {
    uppy: uppy,
    target: '#file-input-container',
    pretty: true,
    locale: {
      strings: {
        chooseFiles: 'Choose files'
      },
    },
  };

  return (
    <div
      id="file-input-container"
      onMouseEnter={handleMount}
      onMouseLeave={handleUnmount}
    >
      <FileInput {...fileInputProps} />
    </div>
  );
}

in locale.strings there is string text ‘Choose files’, how to replace to be <DeleteOutlined icon ?

Sharp lines in corners of Threejs BoxGeometry shadows

I made a structure using BoxGeometry, and I have a DirectionalLight rotating around it. The problem is, I can see aliased light bleed in the corners. I’ve tried updating the shadow.mapSize, the blur radius, the renderer.shadowMap.type, but nothing has worked so far.

shadow aliasing

//left wall
const geometry = new THREE.BoxGeometry( 1, 15, 7 );
const material = new THREE.MeshPhongMaterial( {color: 0xFFFFFF} );
const cube = new THREE.Mesh( geometry, material );
cube.position.y = 7.5; 
cube.position.z = -4.5; 
cube.receiveShadow = true
cube.castShadow = true
scene.add( cube );

//right wall
const geometry2 = new THREE.BoxGeometry( 1, 15, 7 );
const material2 = new THREE.MeshPhongMaterial( {color: 0xFFFFFF} );
const cube2 = new THREE.Mesh( geometry2, material2);
cube2.position.y = 7.5;
cube2.position.z = -4.5; 
cube2.position.x = 16; 
cube2.receiveShadow = true
cube2.castShadow = true
scene.add( cube2 );


//back wall
const geometry3 = new THREE.BoxGeometry( 1, 15, 15 );
const material3 = new THREE.MeshPhongMaterial( {color: 0xFFFFFF} );
const cube3 = new THREE.Mesh( geometry3, material3);
cube3.position.y = 7.5;
cube3.position.x = 8;
cube3.position.z = -7.5 
cube3.rotateY(Math.PI / 2)
cube3.receiveShadow = true
cube3.castShadow = true
scene.add( cube3 );


//top
const geometry4 = new THREE.BoxGeometry( 1, 7, 17 );
const material4 = new THREE.MeshPhongMaterial( {color: 0xFFFFFF} );
const cube4 = new THREE.Mesh( geometry4, material4);
cube4.position.y = 15.5;
cube4.position.x = 8;
cube4.position.z = -4.5 
cube4.rotateY(Math.PI / 2)
cube4.rotateZ(Math.PI / 2)
cube4.receiveShadow = true
cube4.castShadow = true
scene.add( cube4 );




// DIRECTIONAL LIGHT
const directionalLight = new THREE.DirectionalLight(0xffffff, 1);
directionalLight.position.x += 20
directionalLight.position.y += 20
directionalLight.position.z += 20
directionalLight.castShadow = true
directionalLight.shadow.mapSize.width = settings.shadowMapSize;
directionalLight.shadow.mapSize.height = settings.shadowMapSize;
directionalLight.shadow.radius = settings.shadowRadius
// directionalLight.shadow.blurSamples = 500
const d = 25;
directionalLight.shadow.camera.near = 0.5
directionalLight.shadow.camera.far = 60
directionalLight.shadow.camera.left = - d;
directionalLight.shadow.camera.right = d;
directionalLight.shadow.camera.top = d;
directionalLight.shadow.camera.bottom = - d;
scene.add(directionalLight);

scene.add( new THREE.CameraHelper( directionalLight.shadow.camera ) );

react jest test without assertions to test rendering with getBy queries

@testing-library/react provides several methods for querying rendered elements including getBy* queries which will throw an error if the element is not found.

How should I handle this in my test when I just want to test that there rendered elements are on screen.
When the getBy throws an error if element is not found there is no need to assert that expect(element).toBeInTheDocument() but then I have a test without assertion.

Should I use a dummy assertion like expect(1).toBe(1) or whats the best practice here?

Example:

describe("MyComponent", () => {

  // Render helper
  function renderer(props) {
    const result = render(<MyComponent {...props} />);

    // Will throw error when element with text "My element" is not found
    const element = screen.getByText("My element");

    return {...result, element);
  }

  it("renders with my element", () => {
    const {element} = renderer({});
   
    // Redundant, will always pass when reaching this point
    expect(element).toBeInTheDocument();
  });

  // Has same effect but does not use assertion
  it("renders with my element w/o assertion", () => {
    renderer({});

    // expect(1).toBe(1); // When using dummy assertion jest wont complain
  });
});



Generic type for key in array.reduce

Have a array of object and by reduce I transform it to {key: [{}], [{}]}, key is date of array
like: [{date: ’22-02-06-00:55:66′, name: ‘one’}…] and result will be {22-02-06: [{}]} all items what includes to this date. My function is:

export function getObjectOfArrayByKey<T, K extends keyof T>(
  data: T[],
  key: K,
  timeFormat: string,
  dateFormat: string,
): { [key in keyof T]: T[] } {
  return data.reduce((acc, item) => {
    const time = dayjs(item[key]).format(timeFormat);
    const date = dayjs(item[key]).format(dateFormat);

    const equalToDate = {
      time,
      ...item,
    };

    acc[date] = acc[date] || [];

    acc[date].push(equalToDate);

    return acc;
  }, {} as { [key in keyof T]: T[] & { time: string } });
}

But in constant equalToDate I add new value “time” and I don’t know how add to type script this new type for time.

I think problem is here, I need add new property for type of new array

{ [key in keyof T]: T[] & { time: string }

How can I stop javascript from defining something as true or false before the function is called?

I have some javascript code here for a website (not one I’m gonna publish, I’m just learning) and I’m trying to check if the user input on the page matches a string, but when the if statement executes, it returns “false” rather than “true”, even though if I open my browser’s devtools and print the boolean the same way I get it in the if statement, it returns “true”!
I think it’s defining it as true or false as soon as the page loads.
I’m running the function with an href, and the first thing in the html file’s body is calling the javascript file, but why does it not define it as true or false upon the function being called? How can I fix this issue?
Should I call the script in the href somehow?
Sorry if this is an obvious issue, I’m new to javascript.

I expected it to check the condition when the if statement was executed, but instead it checks the condition as soon as the page opens so theres not even time to type anything.

Cross origin requests are only supported for protocol schemes: (…) when accessing local file

I’m building a Text-To-Speech Website using Google API.

Server-Side works fine, now I started building frontend where I currently have a input field for the message that should be converted into mp3, as well as a button.

This is my frontend:

<!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>Document</title>
</head>
<body>
    
    <input type="text" id="textInput">
    <button id="convertButton" onclick="convertTTS()">Konvertieren</button>

    <script>
        function convertTTS() {
            // Creating Our XMLHttpRequest object 
            var url = 'localhost:5500/convertTextToMp3';
            var xhttp = new XMLHttpRequest();

            // Making our connection  
            xhttp.open("GET", url, true);

            // function execute after request ist successful
            xhttp.onreadystatechange = function() {
                if (this.readyState == 4 && this.status == 200) {
                    console.log("Es funktioniert");
                }
            };

            // Sending our request
            xhttp.send();
        }
    </script>
</body>
</html>

and this is my server:

const textToSpeech = require("@google-cloud/text-to-speech")

// dot env
require("dotenv").config()
const fs = require("fs")
const util = require("util")
const client = new textToSpeech.TextToSpeechClient()
const express = require('express');
const app = express();
const cors = require('cors')


async function convertTextToMp3(){
    console.log("Yippie! It works!");

    const text = "Example Text"

    const request = {
        input: {text:text}, 
        voice: {languageCode:"en-US", ssmlGender:"Neutral"},
        audioConfig:{audioEncoding:"MP3"}
    }

    const [response] = await client.synthesizeSpeech(request)

    const writeFile = util.promisify(fs.writeFile)

    await writeFile("output.mp3", response.audioContent, "binary")

    console.log("Text to Speech has completed. Audio File has been saved.")
}

app.use(cors());

app.get('/convertTextToMp3', (req, res) => {
    //convertTextToMp3();
    res.send('Function called successfully!');
});

app.listen(5500, () => console.log('Server started on port 5500'));

The server is running using nodejs and I’m using express for the endpoint.

I start the frontend using the LiveServer extension from VSCode.

I also added Cors (installed using npm).

What I tried is different uses of cors like:

app.use(corse());

or

app.use(cors({
    origin: '*'
    , methods: ['GET','POST','DELETE','UPDATE','PUT','PATCH']
}));

I also tried to include it into app.get directly:

app.get('/convertTextToMp3', cors(), (req, res) => {
    //convertTextToMp3();
    res.send('Function called successfully!');
});

I also tried to call http://127.0.0.1 instead of localhost here:

var url = 'localhost:5500/convertTextToMp3';

but then I get a 404 issue from “http://127.0.0.1:5500/convertTextToMp3”:
enter image description here

What I expect to happen is, that I get a “Yippie! It works!” output on the console.

The actual result is this error:

enter image description here

Why my question is different: So far I’ve seen multiple different questions to this topic, but mostly users are using something like file:/ which I don’t use.

Other questions I found are using specific frameworks which I don’t use.

Could not find a declaration file for module ‘vue-email-editor’ in VueJs

I installed vue-email-editor in my project, But I got the below error when trying to use vue-email-editor in my Laravel vuejs project:

Could not find a declaration file for module ‘vue-email-editor’. ‘/Applications/XAMPP/xamppfiles/htdocs/textiletoday/node_modules/vue-email-editor/dist/vue-email-editor.common.js’ implicitly has an ‘any’ type.
Try npm i --save-dev @types/vue-email-editor if it exists or add a new declaration (.d.ts) file containing declare module 'vue-email-editor';ts(7016).

When I run this “npm i –save-dev @types/vue-email-editor” I got the below error

npm ERR! code E404

npm ERR! 404 Not Found – GET https://registry.npmjs.org/@types%2Fvue-email-editor – Not found

npm ERR! 404

npm ERR! 404 ‘@types/vue-email-editor@*’ is not in this registry.

npm ERR! 404

npm ERR! 404 Note that you can also install from a

npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:

npm ERR! /Users/user/.npm/_logs/2023-02-23T06_35_02_174Z-debug-0.log

why my vercel in nextjs application not showing anything?

Basically, my problem is that my nextjs application is just a pure blank “gray” page website, and I don’t know why.

I already did the npm run build for building the application of nextjs which the folder will be created in .next right?

And this is what my project looks like in my folder VScode.

enter image description here

And I don’t know why even I already it in my github and then try to deploy it in vercel but it doesn’t work? Can anyone explain me why? Is it have something to with environment?

Note my project is only a CRUD with API that’s it

and as you see its empty here.

and the link is here

https://nextjs-crud-api.vercel.app/

enter image description here

Keep css class on Quill clipboard.dangerouslyPasteHTML

I use the Quill Text Editor, and i use the method clipboard.dangerouslyPasteHTML for paste HTML in the editor, but if i send this :

let content= '<p class="perso-class">test</p>'; quill.clipboard.dangerouslyPasteHTML(content)

Editor contents show as: <p>test</p>, i want to keep the custom class CSS.

Thank you for your help !

When using expo to build eas, Android keeps giving me an error

I set package.json as below, but I get an error. In ios, the build was successful, but the url image is not coming out. What should I do?

{ "name": "expo-zazero-app", "version": "1.0.0", "scripts": { "start": "expo start --dev-client", "android": "expo run:android", "ios": "expo run:ios", "web": "expo start --web" }, "dependencies": { "@actbase/react-daum-postcode": "^1.0.4", "@expo/webpack-config": "^0.17.2", "@ouroboros/react-native-picker": "^0.2.1", "@powerdesigninc/react-native-prompt": "^0.1.2", "@react-native-async-storage/async-storage": "~1.17.3", "@react-native-community/checkbox": "^0.5.14", "@react-native-community/datetimepicker": "6.5.2", "@react-native-picker/picker": "2.4.8", "@react-navigation/material-top-tabs": "^6.5.1", "@react-navigation/native": "^6.0.16", "@react-navigation/stack": "^6.3.7", "@tanstack/react-query": "^4.24.4", "accordion-collapse-react-native": "^1.1.1", "AsyncStorage": "^0.1.5", "axios": "^1.2.1", "dropdown-picker": "^0.0.1", "expo": "^47.0.0", "expo-checkbox": "~2.2.2", "expo-clipboard": "~4.0.1", "expo-font": "~11.0.1", "expo-image-picker": "~14.0.2", "expo-modules-autolinking": "~1.0.0", "expo-splash-screen": "~0.17.5", "expo-status-bar": "~1.4.2", "expo-updates": "~0.15.6", "http-proxy-middleware": "^2.0.6", "https-proxy-agent": "^5.0.1", "iamport-react-native": "^2.0.4", "npm": "^9.2.0", "query-string": "^8.1.0", "react": "18.0.0", "react-daum-postcode": "^3.1.1", "react-dom": "18.1.0", "react-native": "0.69.6", "react-native-animatable": "^1.3.3", "react-native-bootstrap": "^0.1.0", "react-native-bootstrap-styles": "^4.5.0-r", "react-native-calendar-strip": "^2.2.6", "react-native-calendars": "^1.1292.0", "react-native-collapsible": "^1.6.0", "react-native-dropdown-picker": "^5.4.3", "react-native-dropdown-select-list": "^2.0.4", "react-native-fast-image": "^8.6.3", "react-native-gesture-handler": "~2.8.0", "react-native-image-slider-banner": "^1.0.3", "react-native-image-slider-box": "^2.0.7", "react-native-keyboard-aware-scroll-view": "^0.9.5", "react-native-modal-datetime-picker": "^14.0.1", "react-native-pager-view": "6.0.1", "react-native-paper": "^5.0.1", "react-native-picker": "^4.3.7", "react-native-picker-select": "^8.0.4", "react-native-render-html": "^6.3.4", "react-native-safe-area-context": "4.4.1", "react-native-screens": "~3.18.0", "react-native-svg": "13.4.0", "react-native-svg-transformer": "^1.0.0", "react-native-tab-view": "^3.3.4", "react-native-vector-icons": "^9.2.0", "react-native-web": "~0.18.7", "react-native-webview": "11.23.1", "react-native-wrapped-text": "^1.2.2", "sharp-cli": "^4.1.0", "yarn": "^1.22.19" }, "devDependencies": { "@babel/core": "^7.19.3" }, "proxy": "http://49.50.162.86:80" }