How do i replace CR LF with a break

Could someone/anyone please explain why the following replace doesnt work?

var s = “Unable to update the property, error is:rnrnProcessRequestsAsync”;

s = s.replace(/rn/g, "<br />");

(after s hasn’t been changed)

I’ve tried various options, eg, gms, gm, gs – none of which work.

Js repeater with bootstrap select2 which is rended using twig is not working

This is my twig select render in a form:

<div id="productList" data-form-inputs="{{ form.restockQueueProductVariants.children[0].children|length }}">
    <div data-repeater-list="productList">
        {% for i in 0..form.restockQueueProductVariants|length - 1 %}
            <div data-repeater-item>
                <div class="row g-5 my-3">
                    <div class="col-md-8">
                        {{ form_label(form.restockQueueProductVariants[i].productVariant, 'admin.restock_queue.supplierName'|trans, {'label_attr': {'class': 'form-label'}}) }}
                        <div class="input-group {% if form.restockQueueProductVariants[i].productVariant.vars.errors|length > 0 %}has-validation{% endif %}">
                            {{ form_widget(form.restockQueueProductVariants[i].productVariant, {'attr': {'class': 'form-select' ~ (form.restockQueueProductVariants[i].productVariant.vars.errors|length > 0 ? ' is-invalid' : ''), 'data-rich-content': 'select', 'data-index-id': 'restock_queue_restockQueueProductVariants__index__productVariant'}}) }}
                            <div class="invalid-feedback">
                                {{ form_errors(form.restockQueueProductVariants[i].productVariant) }}
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3 d-flex align-items-center">
                        <div>
                            {{ form_label(form.restockQueueProductVariants[i].quantity, 'admin.restock_queue.supplierName'|trans, {'label_attr': {'class': 'form-label'}}) }}
                            <div class="input-group {% if form.restockQueueProductVariants[i].quantity.vars.errors|length > 0 %}has-validation{% endif %}">
                                {{ form_widget(form.restockQueueProductVariants[i].quantity, {'attr': {'class': 'form-control' ~ (form.restockQueueProductVariants[i].quantity.vars.errors|length > 0 ? ' is-invalid' : ''), 'min': '1', 'data-index-id': 'restock_queue_restockQueueProductVariants__index__quantity'}}) }}
                                <div class="invalid-feedback">
                                    {{ form_errors(form.restockQueueProductVariants[i].quantity) }}
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-1 d-flex align-items-center justify-content-center">
                        <a href="javascript:;" data-repeater-delete class="mt-8">
                            <i class="bi bi-trash fs-1 text-danger"></i>
                        </a>
                    </div>
                </div>
            </div>
        {% endfor %}
    </div>
    <div class="mt-5">
        <a href="javascript:;" data-repeater-create class="btn btn-outline"><i class="bi bi-plus-lg fs-3"></i> Add varaints</a>
    </div>
</div>

I have this js to use select2 with Form Repeater Bootstrap:

const productOptionsFormat = (item) => {
    if (!item.id) {
        return item.text;
    }

    var data = JSON.parse(item.text);
    var span = document.createElement('span');
    var template = '';
    template += '<div class="d-flex align-items-center">';
    template += '<img src="' + data.image + '" class="rounded-circle h-40px me-3"/>';
    template += '<div class="d-flex flex-column">'
    template += '<span class="fw-bold">' + data.title + '</span>';
    template += '<span class="text-muted">' + data.sku + '</span>';
    template += '</div>';
    template += '</div>';

    span.innerHTML = template;

    return $(span);
}

$('#productList').repeater({
    initEmpty: false,
    show: function () {
        $(this).slideDown();
        // Re-init select2
        $(this).find('[data-rich-content="select"]').select2({
            templateSelection: productOptionsFormat,
            templateResult: productOptionsFormat
        }).val($(this).find('[data-rich-content="select"] option:first').val()).trigger('change');
    },
    hide: function (deleteElement) {
        $(this).slideUp(deleteElement);
    },
    ready: function(){
        // Init select2
        $('[data-rich-content="select"]').select2({
            templateSelection: productOptionsFormat,
            templateResult: productOptionsFormat
        });
    }
});

