Anonymous function vs Arrow function

Is there any difference between the below two functions?

function Person(name) {
    Object.assign(this, {name});
}
Person.prototype.greet1 = () => {
    console.log(`Hello, ${this.name}.`);
}
Person.prototype.greet2 = function() {
    console.log(`Hello, ${this.name}.`);
}

console.log(Person.prototype);
//{ greet1: [Function (anonymous)], greet2: [Function (anonymous)] }

They both print ‘anonymous function’. My guess is they are the same except for the fact that the arrow function will not not have a scoped this within the function body — is that accurate, or what’s the difference in the above two greet functions?

Discord Webhook not sending when i use to post data to a database

When I put under

<button type="submit" name="submit" class="btn btn-success w-100" onclick="sendWebhook(`${document.getElementById('HookURL').value}`, `${document.getElementById('HookAuthor').value}`,`${document.getElementById('HookAvatar').value}`,`${document.getElementById('HookMsg').value}`);">Realizar Cambio</button>

it does not send the information to the database but it does send the webhook. But when I put it below it does not send the webhook but it does send the information to the database.

React render string interpolated component passed via attribute of parent component

I am trying to render a function based on an array of Object values. React is rendering as a string rather than a component. The desired component render is an imported Icon. I have tried various solutions found in other questions related to , react-jsx-parse, and so on. Non of these solutions have worked for this case.

import {
  LinkedIn,
  GitHub,
  Instagram,
  Camera,
  Favorite,
  Palette,
  Motorcycle,
} from "@mui/icons-material"; 
import myJsonInfo from "./myJsonInfo";
import AppBar from "@mui/material/AppBar";
import Tabs from "@mui/material/Tabs";
import Tab from "@mui/material/Tab";

