Ripple not displaying in React Three Fiber, and i’m not sure why

I am trying to create a ripple, below is my code but yet its not rendering on the screen, yet i seem not to be getting any errors.

import './App.css'; 
import { useMemo } from 'react';
import * as THREE from 'three'; 
import { Canvas, useLoader} from '@react-three/fiber';
import circleImg from './assets/circle.png'; 
import { Suspense } from 'react';

function Points(){
  
  const imgTex = useLoader(THREE.TextureLoader, circleImg); 


  const count = 500; 
  const sep = 3;  

  const positions = useMemo(() => {
     let coords = [];

     for(let i = 0; i < count; i++){
      for(let j = 0; j < count; j++){
        let x = sep * (i - count/2);
        let z = sep * (j - count/2);
        let y = 0;
        coords.push(x,y,z);
      }
     }

     let arr = new Float32Array(coords); 
     console.log(arr); 

     return arr; 

  }, [count, sep]);

  return(
    <points>
      <bufferGeometry attach="geometry">
        <bufferAttribute 
          //attach="attributes.position"
          attachObject={['attributes','position']} 
          array={positions}
          count={positions.length/3}
          itemSize={3}
        />
      </bufferGeometry>
      
      <pointsMaterial 
        attach="material"
        //map={imgTex}
        color={0x00AAFF}
        size={0.5}
        sizeAttenuation
        transparent={false}
        alphaTest={0.5}
        opacity={1.0} 
      />
    </points>


  )
}

function AnimationCanvas(){
  return (
    <Canvas 
        camera={{position: [100, 10, 0], fov: 75}}> 
        <Points />
    </Canvas>
  )
}


function App() { 

  return (
      <div className="anim">

        <Suspense fallback={<div>loading...</div>}>
          <AnimationCanvas />
        </Suspense>
      
       </div>
  )
}

export default App

can someone please help out and tell me what i might be doing wrong.
Thanks in advance.

How to query the related in-depth data in typeORM?

I currently have six table instances: module, codefunc, link, combo, node, and edge.

And there are the following relationships:

module 1:1 combo
codefunc 1:1 node
link 1:1 edge

enter image description here

The detail typeORM entities:

@Entity()
@Unique(['path', 'moduleName'])
export class ComboModule {
  @PrimaryGeneratedColumn()
  id: number | undefined

  // Combo
  @OneToOne(type => Combo)
  @JoinColumn()
  combo: Combo | undefined;

  @Column({
    type: 'varchar',
  })
  path: string

  @Column({
    type: 'varchar',
  })
  moduleName: string

  @Column({
    type: 'text'
  })
  desc?: string

  @ManyToOne(type => ComboModule)
  parent?: ComboModule | null

  @OneToMany(type => NodeCodeFunc, codeFunc => codeFunc.module)
  codeFuncs: NodeCodeFunc[] | undefined

  @Column({
    default: false,
    type: 'boolean'
  })
  isDeleted: boolean | undefined

  @CreateDateColumn()
  createDate?: Date

  @UpdateDateColumn()
  updateDate?: Date

  constructor(moduleName: string = '', path: string, desc: string | undefined = '',  parent: ComboModule| null) {

    this.moduleName = moduleName
    this.desc = desc
    this.path = path
    this.parent = parent
  }
}


@Entity()
export class EdgeCommonSupport {
  @PrimaryGeneratedColumn()
  id: number | undefined

  // Combo
  @OneToOne(type => Edge)
  @JoinColumn()
  edge: Edge | undefined;

  @Column({
    type: 'varchar',
    default: 'support' 
  })
  supportName: string | undefined

  @Column({
    type: 'text'
  })
  desc?: string

  @Column({
    default: false,
    type: 'boolean'
  })
  isDeleted: boolean | undefined

  @CreateDateColumn()
  createDate?: Date

  @UpdateDateColumn()
  updateDate?: Date

  constructor(supportName: string = '', desc: string | undefined = '' ) {
    this.supportName = supportName
    this.desc = desc
  }
}

@Entity()
@Unique(['path', 'codefuncName'])
export class NodeCodeFunc {
  @PrimaryGeneratedColumn()
  id: number | undefined

  // Combo
  @OneToOne(type => Node)
  @JoinColumn()
  node: Node | undefined;

  @Column({
    type: 'varchar',
  })
  path: string | undefined

  @Column({
    type: 'varchar',
  })
  codefuncName: string

  @Column({
    type: 'text'
  })
  desc?: string

  @ManyToOne(type => ComboModule, module => module.codeFuncs)
  module: ComboModule | null

  @Column({
    default: false,
    type: 'boolean'
  })
  isDeleted: boolean | undefined

  @CreateDateColumn()
  createDate?: Date

  @UpdateDateColumn()
  updateDate?: Date

  constructor(path: string, codefuncName: string = '', desc: string | undefined = '', module: ComboModule | null) {

    this.path = path
    this.codefuncName = codefuncName
    this.desc = desc
    this.module = module
  }
}