Problem:
On page rendered, the first productVariant is rended correctly. But when I add a new row to form, the previous one’s productOptionsFormat goes back to simple text, but the new one’s is rended correctly….

I dont know why prevous one is rended back to json format text.

Uncaught TypeError: (destructured parameter).profile is null

I’m encountering a TypeError when using map function in TypeScript. I’m mapping over an array of objects and rendering their properties using destructuring syntax. In the object the profile property might be null and I’ve already handled the JSX syntax just like below:

{`${last_name} ${middle_name} ${first_name}` || ""}

What I have tried. However there is still TypeError this time null has no properties.

              (
                {
                  id,
                  email,
                  role: { role },
                  profile: {
                    first_name,
                    middle_name,
                    last_name,
                    address_details: { address_line_one, address_line_two } = {},
                  } = {},
                  date_joined,
                  is_active,
                }: User = {},
                index
              )

@types/user.d.ts

export interface User {
  id: number;
  email: string;
  role: Role;
  profile: Profile;
  date_joined: string;
  is_active: boolean;
}

interface Role {
  role: string;
}

interface Profile {
  first_name?: string;
  middle_name?: string;
  last_name?: string;
  address_details: AddressDetails;
}

interface AddressDetails {
  address_line_one?: string;
  address_line_two?: string;
}

export type UserList = User[];

In my Node JS Express server, I got this error where it says “Route.post() requires a callback function but got a [object Undefined]”

The whole error message says:
D:directorynode_modulesexpresslibrouterroute.js:216
throw new Error(msg);
^

