first chat disappears after adding second chat

I’ve been facing an issue for several days now and can’t seem to pinpoint the cause. My webpage consists of just two chat displays. It originally had only one, but I’ve had to add a second one recently. This page is used as a browser source in OBS, in case that’s relevant. There’s a chat for regular users and another one for premium users.

First, take a look at the code:

const fetchMessages = function(){
    $.post('/get', function(data){
        
        let newMessages = $();
        data.data1.forEach(function(msg){
            newMessages = newMessages.add(`
                <div class="message-container" id="${msg.element}">
                    <img src="${msg.avatarUrl}" alt="Avatar" class="avatar">
                    <p><span class="name">${msg.name}:</span><img src="${msg.logo}" alt="Logo" class="logo"/><span class="content">${msg.message}</span></p>
                </div>
            `);
        });
        $('#messages').empty().append(newMessages);

        let newMessages2 = $();
        data.data2.forEach(function(msg){
            newMessages2 = newMessages2.add(`
                <div class="message-container" id="${msg.element}">
                    <img src="${msg.avatarUrl}" alt="Avatar" class="avatar">
                    <p><span class="name">${msg.name}:</span><span class="content">${msg.message}</span></p>
                </div>
            `);
        });
        $('#messages2').empty().append(newMessages2);
    });


};

fetchMessages();
setInterval(fetchMessages, <%= refreshRate %>);

I’m not sure why I named the function fetchMessages when I’m making POST requests. It’s something I did a while back.

My issue is that only the second chat (messages2) is being displayed; the other div (messages) remains empty. If I use data1 in the second chat, both display messages, but they show the same messages.

It must be a silly mistake somewhere, but I can’t figure it out. Can anyone help?

Calculating custom coordinates

I have a 10x150 rectangular path as following. On this, I am applying certain rotation on the first point of the points dataset which is essentially the starting point of the rectangular path.

const points = [{x:650,y:300},{x:650,y:150},{x:640,y:150},{x:640,y:300}];
const angle = 45;

/*const height = points[0].y-points[1].y;
const width = points[1].x-points[2].x;*/

const rectPath = d3.select('.rect>path')
  .attr('d',(_)=>d3.line().x(d=>d.x).y(d=>d.y)(points))
  .attr('transform', `rotate(${angle},${points[0].x},${points[0].y})`)
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<svg viewBox="0 0 1280 600">
    <rect width="1280" height="600" fill="#EFEFEF"></rect>
    <g class="rect">
      <path fill="none" stroke="red"></path>
    </g>

    <line class="divider" x1="240" x2="1040" y1="300" y2="300" stroke="green"></line>
  </svg>
</body>

</html>

After the transformation, I need to ensure that the opposite arm of the rectangle still stays on the green line. For example, with 45 degree rotation applied, I need something like below (derived through trial and error) d="M650,300L650,150L640,150L640,310", which probably requires one to calculate the last coordinate of the points dataset.

<svg viewBox="0 0 1280 600">
    <rect width="1280" height="600" fill="#EFEFEF"></rect>
    <g class="rect">
      <path fill="none" stroke="red" d="M650,300L650,150L640,150L640,310" transform="rotate(45,650,300)"></path>
    </g>

    <line class="divider" x1="240" x2="1040" y1="300" y2="300" stroke="green"></line>
  </svg>

How can I programmatically calculate the new coordinate with respect to the angle of rotation applied to achieve the desired result?

Chrome Extension – How to send data to it and open popup window

My company has an internal version of ChatGPT that we use, and I was working on creating an extension to have a better way to interact with it.

Basically, we have an internal site, that has a chatbot very similar to the OpenAI one.

As of now, I created an extension that allows me to select editable text in Chrome, and when I right click, I have a list of prompts.
If I click on one, it opens a new tab with the chatbot, and pastes the prompt + selected text.

That works fine.

Also, I have a popup window, when I click on the extension icon, that loads that same site in the popup window.

What I want is to select text, right click on it and select a prompt, and instead of jumping into a new tab with the site, just open the popup window and paste the prompt+text in there.

What I have so far:

My manifest.json file has:

  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_title": "Chatbot Helper",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["https://internal.chatbot.com/*"],
      "js": ["content.js","popup.js"],
    }

My popup.js is just:

"use strict";

But my popup.html is:

<html lang="en">

<head>
    <meta charset="utf-8">
    <script type="module" src="popup.js"></script>
</head>

<body>
    <iframe src="https://internal.chatbot.com/" frameborder="0" style="width: 600px;height:580px;"></iframe>
</body>

</html>

In my background.js, this is the part that takes the selected text to the new tab:

    const selectedItem = menuItems[info.menuItemId];
    if (selectedItem) {
        savedText(selectedMenuItem + " n" + info.selectionText);
        newTab(chatbotURL);
    }

Also, is there a way to invoke that popup by hitting a combination of keys? Instead of clicking on it?

I tried this because I saw a post with something similar but no luck:

    const selectedItem = menuItems[info.menuItemId];
    if (selectedItem) {
        savedText(selectedMenuItem + " n" + info.selectionText);
        chrome.tabs.create({url:"https://internal.chatbot.com/"});
    }

Creating a currency mask in vuetify 2 and v-mask

I am currently using the cdn version of v-mask for my vuetify 2 project. I have been asked to add a currency mask since here in the United States we tend to use thousandth digit comma separation. I am struggling to get it to work though as my range of numbers can be anywhere from the tens of thousands to the hundred billions. I figured I could just use v-mask with the mask amount to be a catch all but it seems to draw an error. Here is my implementation:

                <v-text-field v-model="totalDollarAmount"
                              label="(4) Total Dollar Amount"
                              type="number"
                              v-mask="'###,###,###,###,###.##'"
                              prefix="$"
                              outlined
                              required
                              :rules="[v => !!v || 'Total Dollar Amount is required']"
                              :error-messages="totalDollarAmountWarning"></v-text-field>

The error it generates is as follows:

v-mask.min.js:1 The specified value "758,850,000," cannot be parsed, or is out of range.

The issue is the value may not occupy all the ### and therefore is drawing the error. This might need to be dynamic by dividing by 1000 or using modulus somehow but this seems overlycomplicated.

Date sorting on a datatable with multiple formats

I am using a datatable that has a date column. I am trying to sort the table by Date Ascending but it doesn’t seem to work. It is not sorting properly. It places July 30 above Mar 5. It is because I am using two different date formats (Marc 5, 2024 & Jul 30 – 31, 2024). Can you please help. Thanks. Here is my code –

$(document).ready(function() {
   
   var table = $('#test').DataTable({
  responsive: true,
  paging: false,
  lengthChange: false,
fixedHeader: true,
columnDefs: [
  {
    targets: 2,
    type: 'date',
  }
],
 
order:[[  2, 'asc' ]]
 
 } );
 
} );
<table class="row-border stripe dt-right dataTable no-footer dtr-inline" id="test" style="width: 100%;"><thead text-align="left"><tr><th>Event</th><th>City, State</th><th>Date</th></tr></thead>
<tbody>
<tr>
<td>My first event</th>
<td>Devnver,CO</th>
<td>Mar 4 - 7, 2024</th>
</tr>
 
<tr>
<td>My third event</th>
<td>Devnver,CO</th>
<td>Mar 5, 2024</th>
</tr>
 
<tr>
<td>My second event</th>
<td>Devnver,CO</th>
<td>Jul 30 - 31, 2024</th>
</tr>
 
<tr>
<td>My fourth event</th>
<td>Devnver,CO</th>
<td>Mar 5, 2024</th>
</tr>

AngularJS ng-options use filter and orderBy components together for select dropdown

I have dropdown in angularJS using ng-options. I need to use filter: and orderBy: component together for the ng-options
My filter for the select is working fine, however the OrderBy: component does not seem to be working.

Below is my code implementation of what I have tried:

<label class="control-label">My Dropdown 123</label>
<input type="search" ng-model="searchFilter.Name" class="" placeholder="Search"></input>
<select class="form-control" 
        ng-options="l as (l.ID ? (l.ID  + ' ' + '-' + ' '): '' ) + l.Name  + ' ' +'('+ l.ID + ') ' for l in vm.values | orderBy: l.Name | filter: searchFilter track by l.ID "
        data-ng-model="vm.values"
        ng-disabled="vm.isReadOnly">        
    <option value="">All</option>