@Entity()
export class Node {
  @PrimaryGeneratedColumn()
  id: number | undefined

  // ProjMod
  @ManyToOne(type => ProjMod, projMod => projMod.Nodes)
  projMod: ProjMod

  @Column({
    default: false,
    type: 'boolean'
  })
  isDeleted: boolean | undefined

  @CreateDateColumn()
  createDate?: Date

  @UpdateDateColumn()
  updateDate?: Date

  constructor(projMod: ProjMod) {
    this.projMod = projMod
  }
}

export const EdgeConnectType = {
  NodeToNode: 'NodeToNode',
  NodeToCombo: 'NodeToCombo',
  ComboToCombo: 'ComboToCombo',
  ComboToNode: 'ComboToNode'
}

@Entity()
export class Edge {
  @PrimaryGeneratedColumn()
  id: number | undefined

  // ProjMod
  @ManyToOne(type => ProjMod, projMod => projMod.Nodes)
  projMod: ProjMod

  @Column({
    type: 'varchar',
    nullable: true,
    default: EdgeConnectType.NodeToNode
  })
  connecttype: string | undefined

  // Node:source
  @OneToOne(type => Node)
  @JoinColumn()
  NodeSource?: Node

  // Node:target
  @OneToOne(type => Node)
  @JoinColumn()
  NodeTarget?: Node

  // Combo:source
  @OneToOne(type => Combo)
  @JoinColumn()
  ComboSource?: Combo

  // Combo:target
  @OneToOne(type => Combo)
  @JoinColumn()
  ComboTarget?: Combo

  @Column({
    default: false,
    type: 'boolean'
  })
  isDeleted: boolean | undefined

  @CreateDateColumn()
  createDate?: Date

  @UpdateDateColumn()
  updateDate?: Date

  constructor(projMod: ProjMod) {
    this.projMod = projMod
  }
}

@Entity()
export class Combo {
  @PrimaryGeneratedColumn()
  id: number | undefined

  // ProjMod
  @ManyToOne(type => ProjMod, projMod => projMod.Nodes)
  projMod: ProjMod

  @Column({
    default: false,
    type: 'boolean'
  })
  isDeleted: boolean | undefined

  @CreateDateColumn()
  createDate?: Date

  @UpdateDateColumn()
  updateDate?: Date

  constructor(projMod: ProjMod) {
    this.projMod = projMod
  }
}

I can query out module (and its combo) + codefuncs (and its node).

For example, in the following way(fine-tuning may be required):

export const ModulesWithCodefuncs = publicProcedure.input(z.object({
  projModId: z.number()
})).query(async ({input: {projModId}}) => {

  const modules = await dataBase.getRepository(ComboModule)
 .createQueryBuilder('ComboModule')
 .where("combo.projMod.isDeleted = :isDeleted", { isDeleted: false })
 .andWhere("combo.projMod.id = :projModId", { projModId: projModId })
 .leftJoinAndSelect('ComboModule.combo', 'combo')
 .leftJoinAndSelect('ComboModule.codeFuncs', 'codeFuncs')
 .getMany()

  return modules
})

But now I also want to query out the related edges(because there also has many edges source/target in other projMod). How should I do it?


EDIT-01

I don’t have any idea about how to query it out through typeorm.

The only thing that comes to my mind is to query out all the edges and the module + codefunc queried here, and then iterate through the edges, judging whether the source/target of the edge belongs to module/codefunc, and keep it if it exists.

Mango db haqqinda neleri bilirsiz?

A Brief Overview of MongoDB

MongoDB is a non-relational (NoSQL) database management system designed for flexible and efficient data storage. First introduced in 2009 by MongoDB Inc., it has become a popular choice for managing unstructured and semi-structured data.


Key Features

1. Document-Based Structure

MongoDB stores data in BSON (Binary JSON) documents, which are similar to JSON. This format allows data to be organized in an object-oriented manner, making it intuitive and easy to work with.

2. Flexibility and Scalability

  • MongoDB allows you to define your data models in any format.
  • It supports horizontal sharding, enabling the management of massive data sets across distributed systems.

3. Schema-Less Data Model

Unlike traditional SQL databases, MongoDB does not require predefined schemas, offering greater flexibility for evolving application needs.

4. High Performance

  • Optimized for fast read and write operations.
  • Ensures data security through replica sets and load balancing features.

Core Concepts

  • Database: The primary structure containing collections.
  • Collection: Comparable to a table in SQL, but without rigid structure.
  • Document: The smallest unit of data, stored in a JSON-like format.

Advantages of MongoDB

  1. Speed and Performance
    MongoDB excels in handling large volumes of data due to its simple and efficient structure.

  2. Flexible Data Models
    It easily adapts to changes, making it ideal for dynamic and fast-paced projects.

  3. Scalable Architecture
    It can handle massive data sets effectively with its distributed data approach.


Disadvantages

  • Not as suitable for complex queries as SQL databases.
  • Higher memory requirements due to its document-based structure.
  • Additional configuration may be needed to ensure data consistency.