function myPage(){

return (
...
               <AppBar position="static">
                  <Tabs
                    value={value}
                    onChange={handleChange}
                    indicatorColor="secondary"
                    textColor="inherit"
                    variant="fullWidth"
                    aria-label="full width tabs example"
                  >
                    {myJsonInfo.map((tab, id) => ( 
                      <Tab
                        label={tab.tabButton}
                        icon={`<${tab.tabIcon} sx={{ fontSize: 40 }} />`}
                        iconPosition="top"
                        key={id}
                      />
                    ))}
                  </Tabs>
                </AppBar>
...
)

I am expecting the interpolation to render…but the actual render is …

...
icon={<Camera sx={{ fontSize: 40 }} />}    
icon={"<Camera sx={{ fontSize: 40 }} />"}
...

Here is the json object…

export const myJsonInfo = [
  {
    tabButton: "PHOTOGRAPHY",
    tabIcon: "Camera",
    photos: [
      {
        src: "https://live.staticflickr.com/4894/45935502555_2f67f4525e_m.jpg",
        width: "240",
        height: "180",
        alt: "20190110_131623"
      },
      {
        src: "https://live.staticflickr.com/4413/36739958362_d6b357e792_m.jpg",
        width: "240",
        height: "86",
        alt: "_DSC1990-Pano"
      },
      {
        src: "https://live.staticflickr.com/849/39718694400_97c278f836_m.jpg",
        width: "240",
        height: "160",
        alt: "_DSC3436"
      },

      {
        src: "https://live.staticflickr.com/869/40528225894_2eac07c24e_m.jpg",
        width: "240",
        height: "180",
        alt: "GOPR0332"
      },
      {
        src: "https://live.staticflickr.com/1846/44291032431_9050d0e351_m.jpg",
        width: "240",
        height: "97",
        alt: "20180818_082245"
      },
      {
        src: "https://live.staticflickr.com/933/43285116024_690e779504_m.jpg",
        width: "240",
        height: "117",
        alt: "20180812_114422"
      }
    ]
  },
...

PHP session variable can not be accessed from another PHP file

I am POSTING some data from a React component to a PHP file running on xampp server. Currently, the project is under development, so I am using create-react-app (npm) which runs on the localhost:3000 port And the PHP file runs under localhost:80.

The PHP file which runs under port 80 does some processing and then echoes the processed data. My design structure needs that piece of data to another PHP file that runs on the same port 80. So I tried to share the data via PHP session variable but strangely the other PHP file can not read the data from the session variable. IT says empty. This is happening if I post data from React (localhost:3000) to PHP(localhost:80) and try to share the data via SESSION. But SESSION variable works normally when sharing PHP to PHP on port 80.

Here is the react snapshot code ->

//send msg and trigger the backend flush for frontend sse
function sendMsgHandler(){
    if(chatWith !== undefined && chatWith.length > 0){
        const msgElm = document.querySelector('.chat-input');
        var msg = msgElm.value.trim()
        if(msg == undefined || msg == "" || msg == null){
            return;
        }else{
            var date = new Date().toISOString().slice(0, 19).replace('T', ' ');
            //SET VALUE EMPTY ON INPUT 
            msgElm.value = null;
            const wishTochat = chatWith;
            const CurrentUser = thisUser.id;
            var newMsgObject = {user: CurrentUser, chattingTo: wishTochat, data: msg, dt: date }
            //send data to backend
            setTimeout(() => {
                fetch(insertURL, {
                    mode:'cors',
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Origin':'*',
                    },
                    body:JSON.stringify(newMsgObject)
                    }).then(Response => {return Response.json()})
                    .then(data => {
                        setChatHistory(prev => [...prev, data] );
                        //console.log(data)
                    })
                    .catch(error => console.log("error"))
            },10)

            window.setTimeout(function() {
                var elem = document.querySelector('.chatbox-show-content');
                elem.scrollTop = elem.scrollHeight;
            }, 100);   
        }      
   }
}

And here is the PHP snapshots ->

session_set_cookie_params(233423, "/" , '.http://localhost',false,false);

$params = session_get_cookie_params();

if (session_status() !== PHP_SESSION_ACTIVE) { session_start(); }
header('Cache-Control: no-cache');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-CSRF-Token");



require_once('conn.php');


$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';

if ($contentType === "application/json") {
  //Receive the RAW post data.
  $content = trim(file_get_contents("php://input"));
  $decoded = json_decode($content, true);
      $arg = array(
        'id' => FILTER_SANITIZE_SPECIAL_CHARS,
      ); 
      //$decoded = filter_var_array($decoded,$arg);
  
  //If json_decode failed, the JSON is invalid.
  if(! is_array($decoded)) {
    echo json_encode("invalid");
  } else {
  
    $tableName_1 = "chatBox_".$decoded['user']."_".$decoded['chattingTo'];
    $tableName_2 = "chatBox_".$decoded['chattingTo']."_".$decoded['user'];
        $tableNames = [$tableName_1,$tableName_2];
        $tableName = null;
        foreach($tableNames as $table){
            $sql = "SHOW TABLES LIKE '".$table."'";
            $res = run_query($sql,$mysqli);
            $row = mysqli_fetch_row($res);
              if($row > 0){
                $tableName = $table;
              }
        }

      $currentUser = "user_".$decoded['user'];
      $chattingWith = "user_".$decoded['chattingTo'];
      $data = $decoded['data'];
      $time = $decoded['dt'];
       
      $insertData = "INSERT INTO $tableName  ($currentUser, `dt`, $chattingWith)
                     VALUES('".$data."','".$time."','')";
      sleep(.5);
      $res = run_query($insertData,$mysqli);
      $last_id = mysqli_insert_id($mysqli);
      
      $getLastData = "SELECT * FROM $tableName WHERE `id` = $last_id";
      $data = run_query($getLastData, $mysqli);
      $arr = mysqli_fetch_assoc($data);
      
      
      $_SESSION["last_datas"] = json_encode($arr);
      session_write_close();
      echo $_SESSION["last_datas"];
  }

}

How can I share the $_SESSION[“last_datas”] on another PHP file on localhost:80 or what I am doing wrong? I am going nuts trying to figure it out for days!!!

Your help would be much appreciated.

False promise and stylesheet not loading error on a simple D3 barchart visualization

I am not sure why I am getting a false promise and stylesheet not loading error. I think everything looks good in my code. Please feel free to look at my code and let me know if you see anything wrong. Thank you!
It returns a false promise on the console and the error is: Refused to load the stylesheet 'https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600,700' because it violates the following Content Security Policy directive: "default-src 'none'". Note that 'style-src-elem' was not explicitly set, so 'default-src' is used as a fallback.
This is the code I have for the TS file:

import { Component, AfterViewInit } from '@angular/core';
import * as d3 from 'd3';

@Component({
  selector: 'pie-chart',
  templateUrl: './pie-chart.component.html',
  styleUrls: ['./pie-chart.component.css'],
})
export class PieChartComponent implements AfterViewInit {
  svg: any = null;
  g: any = null;
  rects: any = null;
  name: string = '';
  age: number = null;
  convertedData: Map<string, number> = new Map();
  readonly MARGIN = { LEFT: 100, RIGHT: 10, TOP: 10, BOTTOM: 130 }
  readonly WIDTH = 600 - this.MARGIN.LEFT - this.MARGIN.RIGHT
  readonly HEIGHT = 400 - this.MARGIN.TOP - this.MARGIN.BOTTOM

  constructor() {}
  async ngAfterViewInit() {

    this.svg = d3
      .select('#canvas-area')
      .append('svg')
       .attr("width", this.WIDTH + this.MARGIN.LEFT + this.MARGIN.RIGHT)
        .attr("height", this.HEIGHT + this.MARGIN.TOP + this.MARGIN.BOTTOM)

        this.g = this.svg.append("g")
        .attr("transform", `translate(${this.MARGIN.LEFT}, ${this.MARGIN.TOP})`)

        // X label
this.g.append("text")
.attr("class", "x axis-label")
.attr("x", this.WIDTH / 2)
.attr("y", this.HEIGHT + 110)
.attr("font-size", "20px")
.attr("text-anchor", "middle")
.text("The word's tallest buildings")

// Y label
this.g.append("text")
  .attr("class", "y axis-label")
  .attr("x", - (this.HEIGHT / 2))
  .attr("y", -60)
  .attr("font-size", "20px")
  .attr("text-anchor", "middle")
  .attr("transform", "rotate(-90)")
  .text("Height (m)")

  await d3.json('app/data/data.json').then((data) => {
    data.forEach((d)=>{
      this.convertedData.set(d['name'], Number(d['height']));
    });
    console.log(this.convertedData);

    const x = d3.scaleBand().domain(this.convertedData.map(d => d.name))
    .range([0, this.WIDTH])
    .paddingInner(0.3)
    .paddingOuter(0.2)

    const y = d3.scaleLinear()
    .domain([0, d3.max(this.convertedData, d => d[1]) as number])
    .range([0, this.HEIGHT])

    const xAxisCall = d3.axisBottom(x)
  this.g.append("g")
    .attr("class", "x axis")
    .attr("transform", `translate(0, ${this.HEIGHT})`)
    .call(xAxisCall)
    .selectAll("text")
      .attr("y", "10")
      .attr("x", "-5")
      .attr("text-anchor", "end")
      .attr("transform", "rotate(-40)")

  const yAxisCall = d3.axisLeft(y)
    .ticks(3)
    .tickFormat(d => d + "m")
  this.g.append("g")
    .attr("class", "y axis")
    .call(yAxisCall)

    this.rects = this.svg.selectAll('rect').data(this.convertedData);

    this.rects
      .enter()
      .append('rect')
      .attr('y', 0)
      .attr('x', (d)=>x(d.name))
      .attr('width', x.bandwidth)
      .attr('height', d=> y(d.height))
      .attr('fill', 'gray')
  })
}
}

And, this is data.json:

[{
        "name": "Burj Khalifa",
        "height": "350"
    },
    {
        "name": "Shanghai Tower",
        "height": "263.34"
    },
    {
        "name": "Abraj Al-Bait Clock Tower",
        "height": "254.04"
    },
    {
        "name": "Ping An Finance Centre",
        "height": "253.20"
    },
    {
        "name": "Lotte World Tower",
        "height": "230.16"
    }
]

Extending letters only directive @ Angular

While searching for the optimal solution for only digits directive, I got the following answer to the question I asked:


import { Directive, HostListener, Input, ElementRef } from '@angular/core';

@Directive({
  selector: '[appOnlyDigits]'
})
export class OnlyDigitsDirective {
  constructor(private element: ElementRef) { }

  @Input() allowMultiLine = false;
  @Input() allowNegative = false;
  @Input() allowDecimal = false;
  @Input() maxLength = 0;
  regex!: RegExp;

  @HostListener('keypress', ['$event'])
  onKeyPress(event: KeyboardEvent) {
    this.validate(event, event.key === 'Enter' ? 'n' : event.key);
  }

  @HostListener('paste', ['$event'])
  onPaste(event: Event) {
    const pastedText = (window as any).clipboardData
      && (window as any).clipboardData.getData('Text') // If IE, use window
      || (event as ClipboardEvent)
      && (event as ClipboardEvent).clipboardData!.getData('text/plain'); // Non-IE browsers
    this.validate(event, pastedText);
  }

  @HostListener('cut', ['$event'])
  onCut(event: Event) {
    this.validate(event, '');
  }

  validate(event: Event, text: string) {
    const txtInput = this.element.nativeElement;
    const newValue = (txtInput.value.substring(0, txtInput.selectionStart)
      + text + txtInput.value.substring(txtInput.selectionEnd));
    if (!this.regex) {
      // tslint:disable-next-line: no-eval
      this.regex = (eval('/^'
        + (this.allowNegative ? '-?' : '')
        + (this.allowDecimal ? '((\d+\.?)|(\.?))\d*' : '\d*')
        + '$/g') as RegExp);
    }
    const lines = this.allowMultiLine ? newValue.split('n') : [newValue];
    for (const line of lines) {
      const lineText = line.replace('r', '');
      if (this.maxLength && lineText.length > this.maxLength
        || !lineText.match(this.regex)) {
        event.preventDefault();
        return;
      }
    }
  }

}

It works perfectly and now I want to create an extended letters only directive using this structure.

I changed the condition inputs first:


  @Input() allowSpaceBar = true;
  @Input() allowSpecialChars = false;
  @Input() allowTabs = false;

and I tried to modify condition area like this:


    if (!this.regex) {
      // tslint:disable-next-line: no-eval
      this.regex = (eval('/^[a-zA-Z]+'
        + (this.allowSpaceBar ? '[ ]' : '')         // <- 1st Condition
        + (this.allowSpecialChars ? '[!?*#]' : '')  // <- 2nd Condition
        + (this.allowTabs ? '^w+(s+w+)*' : '')   // <- 3rd Condition
        + '$/g') as RegExp);
    }

..but it does not work. How to correct that?

Find an element in an array that matches the regex given

I am having an array of different elements in the string format, I wanted to check whether an array contains date field in it. Currently I am thinking of using a date regex and then match it with all the elements in an array, but I am not sure of how to use that.

 let arr = ['SUPERMARKET', '465', 'S', 'Arroyo', 'Pkwy', 'Pasadena,', 'CA', '91105', '1', '1', '1', 'DOZ', 'FREE', 'RANGE', 'EGG', '$3.89', 'GV', 'ORGANIC', 'MILK', '2%', '$4.19', 'SBUX', 'FRENCH', 'ROAST', 'WL', '$8.99', 'SUBTOTAL', '$17.07', 'TOTAL', '$17.07', '$17.07', 'PURCHASE', '$17.07', 'VISA', 'DEBIT', '3991', 'Auth', '#140987', 'Exp', 'Date', '**/**', 'Lane', '#14', 'Cashier', '1409', '11/21/2019', '01:28', 'PMRef/Seq', '#140987', 'MRCH', '204650', 'Term=001', 'IC=CC', 'EPS', 'Sequence', '934518', 'ITEM', '1', 'H,', 'STEPHIE', '11/21/2019', '01:28', 'PM', '4130', '29', '1041', '2675']

 let dateRegex = "^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$"

Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] [duplicate]

