JS simple christmas tree on one loop

I’m trying to make one loop christmas tree using string.repeat method.

  let Height = 6;
  let Star = "*";

  for (let i = 0; i < Height; i++) {
    for (let j = 0; j <= i; j++) {
      document.write(Star);
    }
    document.write("<br>");
  }

I’ve created it on 2 loops, but don’t know how to do it on a single one. Thank you for help.

CastError: Cast to ObjectId failed for value “XXXXXXXXXX” (type string) at path “_id” for model “User” for passport-linkedin-oauth2

Getting the above error when trying to authenticate a new user using LinkedIn’s oAuth 2.0. It looks like I’m getting passed a 10 digit ObjectId instead of a 12 or 24 character id…

passport.use(new LinkedInStrategy({
  clientID: process.env.LI_ID,
  clientSecret: process.env.LI_SECRET,
  callbackURL: "http://localhost:3000/auth/linkedin/think-it",
  scope: ['r_emailaddress', 'r_liteprofile'],
  state: true
}, function(accessToken, refreshToken, profile, done) {
  // asynchronous verification, for effect...
  process.nextTick(function () {
    // To keep the example simple, the user's LinkedIn profile is returned to
    // represent the logged-in user. In a typical application, you would want
    // to associate the LinkedIn account with a user record in your database,
    // and return that user instead.
    return done(null, profile);
  });
}));

I’m getting hung up at:

passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(err, user);
  });
});

How does hidden classes really avoid dynamic lookups?

So we have all heard that v8 uses the thing called hidden classes where when many objects have the same shape, they just store a pointer to the shape struct which stores fixed offsets. I have heard this a million time, and I very much get how this reduces memory usage by A LOT (not having to store a map for each one is amazing) and potentially because of that a bit faster performance.

However I still don’t understand how it avoids dynamic lookup. The only thing I have heard is storing a cache between a string (field name) and a fixed offset, and checking it every time, but if there’s a cache miss (which is likely to happen) there will still be a dyanmic lookup.

Everyone says that this is almost as fast as C++ field access (which are just a mov instruction usually), however this 1 field access cache isn’t even close.

Look at the following function:

function getx(o)
{
    return o.x;
}

How will v8 make the access of the x field so fast and avoid dynamic lookup?

Calculate price from width and height

The question is divided into 2 parts.

1. How to structure the data in the json array

2. How to calculate the price from the json array

I need to store the price data inline in HTML as JSON, as AJAX requests to the server are too slow/heavy.

The data are stored as serialized strings in a database. This is added to the database from CSV file uploads. The CSV files looks like below.

      50    100    150    200    250
20    70     90    110    130    150
30    90    110    130    150    170
40    110   130    150    170    190
50    130   150    170    190    210
60    150   170    190    210    230

If you enter 100 in width and 40 in height, the price should be 130.

If you enter 170 in width and 52 in height the price should be 210.

If column or row is not found, it should round up to next column or row.

  1. What is the best way to store this as JSON inline, if you need to calculate the price based on width and heigth?

  2. How would you calculate the price, based on user input width and height?

I am not looking for specific code, just suggestions on the JSON structure and how to calculate from this.

Incrementing DynamoDB value using AWS SDK v3

I’m attempting to migrate my v2 Lambdas to v3, and I’m having some trouble incrementing a value. Here’s my v2 method:

  const params = {
    TableName: process.env.USER_TABLE_NAME!,
    Key: { UID },
    UpdateExpression: 'SET #numRatings = #numRatings + :increment',
    ExpressionAttributeNames: {
      '#numRatings': 'numRatings'
    },
    ExpressionAttributeValues: {
      ':increment': 1
    },
    ReturnValues: 'ALL_NEW'
  };

  return await DB.update(params).promise();

v3 method:

  const params = {
    TableName: process.env.USER_TABLE_NAME!,
    Key: {
      UID
    },
    UpdateExpression: 'set numRatings = numRatings + :increment',
    ExpressionAttributeValues: {
      ':increment': 1
    },
    ReturnValues: 'ALL_NEW'
  } as unknown as UpdateItemCommandInput;

  try {
    const response = await dbClient.send(new UpdateItemCommand(params));
    console.log('response', response);
  } catch (error) {
    console.error('error', error);
  }