Error: Route.post() requires a callback function but got a [object Undefined]
at Route. [as post] (D:directorynode_modulesexpresslibrouterroute.js:216:15)
at proto. [as post] (D:directorynode_modulesexpresslibrouterindex.js:521:19)
at Object. (D:directoryroutessearchRoutes.js:7:8)
at Module._compile (node:internal/modules/cjs/loader:1218:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
at Module.load (node:internal/modules/cjs/loader:1081:32)
at Module._load (node:internal/modules/cjs/loader:922:12)
at Module.require (node:internal/modules/cjs/loader:1105:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object. (D:directoryindex.js:7:22)

My index.js is structured like this:

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const db = require('./database/db');
const roleRoutes = require('./routes/roleRoutes');
const userRoutes = require('./routes/userRoutes');
const searchRoutes = require('./routes/searchRoutes');


const app = express();
app.use(bodyParser.json());
app.use(cors());

const PORT = process.env.PORT;

app.use('/search', searchRoutes);
app.use('/', userRoutes); // Assuming userRoutes handles '/' route
app.use('/', roleRoutes); // Assuming roleRoutes handles '/' route

app.get('/', (req, res) => {
    res.json({Messsage: 'NCF Repository Backend Running!'});
});

// Define a catch-all route handler for undefined routes
app.use((req, res) => {
    res.status(404).json({ message: 'Route not found' });
});

app.listen(PORT, ()=> {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Also, my searchRoutes is structured like this:

const express = require('express');
const router = express.Router();

const fuseController = require('../controllers/fuseSearch');
const fuzzballController = require('../controllers/fuzzballSearch');

router.post('/fuse', fuseController.fuseSearch);
router.post('/fuzzball', fuzzballController.fuzzballSearch);

module.exports = router;

Therefore, I can’t exactly distinguish what’s happening, as I’ve tried several ways to get rid of that error and nothing works for me.

Chrome Extension `chrome.runtime.sendMessage(…)` connection errors

I am developing a Chrome browser extension and I have a background script that reports the status of long-running tasks to the side panel. It seems to working fine, but when I close the side panel, a bunch of errors start showing up in the debug console.

Uncaught (in promise) Error: Could not establish connection. Receiving end does not…

enter image description here

Side panel script

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    const action = request.action;
    if (action === 'status-update') {
        showStatus(request.status);
    }
});

Background script

async function watchStatus(queue) {
    while(queue.running) {
        chrome.runtime.sendMessage({ action: 'status-update', status: queue.getStatus()});
        await new Promise(r => setTimeout(r, 1000));
    }
};

Two questions

  1. Is there a way to check the connection state before invoking sendMessage?

  2. How could I suppress these errors (without swallowing other exceptions)? It does not appear to cause any issues, but all these Could not establish connection log messages make it difficult to spot actual error logs.

  3. Also, I am assuming the chrome.runtime.sendMessage causing the error but the log has no stack trace or line number just background.js:1

Integration between sequelize model js with controller ts – Node.js

I’m in trouble to make my model, with sequelize, User.js be recognized inside my UserController.ts, in typescript.

In the await User.findAll() part, it shows an error when running on the server, saying User is not defined. I’ve already changed the way I import this require, when I used import to import the User model, the IDE pointed to this error: “The ‘this’ context of type ‘typeof User’ is not assignable to method’s ‘this’ of type ‘ModelStatic’.
Type ‘typeof User’ is not assignable to type ‘NonConstructor’.
The types returned by ‘init(…)’ are incompatible between these types.”

the UserController.ts code, where is the problem:

import { Request, Response } from 'express';
var User = require("../model/User");

export class UserController {
    async getAllUsers(req: Request, res: Response): Promise<Response> {
        // const { id } = req.params;
        try {
          const user = await User.findAll(); // Here is the line appointed with problem
          if (!user) {
            return res.status(404).json({ error: 'Usuário não encontrado' });
          }
          return res.status(200).json(user);
        } catch (error) {
          return res.status(400).json({ error: error.message });
        }
    }
}

The User.js model file:

import Sequelize, { Model } from 'sequelize';
class User extends Model {
  static init(sequelize) {
    super.init(
      {
        name: { type: Sequelize.STRING },
        email: { type: Sequelize.STRING },
        password_hash: { type: Sequelize.STRING },
      },
      {
        sequelize,
        tableName: 'users'
      }
    );
  }
}
export default User;

The route I’ve defined here. The file is UserRoute.js:

router.get('/', async function(req, res) {
    res.render('./user/home', { users: UserController.getAllUsers() });
});

In this file I had managed to use the User model inside it and it worked.

The path of structure of these files are here:

src/route/UserRoute.js
src/model/User.js
src/controller/UserController.ts

My current package.json:

"dependencies": {
    "@types/express": "^4.17.21",
    "ejs": "^3.1.10",
    "express": "^4.19.2",
    "node-fetch": "2",
    "pg": "^8.11.5",
    "pg-hstore": "^2.3.4",
    "sequelize": "^6.37.2"
},
"devDependencies": {
    "@types/jest": "^29.5.12",
    "eslint": "^7.32.0 || ^8.2.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-config-prettier": "^9.1.0",
    "eslint-plugin-import": "^2.25.2",
    "eslint-plugin-prettier": "^5.1.3",
    "jest": "^29.7.0",
    "nodemon": "^3.1.0",
    "prettier": "^3.2.5",
    "sequelize-cli": "^6.6.2",
    "sucrase": "^3.35.0",
    "ts-jest": "^29.1.2"
}

Ideas to solve the problem with User class on typescript UserController class?

hardhat testing for sending ethers function

I am trying to test this smart contract using hardhat:

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract Transaction is Ownable {
    using SafeERC20 for IERC20;
    uint256 public maxTransferAmount = 100 ether;

    event EtherTransferred(address from, address to, uint256 amount, string category);

    constructor(address initialOwner) Ownable(initialOwner) {}

    function setMaxTransferAmount(uint256 _maxTransferAmount) external onlyOwner {
        
        maxTransferAmount = _maxTransferAmount*1000000000000000;
    }

    function transferEther(address payable  to, string memory category) external payable onlyOwner {
        uint amount = msg.value;
        require(amount <= maxTransferAmount, "You have exceeded the maximum transfer amount");
        require(msg.sender.balance >= amount, "You don't have enough balance");

        // Transfer Ether
        (bool success, ) = to.call{value: amount}("");
        require(success, "Ether transfer failed");

        emit EtherTransferred(msg.sender, to, amount, category);
    }
}

and this is my js test:

const { ethers } = require("hardhat");
const { expect } = require("chai");

describe("Transaction contract", function () {
    let transaction;
    let owner;
    let recipient;

    beforeEach(async function () {
        // Set up accounts
        [owner, recipient] = await ethers.getSigners();

        // Deploy the contract
        const Transaction = await ethers.getContractFactory("Transaction");
        transaction = await Transaction.deploy(owner.address); // Use owner.address instead of ownerAddress
        await transaction.deploy();
    });

    it("should transfer Ether successfully within the maxTransferAmount", async function () {
        const initialBalance = await recipient.getBalance();

        // Transfer Ether
        const amountToSend = ethers.utils.parseEther("1"); // 1 Ether
        await transaction.transferEther(recipient.address, "Test Category", { value: amountToSend });

        // Check recipient's balance
        const finalBalance = await recipient.getBalance();
        expect(finalBalance).to.be.gt(initialBalance);
    });

    it("should revert if transfer amount exceeds maxTransferAmount", async function () {
        const amountToSend = ethers.utils.parseEther("101"); // More than maxTransferAmount
        await expect(transaction.transferEther(recipient.address, "Test Category", { value: amountToSend }))
            .to.be.revertedWith("You have exceeded the maximum transfer amount");
    });

    it("should revert if sender doesn't have enough balance", async function () {
        const amountToSend = ethers.utils.parseEther("10");
        await expect(transaction.transferEther(recipient.address, "Test Category", { value: amountToSend }))
            .to.be.revertedWith("You don't have enough balance");
    });
});

each time I run

npx hardhat test 

I get the following error massage:

Transaction contract
    1) "before each" hook for "should transfer Ether successfully within the maxTransferAmount"


  0 passing (739ms)
  1 failing

  1) Transaction contract
       "before each" hook for "should transfer Ether successfully within the maxTransferAmount":
     TypeError: transaction.deploy is not a function
      at Context.<anonymous> (testTransaction.js:16:27)