Conclusion

MongoDB is a powerful and modern database system that caters to the needs of contemporary applications. Its flexibility, performance, and schema-less structure make it an ideal choice for startups and enterprises managing large volumes of data. As businesses continue to demand scalable and adaptable solutions, MongoDB remains a leading contender in the world of database technologies.

randoMrandoMrandoMrandoMrandoMrandoM

make divs sticky / unsticky depending on scroll

on one of my website pages, I have two divs, “.page-biography-section-right-sub-section-left” and “.page-biography-section-right-sub-section-right”, contained within a parent div “.page-biography-section-right” displayed using flexbox.

In the back office, I have 3 content blocks, one per period of time (1944-1984, 1984-1998, 1998-2001). Each block contains a text field and a repeater field with images.

On the front end, I want my 3 text blocks to appear in the left column “.page-biography-section-right-sub-section-left”, each within a div “.biography-bloc-text”, stacked vertically with IDs “_1944-1984”, “_1984-1998”, and “_1998-2021”. The images should appear in the right column “.page-biography-section-right-sub-section-right”, stacked vertically, each within a div “.page-content-section-right-img-container”. Each of these image containers has a rel attribute, for example, rel=”1944-1984″, corresponding to the associated text block. The first block corresponds to “1944-1984”, the second to “1984-1998”, and the third to “1998-2021”.

Here’s the behavior I’m trying to achieve:

On page load, the first text block “.biography-bloc-text” in the left column is sticky. and n the right column, the “.page-content-section-right-img-container divs” are sticky as they reach the top of the viewport. Once the last “.page-content-section-right-img-container” associated with the first text block finishes scrolling, the first text block stops being sticky, and the next “.biography-bloc-text becomes” sticky. The image containers in the right column continue behaving the same way. This behavior repeats for all three text blocks and their corresponding image containers.

When the user scrolls back up, the behavior should reverse, with each text block becoming sticky only while its associated images are visible in the viewport.

This is what I have so far:

html :

    <div class="page-biography-section-right">
  <div class="page-biography-section-right-sub-section-left">
    <div class="page-biography-section-right-sub-section-left-inside">
      <div class="biography-bloc-text" id="_1944-1984">
        <a href="#"></a>
        <h1>(1944-1984)</h1>
        <ul>
          <li>1944-1969</li>
          <li>1969-1972</li>
          <li>1973-1984</li>
        </ul>
      </div>
      <div class="biography-bloc-text" id="_1984-1998">
        <a href="#"></a>
        <h1>(1984-1998)</h1>
        <ul>
          <li>1984-1986</li>
          <li>1987-1990</li>
          <li>1989-1995</li>
          <li>1995-1998</li>
        </ul>
      </div>
      <div class="biography-bloc-text" id="_1998-2021">
        <a href="#"></a>
        <h1>(1998-2021)</h1>
        <ul>
          <li>1998-2003</li>
          <li>2003-2009</li>
          <li>2010-2013</li>
          <li>2014-2021</li>
        </ul>
      </div>
    </div>
  </div>
  <div class="page-biography-section-right-sub-section-right">
    <div class="page-content-section-right-img-container taille_1" rel="1944-1984">
      <img src="https://fastly.picsum.photos/id/175/536/354.jpg?hmac=EHlNLOT5uMj3h2CECyDN3o-puYqhu1a9chiXMuvQWCw" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur <br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_3" rel="1944-1984">
      <img src="https://fastly.picsum.photos/id/430/536/354.jpg?hmac=uxrNCXgJuycp2JMZ9jpZb5ThTsZIplRTSPuc4ybMyws" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur <br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_1" rel="1944-1984">
      <img src="https://fastly.picsum.photos/id/387/536/354.jpg?hmac=Zs1KZbc0jXe2zZP7yKL_OrUKxdUVFH0LqLoegVZnIuA" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur <br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_2" rel="1944-1984">
      <img src="https://fastly.picsum.photos/id/403/536/354.jpg?hmac=Cg78SPqGbiGuHfV34a5FcODRJKcDZ6BJu_xkudFYCrE" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur <br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_2" rel="1984-1998">
      <img src="https://fastly.picsum.photos/id/554/536/354.jpg?hmac=D-spLEtV3F0Tjf9bJcNPOFrqI2Qv6HgRkeydjD7dug8" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur<br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_3" rel="1984-1998">
      <img src="https://fastly.picsum.photos/id/870/536/354.jpg?hmac=AMJzzUg_6QocQmkby_VWRi3LY_D7E9NcYcT_j7kJsYw" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur<br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_1" rel="1984-1998">
      <img src="https://fastly.picsum.photos/id/436/536/354.jpg?hmac=7Tk-gHN3W43qiyfXxkZZ8VW3T4tubs1gD6xkYzifiRk" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur<br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_1" rel="1984-1998">
      <img src="https://fastly.picsum.photos/id/256/536/354.jpg?hmac=2oqqAgYp33LoAy3nMLztmG4prUmC1bQx0M7_iG9tnsA" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur<br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_3" rel="1998-2021">
      <img src="https://fastly.picsum.photos/id/1023/536/354.jpg?hmac=q17Uvpe-LDdjeCkEbPPP9qjcYpxVPRpzdTeloXPZaVY" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur <br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_3" rel="1998-2021">
      <img src="https://fastly.picsum.photos/id/879/536/354.jpg?hmac=DHlAvQ-DPSPs6YaodJBSc3a9sVFzvTqygKTW1cTbFFY" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur <br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_1" rel="1998-2021">
      <img src="https://fastly.picsum.photos/id/291/536/354.jpg?hmac=bfJIaH0FmtH4w44We3rF30m4Kd8zK4jsOAbLFVh2E20" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur <br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
    <div class="page-content-section-right-img-container taille_1" rel="1998-2021">
      <img src="https://fastly.picsum.photos/id/59/536/354.jpg?hmac=HQ1B2iVRsA2r75Mxt18dSuJa241-Wggf0VF9BxKQhPc" alt="dsds">
      <div class="caption">
        Lorem ipsum dolor sit amet, consectetur <br /> adipiscing elit, sed do eiusmod
      </div>
    </div>
  </div>