</select>

Please guide and advice as how I can make the orderBy and filter work together for ng-options in AngularJS with HTML.

Any help or advice will be highly appreciated.

Thanks in advance

React setState after data is available

I am creating a form that will be prepopulated with some data that is returned by an api. My problem is that the react state is not updating as expected after the api returns data.

I am getting my api data from context:

  const {
    submissionDetails,
  } = useContext(AppContext) as {
    submissionDetails: {
      branchName: string
      clientAddress1: string
      clientAddress2: string
      clientCity: string
      clientContactEmail: string
      clientContactFullName: string
      clientName: string
      clientState: string
      clientZip: string
      namedInsured: string
      underwriterDisplayName: string
    }
  }

I have console logged my context values and they are as expected.

I am using React state to set my form with the values from context:

  const [referralData, setReferralData] = useReducer(referralReducer, {
    accountName: submissionDetails?.namedInsured || '',
    branch: submissionDetails?.branchName || '',
    clientName: submissionDetails?.clientName || '',
    underwriter: submissionDetails?.underwriterDisplayName || '',
  })

  function referralReducer(
    state: {
      accountName: string
      branch: string
      clientName: string
      underwriter: string
    },
    event: { name: string; value: string | unknown }
  ) {
    return { ...state, [event.name]: event.value }
  }

Now the problem I am having is that my form still appears to have empty strings for its values. I would like my reducer to update with the state values whenever they become available.

How to implement search function with searchbar?

I have a react native app. And I try to implement a search function for searching animals. I have a service that returns all the animals and a context.

So this is the service call:

export const fetchAnimalData = async () => {
    const token = await retrieveToken();
    try {
        if (token) {
            const response = await fetch(`${API_URL}/api/animals/`, {
                method: "GET",
                headers: {
                    Authorization: `Token ${token}`,
                    "Content-Type": "application/json",
                },
            });
            return await response.json();
        } else {
            throw new Error(token);
        }
    } catch (error) {
        console.error("There was a problem with the fetch operation:", error);
        throw error;
    }
};

and the searchContext:

import React, { createContext, useEffect, useState } from "react";
import { fetchAnimalData } from "./animal/animal.service";


export const SearchAnimalContext = createContext();