Recently I followed a tutorial for making a forum with PHP and MySQL. Then I got this error:
Error: parsererror – SyntaxError: Unexpected token < in JSON at position 0
I figured out why it was saying that. There was a error on save.php and which was caused due to a error in conn.php this is the full error on conn.php :
Fatal error: Uncaught PDOException: SQLSTATE[HY000] [2002] No such file or directory in /home/runner/AnchoredHeftyTrigger/conn.php:6 Stack trace: #0 /home/runner/AnchoredHeftyTrigger/conn.php(6): PDO->__construct(‘mysql:host=loca…’, ‘root’, ”) #1 {main} thrown in /home/runner/AnchoredHeftyTrigger/conn.php on line 6
This is the code of conn.php:

<?php
session_start();
$db_username = 'root';
$db_password = '';

$conn = new PDO('mysql:host=localhost;dbname=forum', 
                $db_username, $db_password);
if(!$conn){
die("Fatal Error: Connection Failed!");
}

?>

I’m sorry if I’m not giving much information: I’m very new with PHP and JSON

Dom in javascript , I am new at programming so please can anybody help me regarding this assigment?

Q1. Write a JavaScript function that takes an array and a value and search that value in the given array. Write a function which takes two arguments – an array and a value. If the value provided in the argument is found in the array, the function should return the position of the element in an array. If the element is not found, the function should return “-1”.