</div>

and CSS :

.page-biography-section-right {
  width: 85%;
  display: flex;
}

.page-biography-section-right-sub-section-left {
  width: calc(100% - (50% / 0.85));
}

.biography-bloc-text {
  padding: 15px;
  background-color: white;
  padding-bottom: 25vh;
  border-top: 0.5px solid;
  position:sticky;
  top: 85.5px;
}

.biography-bloc-text a {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.biography-bloc-text h1 {
  font-size: 61px;
  line-height: 68px;
}

.biography-bloc-text ul {
  list-style: none;
  font-size: 15px;
  line-height: 17px;
}

.page-biography-section-right-sub-section-right {
  width: calc(50% / 0.85);
}

.page-content-section-right-img-container {
  position: sticky;
  top: 85.5px;
  margin-bottom: 30px;
}

.page-content-section-right-img-container.taille_2 {
  padding-right: 25%;
}

.page-content-section-right-img-container.taille_3 {
  padding-right: 33%;
}

.page-content-section-right-img-container img {
  margin-bottom: 15px;
}

.caption {
  position: absolute;
  bottom: 15px;
  left: 15px;
  color: white;
}

img {
  width: 100%;
  height: auto;
  display: block;
}

Can anybody help me with this ? it’s possible to modify the css obvisously, the html too, and use jquery / javascript

here’s a jsfiddle :
https://jsfiddle.net/br3fqn2s/

Need Regex pattern space and hyphen validation [duplicate]

I need regex pattern for phone number with below protocols

  1. Phone number allow + symbol at first position only with optional value

  2. - (hyphen) should not allow first and last position . But hyphen can allow in between number but maximum three hyphen can allow

  3. Space can allow in between numbers but continuously should not allow more than one space .. but single space allow n number of times

Example of allowed patterns:

  • +34 35 45-45-55-4
  • 34-5-4-45 5 5 555

Example of invalid patterns:

  • 34 455 55-66— 5–
  • -455-
  • 444 55 - 5- -55

When I tried the following pattern, then 33445-445 4556 45666-4566 and 33445-445 4556 45666-4566 are not accepted:

/^+?d+(?:-d+){0,3}(?: d+){0,}$/gm

How to change browser langage on playwright

I’m trying to make my scraper stealthy.
The last hurdle for me is the browser language, in fact I can’t modify it no matter what the parameters are.

screenshot of the browserscan.net

I can modify the HTTP header for the language, but not the browser language, I searched in the system files of the playwirght browser but there is no parameter for that.

Here is a minimal part of my code :

const { firefox } = require('playwright-extra');
const stealth = require('puppeteer-extra-plugin-stealth')();


firefox.use(stealth);
firefox.launch({
  headless: false,
  args: ['--lang=fr-FR'],
}).then(async browser => {

  const context = await browser.newContext({

    locale: 'fr-FR',
    timezoneId: 'Europe/Paris',
    geolocation: { latitude: 48.8566, longitude: 2.3522 },
  });

  const page = await context.newPage();
  await page.setExtraHTTPHeaders({
    'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
  });

  console.log('Navigating to test browser language settings...');

  const url = 'https://www.browserscan.net/';
  
  await page.goto(url, { waitUntil: 'networkidle0' });
  await page.screenshot({ path: 'browser-language.png', fullPage: true });

  console.log('Done! Check browser-language.png for results.');
  await browser.close();
})

Does anyone have a clue?

How can I skew certain y-axis values on a line chart in ECharts?

I’m building a line chart in ECharts, but I want to skew/weight a specific range of the y-axis to be larger than it would be linearly. For example, I would like values 0-70 to take up 1/3 of the chart size and the remaining 70-100 to take up 2/3. I don’t have much experience with charting, so I’m a little lost on the best approach.

An example of a chart that doesn't have any skewing with visual indicators of what should be skewed

Here are the ECharts options I’m using to create the line chart, also available in this Codesandbox:

import { format } from "date-fns";
import { createFakeValues } from "../utils";

const dataValues = createFakeValues({
  yValues: [29, 32, 35, 40, 47, 49, 50, 49, 48, 45, 43, 39, 35, 30, 27, 25, 24],
  startDate: new Date("2024-12-01T18:27:08.199Z"),
  dateDeltaMs: 1800000,
});

const eChartsDataValues = dataValues.map((dv) => [dv.date, dv.value]);

export const eChartsOptions = {
  dataset: [
    {
      source: eChartsDataValues,
      dimensions: ["timestamp", "value"],
    },
  ],
  xAxis: {
    type: "time",
  },
  yAxis: {
    min: 0,
    max: 50,
  },
  series: [
    {
      name: "Y Level",
      type: "line",
      smooth: true,
      datasetIndex: 0,
      showSymbol: false,
      encode: {
        x: "timestamp",
        y: "value",
      },
      markArea: {
        silent: true,
        emphasis: {
          disabled: true,
        },
        label: {
          fontSize: 12,
          textBorderColor: "transparent",
          position: "insideBottomLeft",
        },
        data: [
          [
            {
              name: "This is mathematically a shorter range (40-50), but it should take up the majority of space on the graph",
              yAxis: 40,
              itemStyle: {
                color: "red",
              },
            },
            {
              yAxis: 50,
            },
          ],
          [
            {
              name: "This is mathematically a bigger range (0-40) but should take up a smaller section of the graph",
              yAxis: 0,
              itemStyle: {
                color: "green",
              },
            },
            {
              yAxis: 40,
            },
          ],
        ],
      },
    },
  ],
};

add nested attributes with javascript

I’m having trouble creating a JSON structure as javascript objects. Basically I have a JSON object coming into my javascript program then the program updates it and the object ships back out.

lets say I import this JSON structure:

{
  "123":{
itemname: "name",
itemprice: "price"
  }
  "456":{
itemname: "name2",
itemprice: "price2"
  }
}

And I want this output:

{
  "123":{
itemname: "name",
itemprice: "price"
  }
  "456":{
itemname: "name2",
itemprice: "price2"
  }
  "789":{
itemname: "name3",
itemprice: "price3"
  }
}

I would use the JSON.parse on input and JSON.stringify on output.

If in PHP, $json contained this structure decoded, then I could add my entry via:

$json['789']['itemname']='name3';
$json['789']['itemprice']='price3';

So in Javascript, I tried this (assume x is the structure decoded via JSON.parse):

var i="789",j="itemname";
if(!x[i]){x[i]={}}
if(!x[i][j]){x[i][j]="";}
x[i][j]+=n;

and somewhere in that declaration my web browser locks up and the javascript console does not react. The values of i and j are set to fixed values as an example, but the values can change in the real program.

What am I doing wrong?

‘addEventListener’ does not work for HTML Web Component

I made web component like below.

Webtest.js

class Webtest extends HTMLElement {
    constructor() {
        super();
    }

    connectedCallback() {
        this.attachShadow({mode: 'open'});
        this.shadowRoot.innerHTML = `
            <style>
                .special {
                    color: green; /* Active link styling */
                    font-weight: bold;
                }
            </style>

            <a id="testId" href="/mypath/index.html">textA</a>
            <a id="testId" href="/mypath/subfolderA/subfolderA.html">textB</a>
            <a id="testId" href="/mypath/subfolderB/subfolderB.html">textC</a>
            <a id="testId" href="/mypath/subfolderC/subfolderC.html">textD</a>
        `;

        const links = this.shadowRoot.querySelectorAll("#testId");
        
        links.forEach(link => {
            link.addEventListener('click', () => {
                this.shadowRoot.querySelector('.special')?.classList.remove('special');
                link.classList.add('special');
            });
        });
    }
}
customElements.define('webtest-component', Webtest);

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="color-scheme" content="dark">
    <script src="./Webtest.js"></script>
</head>

<body>
    <webtest-component></webtest-component>    
</body>

</html>

I have 4 hyperlinks on top of page like this.
enter image description here

I want to highlight the text of last clicked link (one of textA, textB, textC, textD) by inserting special class to last clicked link. But it does not work.

What I tried:
Use ‘addEventListener’ to get the click effect.
click effect:

  1. Remove ‘special’ class from last clicked one.
  2. Add ‘speical’ class to last clicked one.
  3. Since ‘special’ class is defined in style section, it should be highlighted.

Expecting result:
After clicking each text, each text should be highlighted as green color and bold.

Thank you for your help!


According to Nick and Bravo’s help, this is what’s happening. (Thank you very much!)

After clicking page, class properly gets updated but the page redirects to another page and gets refreshed.

So the updated class by the JS only lasts momentarily before the page refreshes.

I want to navigate to each page AND highlight the text of last clicked link.
I want to keep my format as it is.
Any suggestions would be really appriciated!
If you think it is not possible, kindly share as well!
Thank you.

Best Practice for Securing Access Token Server Side

I am looking for some best practices regarding security of an access token. I am building a React / Next JS 14 app and I am using a third party to retrieve financial data from a user’s bank account (Plaid), and one of the things that is sent back when they connect a bank account is an access token. This access token is a permanent identifier of the account / user, and does not expire. I have stored it in the database on the user’s table; however, I don’t know exactly how to use it.

I know it is bad security to expose the access token on the client side; but does this mean that every time I perform a plaid request on the server side, I first have to make a call to my database (based on something like user id), to get the access token? This sounds sort of tedious and inefficient to have to make this same database call for all of my plaid calls to get the access token, but is this just best practice and something I have to put up with? Or is there some sort of way to cache the access token server side for reuse? I know of caching using local, session, and cookies on the browser, but again that is client side and insecure. I am not sure what to do here. Any thoughts sure would be helpful. Thanks!!

Is there any way to show LaTeX in Markdown – React Native

I’m building an AI assistant app and have been struggling to display LaTeX content alongside Markdown-rendered text. Currently, I’m using react-native-markdown-display for Markdown support and the (deprecated) react-native-math-view for LaTeX.

One solution I attempted was to parse the content with a regex to split out Markdown vs. LaTeX segments, then conditionally render them using <Markdown /> or <MathView />. While this works to some extent, it introduces significant alignment and formatting issues.

Below is my current MessageRenderer component, which implements this approach:

import React from 'react';
import {StyleSheet, Text, View} from 'react-native';
import MathView, {MathText} from 'react-native-math-view';
import {textStyle} from "../styles/common.style";
import Markdown from "react-native-markdown-display";
import {MsgType} from "./class/MessageItem";

const MessageRenderer = ({message, type}) => {
    const parts = parseMessage(message);
    
    return (
        <View style={styles().main}>
            {parts.map((part, index) => {
                if (part.type === 'text') {
                    return (
                        <Markdown 
                            key={index} 
                            style={{ body: type === MsgType.USER ? styles().normalText : styles().assistantNormalText }}
                        >
                            {part.content}
                        </Markdown>
                    );
                } else if (part.type === 'math') {
                    return (
                        <MathView
                            key={index}
                            math={part.content}
                            style={styles().mathText}
                        />
                    );
                }
                return null;
            })}
        </View>
    );
};

const parseMessage = (message) => {
    const regex = /\(([sS]*?)\)|\[([sS]*?)\]/g; // Matches math expressions within (...) or [...]
    const parts = [];
    let lastIndex = 0;
    
    try {
        message.replace(regex, (match, group1, group2, index) => {
            // Add text content before the current match
            if (lastIndex < index) {
                parts.push({ type: 'text', content: message.slice(lastIndex, index) });
            }
            
            // Add the matched math content
            const formula = group1 || group2; 
            parts.push({ type: 'math', content: formula });
            
            // Update the lastIndex to the end of the current match
            lastIndex = index + match.length;
        });
        
        // Add any remaining text after the last match
        if (lastIndex < message.length) {
            parts.push({ type: 'text', content: message.slice(lastIndex) });
        }
    } catch (e) {
        console.log("error", e);
        return parts;
    }
    
    return parts;
};

const styles = () => {
    return StyleSheet.create({
        main: {
            flexDirection: 'row',
            flexWrap: 'wrap',
            alignItems: 'center'
        },
        normalText: {
            ...textStyle.Body_4,
            color: 'white'
        },
        mathText: {
            ...textStyle.Body_4,
            marginHorizontal: 2,
            color: 'white'
        },
        assistantNormalText: {
            ...textStyle.Body3,
            color: 'white'
        }
    });
};

export default MessageRenderer;

Sample Test Data

const message = `

- This is a paragraph with some inline math: \(E = mc^2\).

- Some text with inline math \(a^2 + b^2 = c^2\)

- And block math

\[
e = sum_(n=0)^oo 1/n!
\]

\[
\int_{a}^{b} x^2 dx
\]

Here is a JavaScript code block:

```javascript
function greet() {
  console.log("Hello, world!");
}
```

And some more inline math: \(a^2 + b^2 = c^2\).
`;

Question
Is there a more robust or straightforward method to render both Markdown and LaTeX together in React Native without resorting to manually parsing the content via regex?

Cómo hacer que el carrito de una pagina de Compras muestre la cantidad de productos y los productos? [closed]

Estoy construyendo un proyecto de carrito de compras. He avanzado bastante,

  • Ya revisé la sintaxis de todos los componentes, y me parecen, están bien.

  • Pruebas a través de la consola para verificar si se está llamando correctamente el dispatch, y si lo está haciendo.

  • El reducer está retornando un nuevo estado correctamente.

  • Se renderizan en el navegador los elementos

Sin embargo, aún no logro que el carrito de compras realicé la acción de mostrar el contenido, los ítems y la suma de los mismos; tal como lo cree en el componente CartPage.jsx, y cuando voy agregando productos solo me muestra que existe un ítem en el icono del carrito.


    import { useContext } from "react"
    import { CartContext } from "../context/CartContext"
    
    
    export const CartPage = () => {
    
      const { shoppingList, increaseItem, decreaseItem, removePurchase } = useContext(CartContext)
      console.log("Shopping list in CartPage:", shoppingList);
      
      const calculateTotal = () => {
        return shoppingList.reduce((total, item) => total + item.price * item.quantity, 0).toFixed(2) 
      }
      
      const handlePrint = () => {
      //  print()
      };
    
      return ( 
        <>
          <table className="table">
            <thead>
              <tr>
                <th scope="col">Name</th>
                <th scope="col">Price</th>
                <th scope="col">Quantity</th>
                <th scope="col">Remove</th>
              </tr>
            </thead>
            <tbody>
              {
                shoppingList.map(item => (
                  <tr key={item.id}>
                    <th>{item.title}</th>
                    <td>{item.price}</td>
                    <td>{item.quantity}</td>
                    <td>
                      <button className="btn btn-outline-primary"
                      onClick={ () => decreaseItem(item.id) }>-</button>
                      <button className="btn btn-primary"> {item.quantity} </button>
                      <button className="btn btn-outline-primary"
                      onClick={ () => increaseItem(item.id) }>+</button>
                    </td>
                    <td>
                      <button
                      type="button"
                      className="btn btn-danger"
                      onClick={()=>removePurchase(item.id)}>
                      Remove
                      </button>
                      </td>
                  </tr>
                ))
              };
    
              <th> <b>TOTAL: </b> </th>
              <td></td>  
              <td></td>  
              <td>${calculateTotal()}</td>  
    
            </tbody>
          </table>
    
          <div className="d-grid gap-2">
            <button 
            className="btn btn-primary"
            onClick={handlePrint}
            disabled={shoppingList>1}
            > Buy </button>
          </div>
    
        </>
      )
    }


    import './App.css';
    import { Route, Routes, Navigate } from 'react-router-dom';
    import { NavBar } from './Components/NavBar';
    import { ShoppingPage } from './Pages/ShoppingPage';
    import { CartPage } from './Pages/CartPage';
    import { ProductsProvider } from './context/ProductsProvider';
    import { CartProvider } from './context/CartProvider';
    
    function AppCart() {
      return (
        <ProductsProvider>
          <CartProvider>
            <NavBar> </NavBar>
            <div className="container">
              <Routes>
                <Route path='/' element={<ShoppingPage></ShoppingPage>}></Route>
                <Route path='/little cart' element={<CartPage></CartPage>}></Route>  
                <Route path='/*' element={<Navigate to='/' />}></Route> 
              </Routes> 
            </div>    
            </CartProvider>  
        </ProductsProvider>
      );
    }
    
    export default AppCart;

  • En la depuración en consola con (“Add Purchase:”, action.pyload, state); refleja objeto en consola, las características solicitadas y la cantidad es un número que aumenta conforme vas adicionando productos.

  • La prueba realizada con console.log “Adding product:” en el shoppingList presenta los datos correctamente

  • El estado shoppingList refleja los cambios en consola y el quantity está actualizando los cambios


    import { CartContext } from "./CartContext";
    import { useReducer } from "react";
    
    const initialState = []
    
    export const CartProvider = ({ children }) => {
        
    const shoppingReducer = (state = initialState, action = {}) => {
        console.log("Reducer action:", action);
        switch (action.type) {
            case '[CART Add Purchase]':
                console.log("Add Purchase Reducer State:", state);
                console.log("Add Purchase:", action.payload, state);
                const existingProduct = state.find(item => item.id === action.payload.id);
                if (existingProduct) {
                    return state.map(item =>
                        item.id === action.payload.id
                            ? {...item, quantity: item.quantity + 1}
                            : item
                     );
                } else {
                    return [...state, {...action.payload, quantity: 1 }];
                }
                           
            case '[CART] Increase item Purchase': // TODO: Add quantity and to modify
                console.log("Increase Reducer State:", state);
                        return state.map(item => 
                            item.id === action.payload 
                            ? {...item, quantity: item.quantity + 1}
                            : item
                        );
                        
            case '[CART] Decrease item Purchase': // TODO: Add quantity and to modify
                        return state.map(item => 
                            item.id === action.payload 
                            ? {...item, quantity: item.quantity - 1 }
                            : item
                        );
    
            case '[CART] Remove Purchase':
                return state.filter(item => item.id !== action.payload)
    
            default:
                return state;
        }
    }; 
    
    
        const [shoppingList, dispatch] = useReducer(shoppingReducer, initialState)
        console.log("Shopping list in CartPage:", shoppingList);
    
        const addPurchase = (product) => {
            console.log("Adding product:", product);
            const action = {
                type: '[CART Add Purchase]',
                payload: product 
            } 
            dispatch(action)    
        }
    
        const increaseItem = (id) => { 
            const action = {
                type: '[CART] Increase item Purchase',
                payload: id
            }              
            dispatch(action)
            console.log("Increasing item with ID:", id); // Depuration
            dispatch({ type: '[CART] Increase item Purchase', payload: id });
    
        };
    
        const decreaseItem = (id) => {
            const action = {
                type: '[CART] Decrease item Purchase',
                payload: id
            }                         
            dispatch(action)    
        };
    
        const removePurchase = (id) => { 
            const action = {
                type: '[CART] Remove Purchase',
                payload: id
            }          
            dispatch(action)    
        };
    
    
      return (
        <CartContext.Provider value={{shoppingList, addPurchase, increaseItem, decreaseItem, removePurchase}} >
            {children}
        </CartContext.Provider>
      )
    } 

Una parte de la Impresión en consola:

    Adding product: {purchase: {…}}purchase: category: "men's clothing"description: "Your perfect pack for everyday use and walks in the forest. Stash your laptop (up to 15 inches) in the padded sleeve, your everyday"id: 1image: "https://fakestoreapi.com/img/81fPKd-2AYL._AC_SL1500_.jpg"price: 109.95rating: {rate: 3.9, count: 120}title: "Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops"[[Prototype]]: Object[[Prototype]]: Object
    CartProvider.jsx:9 Reducer action: {type: '[CART Add Purchase]', payload: {…}}
    CartProvider.jsx:12 Add Purchase Reducer State: [{…}]
    CartProvider.jsx:13 Add Purchase: {purchase: {…}} [{…}]0: purchase: {id: 1, title: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops', price: 109.95, description: 'Your perfect pack for everyday use and walks in th…to 15 inches) in the padded sleeve, your everyday', category: "men's clothing", …}quantity: 5[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)
    CartProvider.jsx:50 Shopping list in CartPage: [{…}]
    CartProvider.jsx:9 Reducer action: {type: '[CART Add Purchase]', payload: {…}}
    CartProvider.jsx:12 Add Purchase Reducer State: [{…}]
    CartProvider.jsx:13 Add Purchase: {purchase: {…}} [{…}]
    CartProvider.jsx:50 Shopping list in CartPage: [{…}]0: purchase: {id: 1, title: 'Fjallraven - Foldsack No. 1 Backpack, Fits 15 Laptops', price: 109.95, description: 'Your perfect pack for everyday use and walks in th…to 15 inches) in the padded sleeve, your everyday', category: "men's clothing", …}quantity: 6[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)
  • Ya revisé el map. en el shoppingList (componente CartPage) y, validé enviando directamente { …product} en el componente CartProvider, pero aún nada.

Esta es la construcción de mi ShoppingPage:


    import React, { useContext } from "react";
    import { Card } from "../Components/Card";
    import { ProductsContext } from "../context/ProductsContext";
    import { CartContext } from "../context/CartContext";
    
    export const ShoppingPage = () => {
      
      const { products } = useContext(ProductsContext);
    
      const handleAdd = ( purchase ) =>{
        addPurchase({
          purchase
        });
      };  
      const handleRemove = (id) =>{
        removePurchase(id)
      };
    
      const {
        addPurchase,
        removePurchase,
      } = useContext(CartContext);
    
      
      return (
        <>
          <h1>Shopping: </h1>
          <hr />
    
          {products.map(product => (
            <Card
              key={product.id}
              image={product.image}
              title={product.title}
              description={product.description}
              price={product.price}
              handleAdd={() => handleAdd(product)}
              handleRemove={() => handleRemove(product.id)}
            >
    
            </Card>
          ))};
        </>
      );
    }

How can I start search after setting value of search field?

I am trying to set the value of a search box using JavaScript in Chrome’s console, as shown in this screenshot:

enter image description here

I use the following code to set the value:

document.querySelector("body > main > eup-orders > div > div > div > div.table-header.form-inline.clearfix.with-search > form > div > div > input").value = "Hello World";

Next, I want to trigger the search by clicking the search button, as shown in this screenshot:

enter image description here

Here’s the code I use to click the button:

document.querySelector("#btn-search").click();

The problem: Although the value is successfully set in the search field, the search does not start unless I manually click inside the search field.

Question: Is there a way to programmatically trigger the update of the search field so it works without manual interaction?
Alternatively, is it possible to simulate pressing the Enter key?

Javascript AJAX request with 2 different return types

Is it possible to return 2 different types by an AJAX request?
I created a form with method post. The PHP file creates a PDF file what is returned to the JavaScript file and is automatically downloaded.

But I want also return an array to the same JavaScript file with messages like errors or a notice.

Can I do this in one call or is there a second call needed?

var form = event.target;
var formData = new FormData(form);
fetch(url,{
    method: 'post',
    body: formData
}).then(response => response.blob()).then(response => {
    const blob = new Blob([response], {type: 'application/pdf'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = formData.getAll("invoicenumber")+".pdf";
    document.body.appendChild(a);
    a.click();
});

PHP

$createPdf = new CreatePdf;
$response['msg'] = 'PDF is created!';
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($response);