I’m using TypeScript and VS Code gives this error:

Types of property 'Key' are incompatible.
    Type '{ UID: string; }' is not comparable to type '{ [key: string]: AttributeValue; }'.
      Property 'UID' is incompatible with index signature.
        Type 'string' is not comparable to type 'AttributeValue'

CloudWatch gives this unhelpful error:

Cannot read property ‘0’ of undefined

I’m really confused as, as far as I can tell I have followed the documentation properly, their equivalent of “params” is defined as so:

export const params = {
  TableName: "TABLE_NAME",
  Key: {
    primaryKey: "VALUE_1", // For example, 'Season': 2.
    sortKey: "VALUE_2", // For example,  'Episode': 1; (only required if table has sort key).
  },
  // Define expressions for the new or updated attributes
  UpdateExpression: "set ATTRIBUTE_NAME_1 = :t, ATTRIBUTE_NAME_2 = :s", // For example, "'set Title = :t, Subtitle = :s'"
  ExpressionAttributeValues: {
    ":t": "NEW_ATTRIBUTE_VALUE_1", // For example ':t' : 'NEW_TITLE'
    ":s": "NEW_ATTRIBUTE_VALUE_2", // For example ':s' : 'NEW_SUBTITLE'
  },
  ReturnValues: "ALL_NEW"
};

My apologies if that’s too many code examples but I wanted to be thorough. UID is a string. Thank you in advance for any help

Method not getting triggered on click React

I am trying to render a popup when a card is clicked. My problem is that I can’t get the showPopup function running on click of the card component.

//... all required imports 

class App extends Component {
  constructor() {
    super();

    this.state = {
      monsters: [],
      searchField: ''
    };
  }

  componentDidMount() {
    // Fetches monsters and updates the state (working fine)
  }

  showPopup = () => {
    console.log(2);
  };

  render() {
    const { monsters, searchField } = this.state;
    const filteredMonsters = monsters.filter(monster => monster.name.toLowerCase().includes(searchField.toLowerCase()));

    return (
      <div className="App">
        <CardList className="name" monsters={filteredMonsters} showPopup={e => this.showPopup(e)} />
      </div>
    );
  }
}

Following is the code for my CardList component

import React from 'react';
import { Card } from '../card/card.comp';
import './card-list.styles.css';

export const CardList = props => {
    return (
      <div className="card-list">
        {props.monsters.map(monster => (
          <Card key={monster.id} monster={monster} onClick={props.showPopup} />
        ))}
      </div>
    );
};

The onclick function above is not working as expected. Please help me find out the problem.

CSS Rotation controlled by scrolling speed with jQuery

I’m trying to rotate two objects by scrolling horizontally. The scrolling is controlled by the mousemovement. When the pointer goes right, the objects rotate left, and the other way round. The faster the mouse moves, the more the object rotates.
When the mouse pointer stops for 30ms I want the object to commute slowly with a keyframe that is defined by the current mouse/scroll-speed.
The rotation during the scrolling works fine, but when I added the keyFrame-Function to commute the object, it all went weird.
It starts to rotate after I stop the mouse and it rotates up to 3 times and not in the shortest way.