Test the code by defining an array and pass that array as an argument in your function

Read more/read less only works after first click

I am trying to implement a read more button for a long paragraph. Not really sure what the issue is maybe there is some styling that is overwriting what I have written. When I remove the id styling it still functions the same way.

Here is my javascript function

function myFunction() {
    var moreText = document.getElementById("more");
    var btnText = document.getElementById("myBtn");

    if (moreText.style.display === "inline") {
        btnText.innerHTML = "Read More";
        moreText.style.display = "none";
    }
    else{
        btnText.innerHTML = "Read less"; 
        moreText.style.display = "inline";
    }
  }

Here is my CSS styling (I am using tailwindCSS with this webpage)

#more {
    display: none;
}

Here is my Html code

<div class="flex flex-wrap justify-center text-center lg:text-left lg:block">
    <h3 class="text-white text-3xl font-semibold">Networks</h3>

        <div class="w-full lg:w-auto flex flex-wrap justify-center lg:justify-start gap-3 mt-6 mb-8">
            <div class="badge">Sockets</div>
            <div class="badge">Servers</div>
            <div class="badge">C</div>
            <div class="badge">Python</div>
        </div>

        <p>Implemented a TCP connection between server and client sockets in both python and C.
        <span id="more"> Accept and parse the HTTP request, get the requested file from the 
        server’s file system, create an HTTP response message consisting of the requested 
        file preceded by header lines, and then send the response directly to the client. 
        If the requested file is not present in the server, the server should send an HTTP “404 Not Found” 
        message back to the client.</span></p>
        <button onclick="myFunction()" id="myBtn">Read more</button>