I tried to hash this line:

        await transaction.deploy();

but I got:

Transaction contract
1) should transfer Ether successfully within the maxTransferAmount
2) should revert if transfer amount exceeds maxTransferAmount
3) should revert if sender doesn’t have enough balance

0 passing (765ms)
3 failing

  1. Transaction contract
    should transfer Ether successfully within the maxTransferAmount:
    TypeError: recipient.getBalance is not a function
    at Context. (testTransaction.js:20:48)

  2. Transaction contract
    should revert if transfer amount exceeds maxTransferAmount:
    TypeError: Cannot read properties of undefined (reading ‘parseEther’)
    at Context. (testTransaction.js:32:43)

  3. Transaction contract
    should revert if sender doesn’t have enough balance:
    TypeError: Cannot read properties of undefined (reading ‘parseEther’)
    at Context. (testTransaction.js:38:43)

Nginx can’t find .js files?

I am attempting to host my Flutter web app on my home server running Nginx. My index.html loads fine when going to the ip, but included .js files aren’t loaded. The request returns 502: GET http://192.168.1.187/test.js

index.html, using test.js as an example.

<!DOCTYPE html>
<html>
<head>
  <!--
    If you are serving your web app in a path other than the root, change the
    href value below to reflect the base path you are serving from.

    The path provided below has to start and end with a slash "/" in order for
    it to work correctly.

    For more details:
    * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

    This is a placeholder for base href that will be replaced by the value of
    the `--base-href` argument provided to `flutter build`.
  -->

  <meta charset="UTF-8">
  <meta content="IE=Edge" http-equiv="X-UA-Compatible">
  <meta name="description" content="A new Flutter project.">

  <!-- iOS meta tags & icons -->
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="apple-mobile-web-app-title" content="plant_monitor">
  <link rel="apple-touch-icon" href="icons/Icon-192.png">
<!-- Favicon -->
  <link rel="icon" type="image/png" href="favicon.png"/>

  <title>plant_monitor</title>
  <link rel="manifest" href="manifest.json">
  <script src="test.js" type="text/javascript"></script>
  <script>
    // The value below is injected by flutter build, do not touch.
    const serviceWorkerVersion = "1760324881";
  </script>
  <!-- This script adds the flutter initialization JS code -->
<!--  <script src="./flutter.js" defer></script> -->
</head>
<body>
  <script>
    console.log(window.location);
  </script>
</body>
</html>

By default, flutter set base href to “/”, but I also tried it with “./” and now without.

nginx default.conf:

# "You are not configured" page, which is the default if another default doesn't exist
server {
        listen 80;
        listen [::]:80;

        set $forward_scheme "http";
        set $server "127.0.0.1";
        set $port "80";

        server_name localhost-nginx-proxy-manager;
        access_log /data/logs/fallback_access.log standard;
        error_log /data/logs/fallback_error.log warn;
        include conf.d/include/assets.conf;
        include conf.d/include/block-exploits.conf;
        include conf.d/include/letsencrypt-acme-challenge.conf;

#       index index.html;
        root /usr/share/nginx/html;
        location ~* .(js|jpg|png|css)$ {}
#       location ~* .(?:css|js|map|jpe?g|gif|png)$ { }

        location / {
                try_files $uri $uri/ /index.html;
        }
}

# First 443 Host, which is the default if another default doesn't exist
server {
        listen 443 ssl;
        listen [::]:443 ssl;

        set $forward_scheme "https";
        set $server "127.0.0.1";
        set $port "443";

        server_name localhost;
        access_log /data/logs/fallback_access.log standard;
        error_log /dev/null crit;
        include conf.d/include/ssl-ciphers.conf;
        ssl_reject_handshake on;

        return 444;
}

The folder usr/share/nginx/html contains index.html, test.js, along with the actual flutter generated files I need when I can figure out how to load test.js.

Textarea with linenumber and scroll

I wanna make a textarea component for code editor.

So i made div for textarea that created dynamically when textarea’s new line has created.

But i can’t make successful scroll function for overflowed lines.

These are my codes below.



import React, { useState, useEffect, useRef } from 'react';

import { create } from 'zustand';

import styles from './CodeEditor.module.scss';



interface CodeStore {

  code: string;

  setCode: (newCode: string) => void;

}



const useCodeStore = create<CodeStore>((set) => ({

  code: '',

  setCode: (newCode) => set({ code: newCode }),

}));



const CodeEditor: React.FC = () => {

  const { code, setCode } = useCodeStore();

  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const lineNumbersRef = useRef<HTMLDivElement>(null);



  useEffect(() => {

    const updateLineNumbers = () => {

      if (textareaRef.current && lineNumbersRef.current) {

        const numberOfLines = textareaRef.current.value.split('n').length;

        lineNumbersRef.current.innerHTML = Array(numberOfLines).fill('<span></span>').join('');

      }

    };



    if (textareaRef.current) {

      textareaRef.current.addEventListener('input', updateLineNumbers);

    }



    updateLineNumbers(); // 초기 업데이트



    return () => {

      if (textareaRef.current) {

        textareaRef.current.removeEventListener('input', updateLineNumbers);

      }

    };

  }, []);



  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {

    if (e.key === 'Tab') {

      e.preventDefault();

      const start = textareaRef.current?.selectionStart || 0;

      const end = textareaRef.current?.selectionEnd || 0;



      setCode((prevCode) => prevCode.substring(0, start) + 't' + prevCode.substring(end));

      textareaRef.current?.focus();

    }

  };



  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {

    const value = e.target.value;

    setCode(value);

  };



  return (

    <div className={styles.CodeEditor}>

      <div className={styles.lineNumbers} ref={lineNumbersRef}>

        {/* 줄 번호가 여기에 동적으로 추가됩니다. */}

      </div>

      <textarea

        ref={textareaRef}

        value={code}

        onChange={handleInputChange}

        onKeyDown={handleKeyDown}

        className={styles.textarea}

      />

    </div>

  );

};



export default CodeEditor;


.CodeEditor {
  border: 2px solid var(--color-white);
  background-color: var(--color-grey);
  padding: 20px 20px 20px 10px;
  display: flex;
  flex-direction: row;
  height: 50vh;
  overflow: hidden;
  line-height: 1.5rem;
}

.textarea {
  height: 9999px;
  line-height: 21px;
  overflow-y: hidden;
  padding: 0;
  border: 0;
  min-width: 500px;
  background-color: var(--color-grey);
  outline: none;
  resize: none;
}

.lineNumbers {
  width: 20px;
  text-align: right;
  height: 9999px;
}

.lineNumbers span {
  counter-increment: linenumber;
}

.lineNumbers span::before {
  content: counter(linenumber);
  display: block;
  color: #506882;
}