Maybe someone knows why that is and how to dissolve this problem?

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Rotating Objects</title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src='scripts/jquery.keyframes.js'></script>
  <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
  <style>
  body {
    overflow: hidden; /* Hide scrollbars */
  }

  .draggable, #draggable2 { 
    border: 2px solid #000; 
    width: 100px; 
    height: 200px;
  }
  #containment-wrapper { 
    width: 400px; 
    height:400px; 
    border:2px solid #000;
    left: 10%; 
    bottom: 10px; 
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  #containment-wrapper_2 { 
    width: 400px; 
    height:400px; 
    border:2px solid #000; 
    left: 30%; 
    bottom: 10px; 
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  #stage { 
    width: 400vh; 
    height:80vh; 
    border: 1px solid #000; 
    position: relative; 
  }
  </style>
  <script>

  $(document).ready(function() {

  var supportedFlag = $.keyframe.isSupported();

  //set CSS Rotation Degree
  function setRotationDegree(obj, angle) {
    obj.css({
      '-moz-transform' : 'rotate(' + angle + 'deg)',
      '-ms-transform' : 'rotate(' + angle + 'deg)',
      '-o-transform' : 'rotate(' + angle + 'deg)',
      'transform' : 'rotate(' + angle + 'deg)',
      'transition' : 'transform .3s ease-in'
    });
  }

  //set Keyframe Values for commute after stop
  function setRotateKeyframes(keyName, angle) { 
      //angle = angle * -1;
      $.keyframe.define([{
        name: keyName,
        '0%': {'-moz-transform' : 'rotate(' + angle + 'deg)',
                '-ms-transform': 'rotate(' + angle + 'deg)',
                '-o-transform' : 'rotate(' + angle + 'deg)',
                'transform' : 'rotate(' + angle + 'deg)'
              },
        '25%': {'-moz-transform' : 'rotate(' + (angle * -0.9) + 'deg)',
                '-ms-transform': 'rotate(' + (angle * -0.9) + 'deg)',
                '-o-transform' : 'rotate(' + (angle * -0.9) + 'deg)',
                'transform' : 'rotate(' + (angle * -0.9) + 'deg)'
              },
        '50%': {'-moz-transform' : 'rotate(' + (angle * 0.25) + 'deg)',
                '-ms-transform': 'rotate(' + (angle * 0.25) + 'deg)',
                '-o-transform' : 'rotate(' + (angle * 0.25) + 'deg)',
                'transform' : 'rotate(' + (angle * 0.25) + 'deg)'
              },
        '75%': {'-moz-transform' : 'rotate(' + (angle * -0.1) + 'deg)',
                '-ms-transform': 'rotate(' + (angle * -0.1) + 'deg)',
                '-o-transform' : 'rotate(' + (angle * -0.1) + 'deg)',
                'transform' : 'rotate(' + (angle * -0.1) + 'deg)'
              },
        '100%': {'-moz-transform' : 'rotate(0deg)',
                '-ms-transform': 'rotate(0deg)',
                '-o-transform' : 'rotate(0deg)',
                'transform' : 'rotate(0deg)'
              }
      }]);
    }

    var docWidth = $('body').width(),
    slidesWidth = $('#stage').width(),
    rangeX = slidesWidth - docWidth,
    $div = $('#stage');

    $(window).on('resize', function() {
      var docWidth = $('body').width(),
      slidesWidth = $('#stage').width(),
      rangeX = slidesWidth - docWidth;
    })
  
    //variable for if mouse-doesnt-move check
    var timeout = null;

    //variable for scrolling direction check
    var lastScrollLeft = 0;

    $(document).mousemove(function(e) {
      var mouseX = e.pageX,
        percentMouse = mouseX / docWidth,
        offset = percentMouse * slidesWidth - percentMouse * docWidth;

      //check if left or right direction
      var sl = offset;
      var leftOrRight = 0;
      //speed of mousemovement
      var scrollSpeed = offset - lastScrollLeft;

      //Maximum 180degree rotate not necessary?
      scrollSpeed = (scrollSpeed * -30);

      setRotationDegree($('.draggable'), scrollSpeed);

      lastScrollLeft = sl;

      //Rotate back when mouse didn't move for 30ms
      clearTimeout(timeout);

      timeout = setTimeout(function() {
        //setRotationDegree($('.draggable'), 0);

        //THIS BRINGS THE TROUBLE
        setRotateKeyframes('swingRotate', (scrollSpeed));
        $('.draggable').playKeyframe(
          'swingRotate 3s ease-in-out both',
        );
      }, 30);

      $div.css({
        '-webkit-transform': 'translate3d(' + -offset + 'px,0,0)',
        'transform': 'translate3d(' + -offset + 'px,0,0)'
      });
    });

    //Object draggable
    $( ".draggable" ).draggable({ 
      revert: true,
      containment: "#containment-wrapper",
    });
    $( "#draggable2" ).draggable({ 
      revert: true,
      containment: "#containment-wrapper_2",
    });

  });

  </script>
