Javascript textarea keydown detect if Alt gr key being pressed and prevent its action futher

I Have a character limit in my text area and when it reaches a verge of 999 out of 1000 i dont want any accent characters to be entered.
Im not able to capture the final output of combination key, so when only 1 characters is left i need to detect Alt gr key being pressed and prevent its action further as not proceed with that combination.

keyDownEvent(e){
  if ( (charactersLeft === maxLength -1) && e.keyCode === 18) {
    e.preventDefault();
  }
}

The above is not working still the key combination happens and accent key(alt gr + a = ā) is being printed. How to stop this event.

How to add input field on button click

I’m trying to add field on Button Click but by default field is not showing and not adding on button click

i’ve tried my best but i don’t know what is the problem i added functions and use Math for generate unique id console.log is is working perfectly nut fields are not showing

"use client";
import React, { useState } from "react";
import { Button } from "../ui/button";

const DynamicForm = () => {
  const [fields, setFields] = useState([]);

  const addField = (event) => {
    event.preventDefault();
    const newFieldId = Math.random().toString(36).substring(2, 15);
    fields.push(...fields, { label: "", type: "text", id: newFieldId });
    console.log(fields);
  };

  const handleFieldChange = (index, event) => {
    const updatedFields = [...fields];
    updatedFields[index].label = event.target.value;
    setFields(updatedFields);
  };

  const handleTypeChange = (index, event) => {
    const updatedFields = [...fields];
    updatedFields[index].type = event.target.value;
    setFields(updatedFields);
  };

  return (
    <>
      <form>
        <h2>Dynamic Form</h2>
        {fields.map((field, index) => (
          <div key={field.id}>
            <label htmlFor={field.id}>Label: </label>
            <input
              id={field.id}
              name={field.id}
              value={field.label}
              onChange={(e) => handleFieldChange(index, e)}
            />
            <select
              value={field.type}
              onChange={(e) => handleTypeChange(index, e)}
            >
              <option value="text">Text</option>
              <option value="email">Email</option>
            </select>
            <Button onClick={() => setFields(fields.slice(0, index))}>
              Remove
            </Button>
          </div>
        ))}
        <div className="gap-3">
          <Button onClick={addField}>Add Field</Button>
        </div>
      </form>
    </>
  );
};

export default DynamicForm;

How to apply a sorting algorithm to array field whenever a value is added or changed?

I have a few array fields in my Sanity project that would work better if they were automatically sorted based on their values rather than having a user manually sort them.

I tried to create a custom component like this:

import type { ArrayOfObjectsInputProps } from 'sanity'


export function sortedArray(props: ArrayOfObjectsInputProps) {
  return props.renderDefault({
    ...props, onChange: (_patch) => {
      //@ts-ignore
      props.value?.sort(props.schemaType.options.sortFunc)
    }
  })
}

With something like this in my schema:

import { sortedArray } from '...'

//...