</div>

jsodc grouping / add cathegorys

I try to document my “large” node.js backend, which has the following file/folder structure:

backend
├── components
│   ├── devices
│   ├── endpoints
│   ├── plugins
│   ├── rooms
│   └── vault
├── helper
│   ├── debounce.js
│   ├── expose.js
│   ├── extend.js
│   ├── infinity.js
│   ├── iterate.js
│   ├── mixins.js
│   ├── observe.js
│   ├── promisify.js
│   ├── propertys.js
│   ├── queue.js
│   ├── request.js
│   ├── sanitize.js
│   └── timeout.js
├── index.js
└── system
    ├── component
    ├── hooks.js
    └── middleware.js

Basically i want to create tree groups: system, helper & components, where i can add.
Is there a way to add custom categorys/groups in the jsdoc with the above headlines? E.g. (Generated jsdoc output edited to illustrate goal):

enter image description here

Is there a built in way with a combination of built in stuff?
(Im pretty new when it comes to work with jsdoc)

How to use reduce function to find the value of field inside an array of Objects?

Here is an object of 3 forms formA, formB, formC in which form A and B are objects and formC is an array of objects which can have multiple objects

"object": {
    "formA": {
        "details": {},
        "isRouteUser": false,
        "province": "ON",
        "prelabel": 10,
        "users": [
            {
                "age": 0
            }
        ]
    },
    "formB": {
        "line11": 0,
        "line12": 0,
        "line150_1": 0
    },
    "formC": [
        {
            "price": 0,
            "details": [
                {
                    "subItemPrice": 0
                }
            ]
        }
    ]
}

I am using the function to find the value of the fields inside the forms


    const getValue = (object, keys) => keys.split('.').reduce((o, k) => (o || {})[k], object);

const key1 = formB.line11
const key 2 = formC[0].price

I am using this function to get the value

const formValue = getValue(object,key1)

case 1: key 1 worked well
case 2: key2 – failed

Is there a way in React to update components on props change? (while developing at least)

I’m developing a React App using different components to layout the page.
While i Work with these components I usually go back and forth changing some of their props in the code.

What I would like is that when I save the file React sees that I changed some props and rerender the component with new props.
Right now I have to update the page every time and it’s really annoying.

EXAMPLE
I have this transform component

function Transform({size, children}) {
          return <div style={`transform: scale(${size});`}>{children}</div>
     }

And I use it in the app like this

<Interface>
    <Transform size={0.25}><Grid layout={'3x4'} /></Transform>
 </Interface>

When I change the size prop on the Transform component (just to test if I want the grid bigger) and save the file, React should reRender the component since one prop has changed and so it will appear differently.
How can I set my workspace like this? Any help is really appreciated thanks!
(even automatically updating the whole page would be great!)