</head>
<body>
<div id="stage">
  <div id="containment-wrapper">
    <div id="draggable" class="draggable">
      <p id="distance"></p>
    </div>
  </div>

  <div id="containment-wrapper_2">
    <div id="draggable2" class="draggable">
      <p id="distance"></p>
    </div>
  </div>
</div>
 
</body>
</html>

Different CSS styles for each HTML tab

Developing a website using Django (irrelevant, really), and have been toying with the implementation of tabs versus a navbar, as I want certain pages to update when selected without completely redirecting to a new page, or refreshing it entirely. For this to be useful, however, each tab would require its own format of CSS, as each page that’s being displayed is inherently different from every other (lets say there are 4 tabs, each tab would display completely different page, ranging from an image library to just text); my question is, how would this theoretically be done, as I have found very little documentation on the matter, other than people claiming “its possible” when asked.

<div class="wrapper">
  <div class="tabs">
    <div class="tab">
      <input type="radio" name="css-tabs" id="tab-1" checked class="tab-switch">
      <label for="tab-1" class="tab-label">Tab One</label>
      <div class="tab-content">sample text</div>
    </div>

Based on the input above, I would assume you could list multiple entries and modify each one using the id=”tab-1″ modifier within CSS, something similar to .tab-1, .tab-2, .tab-3, to update each selection individually, however, this does not seem to work when attempted. I have also attempted to incorporate separate CSS files, which would be the optimal result, however, they do not seem to load properly when incorporated, and I have found little documentation on implementing multiple CSS files in the way that is required for differential tabs.

(Alternatively, is there a way to obtain this format using a navbar, whereas instead of a link to a separate page, it displays the change within the body, similar to a tab modifying its container; ultimately, I want the display to be similar to that of a navbar.)

Thanks for your help.

Puppeteer / POST Request

I’m trying now since over 48 hours and googelt almost the whole web. My problem is that when use puppeteer the POST Request is not working – I tried many websites but the POST Form Action is not working. Can somebody help me?

File test.js
Usage: node test.js

const puppeteer = require('puppeteer');
const randomUseragent = require('random-useragent');
const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36';

(async () => { const browser = await puppeteer.launch({ args: ['--no-sandbox'] }) // headless: true,

const page = await browser.newPage()
    
await page.setViewport({
    width: 1920 + Math.floor(Math.random() * 100),
    height: 3000 + Math.floor(Math.random() * 100),
    deviceScaleFactor: 1,
    hasTouch: false,
    isLandscape: false,
    isMobile: false,
});

const userAgent = randomUseragent.getRandom();
const UA = userAgent || USER_AGENT;

await page.setUserAgent(UA);
await page.setJavaScriptEnabled(true);
await page.setDefaultNavigationTimeout(0);

await page.setRequestInterception(true);
page.on("request", interceptedRequest => {

        var data = {
            
            "method": "POST",
            "postData": "URLz=VIDEOURL"
        };
        interceptedRequest.continue(data);
    });
    
const response = await page.goto('https://fdown.net/download.php')
 //const responseBody = await response.text();
 
await page.screenshot({ path: 'affe.png', fullPage: true })
await browser.close()

})()

TypeError: this.cliEngineCtor is not a constructor

I’m running a react app using a yarn package manager. I’m getting the aforementioned ESLint error. I have tried the following to fix it:

  1. Deleted package-lock.json and node modules and installed yarn and ran yarn init
  2. Modified the eslint-plugin.js file to include at the top of the file:

I used both of these at different times to no avail:

   this.CliEngineCtor = require(this.basicPath).CLIEngine;
   this.CliEngineCtor = require(this.basicPath).CLIEngineCtor;