{
  //...
  components: { input: sortedArray },
  options: {
    //@ts-ignore
    sortFunc: (a, b) => { /* Sorting Algorithm */ },
}

But whatever I try, I can’t get it to work.

How to read response API data without Hardcoding it

I am writing a CLI command where I’m taking input as coin name and currency from user. But when I’m assigning my input variable it’s throwing error. See code first.

I tried Hardcoding instead of doing this res.data.data.coinOption; I did this res.data.data.BTC (Hardcoding);

import axios from "axios";
import colors from "colors";

class CryptoAPI {
  constructor(apikey) {
    this.apikey = apikey;
    this.baseUrl =
      "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest";
  }

  async getPriceData(coinOption, curOption) {
    try {
      const res = await axios.get(
        `${this.baseUrl}?symbol=${coinOption}&convert=${curOption}`,
        {
          headers: {
            "X-CMC_PRO_API_KEY": this.apikey,
          },
        }
      );

      let coinData = res.data.data.coinOption;
      let output = `Coin : ${coinData.symbol} (${coinData.name}) | Price : ${coinData.quote.INR.price} | Rank : ${coinData.cmc_rank} | Change 24H : ${coinData.quote.INR.percent_change_24h}%`;

      return output;
    } catch (error) {
      console.log(error);
    }
  }
}

export default CryptoAPI;
  

Error

TypeError: Cannot read properties of undefined (reading 'symbol')
    at CryptoAPI.getPriceData (file:///C:/Users/***/node.js/Projects/Coindex-CLI/lib/cryptoAPI.mjs:23:39)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async Object.price (file:///C:/Users/***/node.js/Projects/Coindex-CLI/commands/check.mjs:12:31)
undefined

I’m expecting that coinOption carry the input (BTC,ETH,XRP etc) and when I’m putting this variable i n the response data data.coinOption.name i will get “Bitcoin” but it doesn’t happening and in order to get name I’m Hard coding data.BTC.name which is not handy in multiple coins selection

See the data comming from server looks like this For example

"data": {
        "BTC": [
            {
                "id": 1,
                "name": "Bitcoin",
                "symbol": "BTC",
                "slug": "bitcoin",
                "num_market_pairs": 11018,
                "date_added": "2010-07-13T00:00:00.000Z",
           }
              ]
       }

Arduino BLE and website communication issues; SerialCharacteristic not changing?

For a group project I was trying to use the Arduino BLE to connect to my computer, which would be connected to a website that would then return an appropriate value to the Arduino BLE. The issue occurs after connecting to the BLE, because my website showed basically no signs of responding to my BLE’s messages at all. After a bit of testing and logging, I found that the issue was that I was using an eventListener in my javascript to detect whenever the BLE sends a message, but that whenever that message was sent, it does not detect anything because the SerialCharacteristic does not change.

I tried changing some random stuff, from changing the ports of the BLE, to readjusting how I’m sending the strings, but I have no clue how to change the SerialCharacteristic. When I tried using the bt.write() function, it said that apparently bt.write() function didn’t exist. I asked my friend who had used the BLE before and they said that bt.print() worked for them, so I really don’t know why the SerialCharacteristic refuses to change. I can tell that the BLE is connected because of logs, but otherwise I have no clue why things are malfunctioning. Also, during testing there was one random time when the message did get through, but I wasn’t logging stuff at the time and I failed to recreate it.
Relevant JS code:

const serviceUUID = 0xFFE0;
const serialUUID = 0xFFE1;

let device;
let serialCharacteristic;

async function connect(){

    device = await navigator.bluetooth.requestDevice({
        filters: [{
            services: [serviceUUID]
        }],
    });
    console.log("before server");
    const server = await device.gatt.connect();
    const service = await server.getPrimaryService(serviceUUID);

    serialCharacteristic = await service.getCharacteristic(serialUUID);
    console.log(serialCharacteristic);
    await serialCharacteristic.startNotifications();
    console.log("connected");
    serialCharacteristic.addEventListener('characteristicvaluechanged', read);

    document.getElementById('connect').removeEventListener("click", connect);
    document.getElementById('connect').addEventListener("click", disconnect);
    document.getElementById('connect').textContent = "Disconnect";
}

Relevant Arduino Code :

#include <SoftwareSerial.h>

String screen;
String btdata;
String serialdata;
SoftwareSerial bt(10, 11);

void setup() {
    bt.begin(9600);
}
void loop() {
    ...//irrelevant code
    Serial.println(screen)
    bt.print(screen);
       
    while (bt.available() == 0) { //I think bt.available() returns the number of characters ready to be read, so essentially I'm waiting until there's something being returned
        Serial.println(bt.available());
        delay(100);
    }
    btdata = bt.read();
    Serial.println(btdata);
}

How to obfuscate react code using terser or uglify-js? When .JS file has tag in it?

I have tried both npm packages to obfuscate react code.
I tried below code is inside package.json in script object
“minify:js”: “uglifyjs ./src/folder1/folder2/filename.js -c -m -o ./Build/filename.js”
and i run npm run minify:js and got below error.
Parse error at ./src/folder1/folder2/filename.js:15,8
<IconButton
^
ERROR: Unexpected token: operator «<».

The filename.js file has html tag content in it. It reruns an HTML element <IconButton. Because of that, it is throwing an error.

I am providing the code
enter image description here

Opening popup window on different monitor in Chrome [closed]

I can’t believe the hassle I’m having trying to do this. What I need to do, is open up 12 popups on my PC – all opening a different page. Currently, I’m having to manually move 2 of them onto each screen every day. I want to be able to click my button, and programmatically move / set their location onto a different screen. I have 6 screens, all the same size. I found so many posts, and quite a few going back over 10 years:

`window.open` on the second monitor in Chrome

Surely this is possible? I have tried manually setting negative top/left, but all it does is move the position on the primary screen. I’m on Windows 11, using the latest Chrome (happy to move to Firefox if it helps!).

Troubleshooting Data Display Issues in a Flask Web Application

this code should process the user text or file it used to work successfully till I had an error and during the error I reloaded the web and it started to display this message (No recommendations to display) even though I fixed the error it still the same whenever I reloaded the web and it no more displays the boxes only the message no matter what

here is the fe code ,, I get the only message on terminal saying (INFO:root:GET request processed)

app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        text_data = request.form.get('text')
        file = request.files.get('file')
        response_data = {}
        error_message = None
        
        if text_data:
            logging.info('Processing text data')
            response_json = send_to_other_app({'text': text_data}, 'create_cv')
            if response_json is not None:
                recommendations = response_json['recommendations']
                recommendations_newlines = recommendations.replace("['", " ").replace("',", " ").replace("']", " ").replace("'", " ")
                recommendations_newlines = recommendations.replace("\n", "n")
                response_json['recommendations'] = recommendations_newlines
                response_data['text_response'] = response_json
                logging.info(f'response_json_0  : {response_json}')
            else:
                error_message = 'Failed to process text data due to an external service error.'
        
        elif file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
            file.save(save_path)
            logging.info(f'File uploaded: {filename} to path: {save_path}')
            response_json = send_to_other_app({'file_path': save_path}, 'recommend')
            if response_json is not None:
                response_data['file_response'] = response_json
                logging.info(f'response_json_1 {response_json}')
            else:
                logging.info(f'response_json_2 {response_json}')
                error_message = 'Failed to process file due to an external service error.'
        
        if response_data:
            logging.info(f"Response data available: {response_data}")
            return render_template('recommendations.html', response=response_data)
        
        if not response_data and not error_message:
            logging.info("No response data available.")
            error_message = 'No text data or valid file provided for processing.'
        
        logging.error(error_message)
        return jsonify({'error': error_message}), 400

    # Handle GET request
    logging.info('GET request processed')
    return render_template('index.html')

here is the html code

    </style>
</head>
<body>
    <div class="container">
        {% if response %}
            {% if response.text_response %}
                <!-- CV Generated Box -->
                <div class="box">
                    <h2>CV Generated</h2>
                    <div class="content-box">
                        <pre>{{ response.text_response.created_cv }}</pre>
                    </div>
                </div>
        
                <!-- Recommendations Box -->
                <div class="box">
                    <h2>Recommendation</h2>
                    <div class="content-box">
                        <!-- Convert escaped newlines to HTML line breaks -->
                        <pre>{{ response.text_response.recommendations}}</pre>



                    </div>
                </div>
            {% endif %}
            {% if response.file_response %}
                <!-- File Response Box -->
                <div class="box">
                    <h2>Recommendation</h2>
                    <div class="content-box">
                        <pre>{{ response.file_response.recommendations }}</pre>
                    </div>
                </div>
            {% endif %}
        {% else %}
            <div class="no-recommendations">
                <p>No recommendations to display at the moment.</p>
            </div>
        {% endif %}
    </div>
</body>
</html>

How to collide the objects with wall Using AFrame and Javascript

How to collide with wall using and If possible in latest version of and If there is any reference to learn and Three.js. We are trying to work on how to attach the object to the wall in the latest version and Super hands with latest version.

The debug: true parameter to physics will produce wires around the bodies subject to physics, which makes it easier to understand the behavior of the scene. The rest is just placing the bodies and defining them as static or dynamic.
There are several ways of controlling movement in a world with physics. For example, bodies may receive impulse, and depending on the impulse vector, it will behave by gaining velocity, and maybe impacting other bodies.

To illustrate this, we will use some JavaScript to define a new Arame component, push, which will emulate “pushing” (giving some impulse) to the body. This will happen whenever the body collides with some other in the scene, and when that happens, it will get a “push”, always in the same direction and with the same intensity (that is, with the same impulse vector).

There are several ways of controlling movement in a world with physics. For example, bodies may receive impulse, and depending on the impulse vector, it will behave by gaining velocity, and maybe impacting other bodies.

To illustrate this, we will use some JavaScript to define a new Arame component, push, which will emulate “pushing” (giving some impulse) to the body. This will happen whenever the body collides with some other in the scene, and when that happens, it will get a “push”, always in the same direction and with the same intensity (that is, with the same impulse vector).

Unable to resolve dependency tree Error in react js while installing npm package

When I try to install react-sortable-tree npm package getting error like “unable to resolve dependency tree” and solution for this is given in that error message “Fix the upstream dependency conflict, or retry this command with –force or –legacy-peer-deps to accept an incorrect (and potentially broken) dependency resolution.”

What’s the right way to go about fixing this upstream dependency conflict? without using –force or –legacy-peer-deps how can I fix it?

npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@”^18.2.0″ from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@”^16.3.0″ from [email protected]
npm ERR! node_modules/react-sortable-tree
npm ERR! react-sortable-tree@”*” from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with –force or –legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR!
npm ERR! For a full report see:
npm ERR! /Users/user/.npm/_logs/2024-04-25T05_31_59_043Z-eresolve-report.txt

npm ERR! A complete log of this run can be found in: /Users/user/.npm/_logs/2024-04-25T05_31_59_043Z-debug-0.log

In my package.json I have “react”: “^17.0.2”.

Issues with the floating bar given by chrome when i screen record in chrome from my react app

Hello I am expecting some kind of directions/solution here. I have a react web app which enable user to record screen and video. So i use JS getDisplayMedia() to get the screen recording. So for enhancing the experience I have a timer of 5 seconds shown before the recording starts . In this timer screen I had added a keydown listner to catch space and esc button. esc button will abandon the recording and space will pause the timer. Now I will come to my issue. When I use getDisplayMedia() the chrome will prompt a floating window asking what to share (window, tab, screen). and if I choose something there will be a floating bar shown in the bottom by chrome which says stop sharing or hide. If in the options I choose share my entire window then automatically the focus got to the floating bar below(stop sharing one) and my keydown listners won’t work until i click on the screen. So is there a way in which I can avoid the chrome focussing its floating bar. All other sharing options (screen, tab) it is not getting focussed.

Please don’t down vote the question, if you know some links please point me there or if you know a solution please tell me here. If you find the question irrelevant please let me know that also with some reason.

Sonarqube – Error Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed – in javascript

I am getting this error :
30:9 error Refactor this function to reduce its Cognitive Complexity from 18 to the 15 allowed

Possible solutions I tried is like using if and then else if for the rest of the conditions.
Error will go but my code will not work as expected

How can I refactor the below code?

 workItemDetails.value.map((e: any) => {
        const existingData = touchPointRequests.filter((t) => +t.ticket_no === e.id);
        if (existingData.length && e.fields['System.State']) {
          this.updateBrandWebsiteState(existingData, e.fields['System.State']);
        }
        const existingGoLiveDate = new Date(new Date(existingData[0].go_live_date).toDateString());
        const newGoLiveDate = new Date(new Date(e.fields['Custom.GoLiveDate']).toDateString());
        const updateData: any = {};
        if (
          existingData.length &&
          e.fields['Custom.GoLiveDate'] &&
          newGoLiveDate.getTime() !== existingGoLiveDate.getTime()
        ) {
          const zonedDate = utcToZonedTime(new Date(e.fields['Custom.GoLiveDate']), 'Europe/Berlin');
          updateData.goLiveDate = zonedDate;
        }
        if (
          existingData.length &&
          e.fields['Microsoft.VSTS.Common.Priority'] &&
          AzurePriority[e.fields['Microsoft.VSTS.Common.Priority']] !== existingData[0].priority
        ) {
          updateData.priority = AzurePriority[e.fields['Microsoft.VSTS.Common.Priority']];
        }

        if (Object.keys(updateData).length) {
          this.touchPointRequestRepository.UpdateTouchPointRequestById(existingData[0].tpr_id, updateData);
        }
        if (
          existingData.length &&
          e.fields['Custom.PreviewLinks'] != undefined &&
          existingData[0].preview_link !== e.fields['Custom.PreviewLinks']
        ) {
          this.brandWebsiteRequestRepository.UpdateBrandWebsiteRequestByTPId(existingData[0].tpr_id, {
            previewLink: e.fields['Custom.PreviewLinks'],
          });
          this.sendPreviewLinkUpdateMail(existingData);
        }

        if (
          existingData.length &&
          e.fields['System.State'] === 'In Review' &&
          e.fields['Custom.PreviewLinks'] != undefined &&
          existingData[0].feedback_and_comments !== e.fields['Custom.PreviewLinks']
        ) {
          this.brandWebsiteRequestRepository.UpdateBrandWebsiteRequestByTPId(existingData[0].tpr_id, {
            feedbackAndComments: e.fields['Custom.PreviewLinks'],
          });
        }
      });

How to use the Livewire component nested in a livewire form

I have a form which has dynamic selects, I want to separate these selects into another livewire component, so as not to reprogram them in each form, but I don’t know how to validate them and obtain their values from the parent livewire component, how could I do the selects component to use them in other livewire forms?

I have read the documentation and it can be bound with the parent component, but it only allows one property and in these selects I have 3 properties (Country, State and City) these are the selects:

                    <div class="col-4">
                    <x-adminlte-input type="text" wire:model.live='employeeForm.employee_code' name="employeeForm.employee_code" label="Codigo de empleado" />
                </div>
                <div class="col-4">
                    <x-adminlte-select wire:model.live='employeeForm.team_id' name="employeeForm.team_id" label="Equipo:">
                        <x-adminlte-options :options='$employeeForm->teams' empty-option="Seleciona un equipo..." />
                    </x-adminlte-select>
                </div>
                <div class="col-4">
                    <x-adminlte-select wire:model.live='employeeForm.company_id' name="employeeForm.company_id" label="Empresa:">
                        <x-adminlte-options :options='$employeeForm->companies' empty-option="Seleciona una empresa..." />
                    </x-adminlte-select>
                </div>

My component code:

class CreateEmployeeForm extends Component
{
public EmployeeForm $employeeForm;

public $age = 0;

public function mount()
{
    $this->employeeForm->init();
}

public function updatedEmployeeFormCountryId($value)
{
    $this->employeeForm->updateStates($value);
}
public function updatedEmployeeFormstateId($value)
{
    $this->employeeForm->updateCities($value);
}
public function updatedEmployeeFormBirthDate($value)
{
    $this->age = Carbon::parse($value)->diff(now())->y;
}
public function updatedEmployeeFormCompanyId($value)
{
    $this->employeeForm->updateCompanyAssigment($value);
}
public function updatedEmployeeFormDepartamentId($value)
{
    $this->employeeForm->updateJobPositions($value);
}
public function save()
{
    $this->employeeForm->store();
}
public function render()
{
    return view('livewire.create-employee-form');
}
}

My EmployeeForm Code:

    public function updateStates($citySelectedId)
{
    $this->states = Country::find($citySelectedId)?->states()->get()->pluck('name', 'id')->all();
    $this->reset(['state_id', 'city_id']);
}

public function updateCities($stateSelectedId)
{
    $this->cities = State::find($stateSelectedId)?->cities()->get()->pluck('name', 'id')->all();
    $this->reset(['city_id']);
}

public function updateCompanyAssigment($companySelectedId)
{
    $company = app(CompanyRepository::class)->find($companySelectedId);
    $this->departaments = $company?->departaments()->get()->pluck('name', 'id')->all();
    $this->areas = $company?->areas()->get()->pluck('name', 'id')->all();
    $this->payRolls = $company?->payRolles()->get()->pluck('code', 'id')->all();
    $this->reset(['area_id', 'payroll_id', 'departanment_id']);
}

public function updateJobPositions($departamentSelectedId)
{
    $this->jobPositions = Departament::find($departamentSelectedId)?->jobPositions()->get()->pluck('name', 'id')->all();
}

chrome extension how download file user

I have an extension that has added a button to a page. How to make sure that after clicking the button, a file is downloaded from the site/extension folders, the image is allowed in the extension extension, and when you click the download button, it goes in the browser

Didn’t find any information at all, didn’t try anything