What i expected to happen

  • when i press enter key, line number for new line that created at textarea is also created

  • when i scroll textarea, line numbers will be scrolled with textarea at same height

  • maintain indent level same with befor e line

  • like all other code editors(e.g. visual studio code, inteliJ … etc), when i end sentences with { and press enter key, next line will start with indent one more tap(gap)

How to solve this Scrapy HTTP 400 Error that occurs when I try to implement web-scraping using scrapy

Basically, I’m trying to do some scraping with scrapy (still a beginner). However, I don’t know what I’m doing wrong because I keep on getting a Crawled 400 bad request error. Specifically: DEBUG: Crawled (400) <POST https://jobs.ashbyhq.com/api/non-user-graphql?op=ApiJobBoardWithTeams> (referer: https://jobs.ashbyhq.com/quora).
2024-04-13 22:38:21 [scrapy.spidermiddlewares.httperror] INFO: Ignoring response <400 https://jobs.ashbyhq.com/api/non-user-graphql?op=ApiJobBoardWithTeams>: HTTP status code is not handled or not allowed

I tried looking at other stackoverflow posts but none of them helped.

class GreenhouseSpider(scrapy.Spider):
    name = 'greenhouse'
    allowed_domains = ['jobs.ashbyhq.com']
    start_urls = ['https://jobs.ashbyhq.com/api/non-user-graphql?op=ApiJobBoardWithTeams']
    user_agent = 'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36'


    def start_requests(self):
        for url in self.start_urls:
            headers = {
                'Accept': '*/*',
                'Accept-Encoding': 'gzip, deflate, br, zstd',
                'Accept-Language': 'en-US,en;q=0.9',
                'Apollographql-Client-Name': 'frontend_non_user',
                'Apollographql-Client-Version': '0.1.0',
                'Content-Type': 'application/json',
                'Content-Length': '787',
                'Cookie': '_dd_s=rum=1&id=06c05356-744b-493d-b0e1-0acd8af3818c&created=1713050309192&expire=1713051227232',
                'Origin': 'https://jobs.ashbyhq.com',
                'Referer': 'https://jobs.ashbyhq.com/quora',
                'Sec-Ch-Ua': '"Google Chrome";v="123", "Not:A-Brand";v="8", "Chromium";v="123"',
                'Sec-Ch-Ua-Mobile': '?0',
                'Sec-Ch-Ua-Platform': '"Windows"',
                'Sec-Fetch-Dest': 'empty',
                'Sec-Fetch-Mode': 'cors',
                'Sec-Fetch-Site': 'same-origin',
                'Traceparent': '00-0000000000000000637909e68290e363-6158ecaf3752b1aa-01',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36',
                'X-Datadog-Origin': 'rum',
                'X-Datadog-Parent-Id': '7014616656921145770',
                'X-Datadog-Sampling-Priority': '1',
                'X-Datadog-Trace-Id': '7167771167574516579'
            }
            payload = {
                "operationName": "ApiJobBoardWithTeams",
                "variables": {
                    "organizationHostedJobsPageName": "quora"
                },
                "query": "query ApiJobBoardWithTeams($organizationHostedJobsPageName: String!) {n  jobBoard: jobBoardWithTeams(n    organizationHostedJobsPageName: $organizationHostedJobsPageNamen  ) {n    teams {n      idn      namen      parentTeamIdn      __typenamen    }n    jobPostings {n      idn      titlen      teamIdn      locationIdn      locationNamen      employmentTypen      secondaryLocations {n        ...JobPostingSecondaryLocationPartsn        __typenamen      }n      compensationTierSummaryn      __typenamen    }n    __typenamen  }n}nnfragment JobPostingSecondaryLocationParts on JobPostingSecondaryLocation {n  locationIdn  locationNamen  __typenamen}"
            }
            yield scrapy.Request(url=url, method='POST', headers=headers, body=json.dumps(payload), callback=self.parse)```


I tried looking at other stackoverflow posts but none of them helped. 

How to style specific array element while using textContent?

I am able to display value of each array elements in browser for the forEach method. But i am not able to apply , display specific style and also css to specific array element while using texContent. yes i understand textcontent represents “represents text content of specified node” . But i need some other ways to satisfy the requirement. For example in ouput i need value “1.book” should be in green color with 24px,value “2.notepad” should be in orange color with 10px. I tried to find answers online upto my level best but not yet found out the “style specific array element for textContent”. so asking here.

using textContent:

<!DOCTYPE html>
<html>
  <head>
    <title>Hello, World!</title>
    <style>
#mno{
white-space:pre;}
</style>
  </head>
  <body>
      <p id="mno"></p>
      <script>
let abc=['1.book','2.notepad','3.computer'];
abc[0] = '<span style="color:green;border:1px solid green;font-size:40px;">' + abc[0] + '</span>';
abc[1] = '<span style="color:orange">' + abc[1] + '</span>';
abc[2] = '<span style="color:brown">' + abc[1] + '</span>';
let txt = "";
abc.forEach(e=>{txt+=e+"rn";
document.getElementById("mno").textContent = txt;

}
);
        
      </script>
  </body>
</html>

But while Using innerHtML and with some changes everything is working fine.

JavaScript: Checking Object Property Existence – `for` loop vs `.forEach()`

JavaScript: Looping through objects – for loop or .forEach()

I’m working with JavaScript and need to loop through an array of objects. I want to check if a specific property exists within each object. I’m unsure whether to use a traditional for loop or the .forEach() method for this task. Could someone explain the advantages and disadvantages of each approach in this scenario?

Javascript and signup button detect a button press in the sign in form

i’m a beginner on Javascript and Express I apologize in advance for my mistake.

Im try to setup a simple login form which has a button for Signin a new user when the user press this button the user is sent to the signin form where the user can input his data to register register, on this form i put 2 buttons one signup and one cancel but i cant detect any press using express from the sign in form.

i’m looking for some help.

below my code html login:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script defer src="/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="/styles/signin.css">
    <title>Home Page</title>
</head>

 <body>
    
    <div class="container d-flex login-box justify-content-center align-items-center">
        <form class="login-form" action="/submit-form" method="POST">
            <div class="mb-3">
                <h3>Login User</h3>
              <label for="exampleInputEmail1" class="form-label">Email address</label>
              <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp">
              <div id="id_emailHelp" class="form-text">We'll never share your email with anyone else.</div>
            </div>
            <div class="mb-3">
              <label for="exampleInputPassword1" class="form-label">Password</label>
              <input type="password" class="form-control" id="exampleInputPassword1">
            </div>
            
            
            <div class="row">
                <div class="col">
                    <button name="action" value="login" type="submit" class="btn btn-primary w-100">Login</button>
                </div>
                <div class="col">
                    <button name="action" value="signin" type="submit"  class="btn btn-secondary w-100">Sign-in</button>
                </div>
            </div>
           
        </form>
    </div>

 </body>
</html>

the html code for the signup:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script defer src="/js/bootstrap.bundle.min.js"></script>
    <link rel="stylesheet" href="/styles/signin.css">
    <title>Signin</title>
</head>
<body>

   <div class="container d-flex justify-content-center align-items-center">
        <form action="/signin" class=" form-signin rounded border shadow-lg w-50 p-5" method="post">
            <div class="row d-md-flex m-2">
                <h3>Signin</h3>
            </div>

            <div class="row d-md-flex m-2">
                <div class="col-md-6">
                    
                    <label for="inputName" class="form-label">Name</label>
                    <input type="text" class="form-control" id="name_id">
                    
                </div>
                <div class="col-md-6">
                  
                    <label for="inputsurname" class="form-label">Surname</label>
                    <input type="text" class="form-control" id="surname_id">
                    
                </div>
            </div>
            <div class="row d-md-flex m-2">
                <div class="col-md-12 ">
                    <label for="inputEmail" class="form-label">Email</label>
                    <input type="email" class="form-control" id="email_id">
                </div>
            </div>
            <div class="row d-md-flex m-2">
                <div class="col-md-6">
                  
                    <label for="inputPassword" class="form-label">Password</label>
                    <input type="password" class="form-control" id="pass_id">
                    
                </div>
                <div class="col-md-6">
                  
                    <label for="inputPasswordConf" class="form-label">Confirm Password</label>
                    <input type="password" class="form-control" id="pass_conf_id">
                    
                    
                </div>

            </div>

            <div class="row d-md-flex m-2">
                <div class="col-md-6">
                    <button name="action" value="signin" class="btn btn-primary col-12 mt-3" type="button">Signup</button>
                </div>
                <div class="col-md-6">
                    <button name="action" value="cancel"  class="btn btn-dark col-12 mt-3" type="button">Cancel</button>
                </div>
            </div>
        </form>
   </div>
    
</body>
</html>



and my javascript where i’m try to detect the button press.

import express from "express";
import bodyParser from "body-parser";


const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));

app.get("/", (req,res) => {
    res.render("index.ejs");
});


app.listen(port, () => {
    console.log(`Server running on port: ${port}.`);
});



// Handle the login
app.post("/submit-form" , (req,res) => {
   const action = req.body.action;
    if (action === 'login') {
        res.send('Login Process Initiated');
    } else if (action === 'signin') {
        res.render("signin.ejs");

    } else {
        res.send('Unexpected action');
    }
 });

 // Handle the button signin 
app.post("/signin" , (req,res) => {
    // Never call this ---------------------------------
    const action = req.body.action;
    console.log(action);
    console.log("PRESSSS");
  });




I can’t get full chrome browser console logs in the NightWatch.js test

I’m trying to get full browser console logs in the NightWatch.js test.

This is my test script.

module.exports = {
    'Console Log Test': function (browser) {
        browser
            // Navigate to the test page
            .url(`${environment.API_PATH_LOCAL}/log-test`)

            // Wait for the keypad is loaded
            .waitForElementVisible('ion-button[data-e2e="dial-digit-5"]', 10000)
            .waitForElementVisible('ion-button[data-e2e="dial-digit-2"]', 10000)
            .waitForElementVisible('ion-button[data-e2e="dial-digit-0"]', 10000)
            
            // Wait for the call button is loaded
            .waitForElementVisible('#callBtn', 10000)

            // Click the digits
            .click('ion-button[data-e2e="dial-digit-5"]')
            .click('ion-button[data-e2e="dial-digit-2"]')
            .click('ion-button[data-e2e="dial-digit-0"]')
            .click('ion-button[data-e2e="dial-digit-0"]')

            // Click the call button
            .click('#callBtn')
            
            // Get the full browser console logs
            .getLog('browser', function(logEntriesArray) {
                console.log('Log length: ' + logEntriesArray.length);
                  logEntriesArray.forEach(function(log) {
                      console.log('[' + log.level + '] ' + log.timestamp + ' : ' + log.message);
                  });
              });

        // End the test
        browser.end();
    }
}

This is my nightwatch.conf.js file.

module.exports = {
    src_folders: ["tests"],
    
    webdriver: {
      start_process: true,
      port: 4444,
      server_path: require('chromedriver').path,
      cli_args: []
    },
    
    test_settings: {
      default: {
        launch_url: 'https://nightwatchjs.org',
        desiredCapabilities : {
          browserName : 'chrome',
          'goog:chromeOptions' : {
            w3c: true,
            args: [
              '--no-sandbox',
              '--disable-dev-shm-usage'
            ]
          },
          handleAlerts: true,
          loggingPrefs: { 'browser': 'ALL' }
        }
      }
    }
  };

I also tried this way but didn’t get the full browser console log either.

module.exports = {
    'Console Log Test': function (browser) {
        browser
            // Navigate to the test page
            .url(`${environment.API_PATH_LOCAL}/log-test`)

            // Wait for the keypad is loaded
            .waitForElementVisible('ion-button[data-e2e="dial-digit-5"]', 10000)
            .waitForElementVisible('ion-button[data-e2e="dial-digit-2"]', 10000)
            .waitForElementVisible('ion-button[data-e2e="dial-digit-0"]', 10000)
            
            // Wait for the call button is loaded
            .waitForElementVisible('#callBtn', 10000)

            // Click the digits
            .click('ion-button[data-e2e="dial-digit-5"]')
            .click('ion-button[data-e2e="dial-digit-2"]')
            .click('ion-button[data-e2e="dial-digit-0"]')
            .click('ion-button[data-e2e="dial-digit-0"]')

            // Click the call button
            .click('#callBtn')
            
            // Get the full browser console logs
            .captureBrowserConsoleLogs((event) => {
                console.log('event', event)
            })

        // End the test
        browser.end();
    }
}

During the test, there are nearly 300+ logs logged in browser console but I only get 8 logs. How can I get full browser console logs?