export const SearchAnimalContextProvider = ({ children }) => {
    const [CatgoryList, setSubCategoryList] = useState([]);
    const [searchAnimal, setSearchAnimal] = useState("");
    const [results, setResults] = useState([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState(null);

    const handleSearch = (text) => {
        setSearchAnimal(text);
    };

    const filteredData = CatgoryList.filter((item) =>
        item.name.toLowerCase().includes(searchAnimal.toLowerCase())
    );

    const performSearch = async () => {
        setLoading(true);
        setError(null);
        try {
            const response = await fetchAnimalData(filteredData);
            console.log(response); 
            setResults(response.data);  
        } catch (error) {
            setError(error.message);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {}, []);

    return (
        <SearchAnimalContext.Provider
            value={{
                data: filteredData,
                searchAnimal,
                setSearchAnimal,
                handleSearch,
                performSearch,
                results,
                loading,
                error,
            }}>
            {children}
        </SearchAnimalContext.Provider>
    );
};

And I try to inject the searchContext in this component:

export const CategoryScreen = ({ navigation }) => {
    const { loading, categoryList } = useContext(CategoryContext);
    const { searchAnimal, performSearch } = useContext(SearchAnimalContext);

    const handleSearch = () => {
        performSearch();
    };

    return (
        <SafeArea>
            {loading && (
                <LoadingContainer>
                    <ActivityIndicator animating={true} color={MD2Colors.blue500} />
                </LoadingContainer>
            )}
            <Searchbar placeholder="Search" onChangeText={handleSearch} value={searchAnimal} />
            <CategoryList
                data={categoryList}
                renderItem={({ item }) => {
                    return (
                        <>
                            <TouchableOpacity
                                onPress={() => navigation.navigate("groepen", { subcategories: item.id })}>
                                <Spacer position="top" size="large">
                                    <CategoryInfoCard category={item} />
                                </Spacer>
                            </TouchableOpacity>
                        </>
                    );
                }}
                keyExtractor={(item) => item.id}
            />
        </SafeArea>
    );
};

But if I type a letter in the searchbar I see in the console that all the animals are returned. And the searching is not working.

Question: How to implement the search functionality correct?

Web3.js solana getBalance and connection

I have a problem pls help me, so i have this problem when i start this code

Error when receiving balance: Error: failed to get balance of account AXVegit8N2AuKv4A8Ad4zizbWLHnT2RPsqiocKyPWmLS: Error: 403 : {“jsonrpc”:”2.0″,”error”:{“code”: 403, “message”:”Access forbidden, contact your app developer or [email protected].”}, “id”: “26150ee6-97a4-4d47-ac77-92e0648b8ec0” }

at connection.ts:3245:1
at async Connection.getBalance   (connection.ts:3242:1)
at async handleBalanceCheck      (BalanceApp.jsx:29:1)





import React, { useState } from "react";
import {
Connection,
PublicKey,
LAMPORTS_PER_SOL,
clusterApiUrl,
} from "@solana/web3.js";

const BalanceApp = () => {
const [publicKeyInput, setPublicKeyInput] = useState("");
const [balance, setBalance] = useState(null);

const handleBalanceCheck = async () => {
    try {
         const connection = new Connection(clusterApiUrl("testnetz"));
         const connection = new Connection(
             "https://api.testnet.solana.com",
             "confirmed"
         );
        const connection = new Connection(clusterApiUrl("mainnet-beta"));
          const connection = new web3.Connection(
             web3.clusterApiUrl("mainnet-beta")
        );
    
        const walletPublicKey = new PublicKey(publicKeyInput);

        const balance = await connection.getBalance(walletPublicKey);
        setBalance(balance / LAMPORTS_PER_SOL);
    } catch (error) {
        console.error(error);
    }
   };

   return (
    <div>
        <h1>Checking your Solana wallet balance</h1>
        <input
            type="text"
            value={publicKeyInput}
            onChange={(e) => setPublicKeyInput(e.target.value)}
            placeholder="Enter the wallet's public key"
        />
        <button onClick={handleBalanceCheck}>Check balance</button>
        {balance !== null && <p>wallet balance: {balance} SOL</p>}
    </div>
   );
  };

  export default BalanceApp;

But if i use in this peace of code "https://api.testnet.solana.com" all work, but i dont need 
a test solana balance i need a real solana balance on users wallets)

const connection = new Connection(
            "https://api.testnet.solana.com",
            "confirmed"
             );            

PLS Help me)

Making a selected text bold or un-bold in React rich text editor

I’m working on creating a rich text editor in react without using any library using contentEditable attribute. I’m able to bold a text using the code given below. But the problem arises when I try to un-bold it.

When I bold the selected text it gets bold, but when without unselecting it I try to un-bold it, it instead runs the same code as making the text bold.

here’s the code I’m using –

<div
                    className={`${styles.richTextEditor}`}
                    ref={richTextEditorRef}
                    onInput={handleContentChange}
                    contentEditable
                    dir="ltr"
                    dangerouslySetInnerHTML={{ __html: defaultValue.current }}
                ></div>
export function toggleBold() {
    let selection = window.getSelection();

    if (selection.rangeCount > 0) {
        const range = selection.getRangeAt(0);

        const parentElement = range.commonAncestorContainer;
        const nearestHtmlTag = findNearestHTML(parentElement);

        if (nearestHtmlTag.tagName.toLowerCase() !== "span") {
            const boldSpan = document.createElement("span");
            boldSpan.style.fontWeight = "bold";
            // boldSpan.setAttribute("class", "boldSpan");
            range.surroundContents(boldSpan);
        }

        if (
            nearestHtmlTag.tagName.toLowerCase() === "span" &&
            nearestHtmlTag.contains(range.commonAncestorContainer)
        ) {
            const isBold =
                nearestHtmlTag.style.fontWeight === "bold" ||
                window.getComputedStyle(nearestHtmlTag).fontWeight === "bold";
            if (isBold) {
                nearestHtmlTag.style.fontWeight = "normal";
            } else {
                nearestHtmlTag.style.fontWeight = "bold";
            }
        }
    }
}

function findNearestHTML(node) {
    while (node && node.nodeType !== 1) {
        node = node.parentNode;
    }

    return node;
}

I think the problem lies in selecting the parentElement and neartestHtmlTag because if I unselect the text and then select it, the code works perfectly fine. Also using console.log without unselecting the text the parent element is not <span> but <div>.

Data rendering on the OverlayPanel using Vue js and PrimeVue

Question on data rendering on the OverlayPanel using Vue.js

<template>
  <Column field="tags" header="Tags">
    <template #body="{ data }">
      {{ console.log( 'tags1 ', data.tags) }}
      <span class="more-tags" @click="toggle"> More </span>
      {{ console.log('tags2 ', data.tags) }}
      <OverlayPanel ref="op">
        <div v-for="tag in data.tags" :key="tag">{{ tag }}</div>
      </OverlayPanel>
    </template>
  </Column>
</template>

<script setup>
import { ref } from 'vue';
import OverlayPanel from 'primevue/overlaypanel';

const op = ref(null);

const toggle = (event) => {
  op.value.toggle(event);
};
</script>

data.tags is an array of objects like below

[
    "apartment",
    "third-floor",
    "Living Room",
    "Residential"
]

[
    "apartment",
    "fourth_floor"
]
[
   "mobile"
]

But on the overlayPanel, it always displays same data for example when I click on “More”, it always displays mobile. I expected to dynamically display tags.

but console statement prints tags1 and tags2 correctly.
Not sure why the OverlayPanel displays same data.

Any help?

use npm package in laravel livewire

i am using a npm package in my livewire project.
when load the page via refresh package work fine, but when redirect with livewire navigate the package does not work, this is my code:

import $ from 'jquery';
import '@majidh1/jalalidatepicker/dist/jalalidatepicker.min.css';
import '@majidh1/jalalidatepicker/dist/jalalidatepicker.min.js';
function create_datepicker(){
    jalaliDatepicker.startWatch({
        hideAfterChange : false,
        showEmptyBtn : false,
        autoReadOnlyInput : true,
        autoHide : false,
        time : false
    });
}
document.addEventListener('livewire:navigated', () => {
    setTimeout(create_datepicker, 200);
});
document.addEventListener('hide_datepicker', () => {
    jalaliDatepicker.hide();
});

How can I find out the used obfuscation method of an internet page [closed]

For creating football statitics, I load content from fussball.de, it’s public data.
Playernames (which in a different submenu are clear text), are obfuscated, e.g.

<div class="player-name"><span data-obfuscation="bf2q62ku" class="firstname results-c-bf2q62ku"> </span><span data-obfuscation="bf2q62ku" class="lastname results-c-bf2q62ku"></span></div>

I already know the following

  • exactly one char is replaced by another char which is never ASCII
  • spaces are not replaced
  • the same chars in a string do not have necessarily the same replacement
  • a string is used for obfuscation, in the example: bf2q62ku

an URL for a complete example:
https://www.fussball.de/mannschaft/rsv-bueblingshausen-ii-rsv-bueblingshausen-hessen/-/saison/2324/team-id/011MIBJEF0000000VTVG0001VTR8C1K7#!/

Were do I find in html code the used obfuscation method, so that I can translate the strings back in Java?
The browser itself also translates the data, so he must know, how to deal with the obfuscation strings

react-accessible-treeview expand nodes dynamically added

I’m using react-accessible-treeview component addingremoving nodes dynamically dragging nodes from a tree view to another.
When a node is dropped to destination tree, all parents is added too, the problem is that i want to expand the dropped node and all its parents.
I tried to work with the property “expandedIds”, it woks but is some nodes will be expand with mouse click the “expandedIds” state is not updated by the component and, when the next node will be dropped the “mouse clicked” expanded node collapse.
What is the way to achieve the right behavior?