Pertinent package.json entry:

{
  "name": "react-millionaire-quiz",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "^5.0.0",
    "web-vitals": "^2.1.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "eslint": "^8.7.0"
  },

I tried changing the eslint to lower versions, but that just created other problems breaking other dependencies and creating other errors.

How can this be fixed, or do I have to disable ESLint?

Loop is not incrementing

I am new to javascript.

I have to create a function that returns the next multiples of 5 based on a given number.But my loop repeats the information, it doesn´t increment the result.What am I doing wrong?

function proS (num, mult){
    let arr = []

for (var i = 1; i <= mult; i ++){
arr.push(Math.ceil(num / 5) * 5)
}
return arr
}

proS(6,4)

returns [10,10,10,10]

Execution Timed Out (12000 ms): How can I optimize JS kata to run faster? [Upside-Down Numbers – Challenge Edition]

    function upsideDown(x, y) {
      const list = ["0", "1", "6", "8", "9"];
      let count = 0;
      for (let i = parseInt(x); i <= parseInt(y); i++) {
        let curr = i.toString().split("");
        let upsideDownCurr = "";
        if (
          !curr.every(function (x) {
            return list.includes(x);
          })
        )
          continue; // Skips if number includes non-upDown num
        for (let j = 0; j < curr.length; j++)
          if (curr[j] === "6") upsideDownCurr = "9" + upsideDownCurr;
          else if (curr[j] === "9") upsideDownCurr = "6" + upsideDownCurr;
          else upsideDownCurr = `${curr[j]}` + upsideDownCurr;
        if (upsideDownCurr === curr.join("")) count++;
      }
      return count;
    }

Input:

Your function will receive two strings, each comprised of digits representing a positive integer. These two values will represent the upper and lower bounds of a range.
Output:

Your function must return the number of valid upside down numbers within the range of the two input arguments, including both upper and lower bounds.
What is an Upside-Down Number?

An upside down number is an integer that appears the same when rotated 180 degrees, as illustrated below.

This works fine untill
Test.assertEquals(upsideDown('100000','12345678900000000'),718650)
any idea how to optimize the code?

Regex for ISO8601 temporal duration but only with minutes and seconds

I’m attempting to write Regex to match the ISO8601 standard for temporal durations, but only where PT and M or S are valid.

So far I have found a full example of ISO8601 regex but it is more complex than I need. I need match durations like the following:

  • PT7S
  • PT10M50S
  • PT150S

Essentially I want the Regex to always check that:

  • capitalised PT is at the beginning of the string
  • M is preceded by a whole number
  • S is preceded by a whole number
  • M comes before S

My attempt so far:

  • capitalised PT at the beginning = ^PT
  • M preceded by a whole number = [0-9]+M – except this allows something like 10.5M because the 5M counts
  • S preceded by a whole number = same as above
  • M comes before S. Again no idea!

I’m really stuck on trying to figure this out, I’ve been trying to get each part to match so I could try and combine them all later but I can’t get over the first hurdle.

addEventListener: click just one element of a bunch of elements

I’m beginner and have trouble with something in JS that might be simple to solve.

I made a quiz based on a NetNinja Udemy course, and I want the submit button to be enabled just when the user clicks on any answer option, and not before, so that he/she can’t send a totally empty quiz.

The quiz has 4 questions with 2 options each, and I found this way…

const input_a = document.getElementById("q1a");
const input_b = document.getElementById("q1b");


button.disabled = true;




input_a.addEventListener('click', () => {
    button.disabled = false;

});

input_b.addEventListener('click', () => {
    button.disabled = false;

});

…to enable the button when the user clicks on any of the two options of the first question (ids: q1a & q1b) Following this logic, there’d also be q2a, q2b, q3a, q3b, q4a & q4b..

As there is a way to include all the answers in one JS element, what should I do in the event function to say “when you click any of this 8 options, enable the button”? Because everything I tried only makes the function work if I click all the buttons, which is obviously impossible in a Quiz .

Thank you! 🙂