how to use .filter to edit a state in react without mutating

Im not sure if this is even possible as I dont think .filter can be used for something like this. If I have an array like so:

abc: [
    {number: 1, letter: "a"},
    {number: 2, letter: "b"},
    {number: 3, letter: "c"},
    {number: 4, letter: "d"},
]

I want to do something like this

abc.filter(item => {
        if(item.number == 1){
            
            item.letter == "aa"
        }
    })

Basically updating the first element in the object to be {number:1, letter:"aa"}. However this ends up giving me an empty array. I dont think im going about it in the correct way. How could I use filter to make edits to certain elements?

refresh data in dataTable when column is reordered in javaScript

I have a dataTable component in my Vuejs application, that I use to display tables.
It has a ‘data’ prop value that allows it to take the data to show in the table.
here is how I call the component:

<aDataTable :data="sites">
        <template #columns> <!-- showing columns here --> </template >
        <template #rows> <!-- showing rows here --> </template >
<aDataTable>

I would like to be able to refresh the data when one of the column headers is clicked.
I would like the sorting to be done on the server-side, hence why im doing it this way.
This is kind of what I would like to do but not sure how

$('#data-table').on('order.dt', function () { 
       // gets the value of the header of the column and using to sort the data in the table
}

Any idea how one can do this?

How to hide navigation on owl carousel in angular

I am using owl carousal in my angular project. I am displaying few records in the carousal, Navigation icons still appears even though there is only one record, I tried to make navigation = false when checking the length of the dataset. But still it doesn’t work. Please assist on this

HTML

<owl-carousel-o [options]="customOptions" (translated)="getData($event)" #owlElement>
      <ng-container *ngFor="let slide of speakersCopy">
        <ng-container *ngIf="slide && slide.id">
          <ng-template carouselSlide [id]="slide.id.toString()">
            <div class="slider-template-wrapper">
              <div class="image-container" (click)="changeSpeaker(slide)">
                <img *ngIf="slide.photoPath; else noUserPhoto" [src]="slide.photoPath" alt="{{slide.title}} Speaker"
                  aria-hidden="true">
                <ng-template #noUserPhoto>
                  <div class="border-1 border-color-primary no-user-photo" style="margin:0 auto">
                    {{ slide.firstName[0] }}
                    {{ slide.lastName[0] }}
                  </div>
                </ng-template>
              </div>
              <div class="details-wrapper" (click)="changeSpeaker(slide)"
                attr.aria-label="Speaker details loaded for {{slide.firstName}} {{slide.lastName}}" role="alert">
                <p class="name fs-medium mb-0 text-center color-primary"> {{slide.firstName}} {{slide.lastName}}</p>
                <p class="title mb-0 text-center body-text-color" [innerHtml]="slide.title"></p>
                <p class="company mb-0 text-center body-text-color"><strong [innerHtml]="slide.company"></strong>
                </p>
              </div>
            </div>
          </ng-template>
        </ng-container>
      </ng-container>
    </owl-carousel-o>

Component

customOptions: any = {
center: true,
loop: true,
mouseDrag: true,
touchDrag: true,
pullDrag: true,
dots: false,
navSpeed: 700,
nav: true,
navigation: true,
navText: [
  '<i title="Previous" class="fa fa-chevron-left prevSlideBtn" tabindex="0" aria-label="Previous"></i>',
  '<i title="Next" class="fa fa-chevron-right nextSlideBtn" tabindex="0" aria-label="Next"></i>',
],
responsive: {
  0: {
    items: 1,
  },
  767: {
    items: 1,
  },
},
onChange: (obj) => {
  console.log('change', obj);
},

};

ngOnChanges(changes: SimpleChanges): void {
this.isSessoinOpened = false;
if (!isEmpty(this.speakers) && this.speaker) {
  this.speakersCopy = Object.assign([], this.speakers);
  const index = this.speakersCopy.findIndex(
    (i) => i.id === this.speaker.id
  );

  this.speakersCopy = this.speakersCopy
    .slice(index, this.speakersCopy.length)
    .concat(this.speakersCopy.slice(0, index));

if (this.speakersCopy.length < 2){
  this.customOptions.nav = false;
  this.customOptions.navText =null;
  this.customOptions.navigation = false;
}

}

}

ignore object name recebeuuser

I want it to ignore the element with the initial “recebeu” and only send what starts with “user”, how can I do that?…

const array = [
  {
    member: "Joao",
    user: {

      user: "id1",
      user2: "id2",
      user3: "null",
      recebeuuser: "null"
    },
  },
  {
    member: "Pedro",
    user: {
      user: "id1",
      user2: "id2",
      user3: "null",
      recebeuuser: "name"
    },
  },
];
const filteredUsers = (user) => Object.values(user).filter(u => u !== 'null' && typeof u === 'string')
const mentionUser = (user) => `<@${user}>`

const stringify = (m) => `${m.member} - ${filteredUsers(m.user).map(mentionUser).join(', ')}`
const breaker = 'n'
console.log(array.map(stringify).join(breaker)) 
Joao - <@id1>, <@id2>
Pedro - <@id1>, <@id2>, <@name>

Hide and show elements inside Django HTML template

I have 2 buttons orders, and suppliers., and want to show data in a Django web app when the corresponding button is clicked. To do this my home.html looks like

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $(".button_order").click(function(){
          $(".myorders").show();
          $(".myproducts").hide();
          $(".mysupplier").hide();
        });
        $(".button_supplier").click(function(){
            $(".myorders").hide();
            $(".myproducts").hide();
            $(".mysupplier").show();
        });
      });
</script>

syle.css looks like;

.myorders,
.myproducts,
.mysupplier{
font-size: 25px;
display: none;
}

This works perfectly fine until I use normal data like;

<body>
    {%block content %}
    <button class="button_order" >ORDERS</button>
    <button class="button_supplier" >SUPPLIER</button>
    <p class="myorders" >
       This is my order
    </p>
    <p class="mysupplier">
       my supplier is cool
    </p>
</body>

But when I try to use data into <p class="mysupplier"> or <p class="myorders" > from my databases, the hide property no longer works, like below part.

<p class="myorders">
    <!-- {% for element in orders  %}
    {% for key,val in element.items %}
    <ul><li>{{key}}:{{val}}</li></ul>
    {% endfor %}
    <hr class="new1">
    {% endfor %} -->
</p>

I should get Order data from database only when ORDER button is clicked, but my server shows all data from before without even clicking the button. How to maintain hide and show the property of my data.

my views.py looks like

from django.shortcuts import render
client = MongoClient("mongodb://localhost:27017/")
db=client.inventory_data
def home(request):
    collection_data_1 = db['orders']
    orders = list(collection_data_1.find())
    collection_data_2= db['suppliers']
    suppliers = list(collection_data_2.find())
    return render(request,'home.html',{'orders': orders,'suppliers':suppliers})

Getting ‘Uncaught TypeError: $(…).dataTable is not a function’ while using datatable in custom wordpress plugin

I am using a datatable to load items from database in a custom wordpress plugin. But I keep getting this error ‘Uncaught TypeError: $(…).dataTable is not a function’.
This is a common question but all the solutions are same and I have checked them all. The jquery and datatable libraries are loaded in correct order, no mistake in the library links and none of them loaded twice. what can be any other cause for this error??
Below is how the libraries enqueued:

if (!function_exists('current_actives_mng_enqueue'))
{
    function current_actives_mng_enqueue()
    {
        // JS
        wp_register_script('cur_act_mng_jquery', '//code.jquery.com/jquery.min.js');
        wp_register_script('cur_act_mng_bootstrap_js', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js');
        wp_register_script('cur_act_mng_bootstrap_popper_js', '//cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js');
        wp_enqueue_script('cur_act_mng_datatable_js','//cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js',array('jquery'));

        wp_enqueue_script('cur_act_mng_jquery');
        wp_enqueue_script('cur_act_mng_bootstrap_js');
        wp_enqueue_script('cur_act_mng_bootstrap_popper_js');
        wp_enqueue_script('cur_act_mng_datatable_js');

        // CSS
        wp_register_style('cur_act_mng_bootstrap', '//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css');
        wp_register_style('cur_act_mng_datatable_css', '//cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css');
        wp_register_style('cur_act_mng_custom', plugins_url('css/style.css', __FILE__));

        wp_enqueue_style('cur_act_mng_bootstrap');
        wp_enqueue_style('cur_act_mng_datatable_css');
        wp_enqueue_style('cur_act_mng_custom');
    }

    add_action('wp_enqueue_scripts', 'current_actives_mng_enqueue');
}

This is the js code for loading the table:

jQuery(document).ready(function($){
    $('#cur_act_tbl').dataTable({    
        ajax: {
            url: "/wp-admin/admin-ajax.php?action=datatables_endpoint",
            cache:false,
        },
        columns: [
            { data: 'mls' },        
            { data: 'status' },        
        ],
        pageLength: 25
    });

React Auto Scroll to show Fetched Data

Im new to react and im trying to auto scroll to Section where data will be shown after being fetched

scrolling should be after data is fetched

const  App = () => {
const [Data ,setData] = useState([])
const [InputTracking , setInputTracking] = useState('')
const [isLoading,setIsLoading] = useState(false)
const [Clicked , setClicked] = useState(false)
//button onClick function 
const searchTrackingID = async (TrackingID) => {
     console.log(TrackingID)
      setIsLoading(true);
      const response = await axios(API_URL+TrackingID) ;
      const res = await response.data ; 
      setData(res)
      setIsLoading(false);
      setClicked(true);
  }
}
 return (
<Header />
//here a form with a text input and button (after clicking it , wait for Data to change state then AUTO SCROLL TO Data (section)
 <section >
  <div >
    <div >
{
   Data.slice(1).reverse().map((mydata)=>(
   <TrackingInfo  Maindata={mydata}/>
   ))
} 
  </div>
  </div>
</section> 
) 

Sending HTTP request from mobile phone does not work like desktop (sending ‘OPTIONS’ instead of ‘POST)

I have a dashboard that works by sending APIs to other parts of my server. It’s a simple html form that is processed with JavaScript to send a fetch request, and the sent request is handled by my flask backend to do the task with the provided data.

The issue is that when the request is sent on desktop, it works properly. When I am sending it in iPhone using google chrome, the request is not sent properly. Instead of a ‘POST’ request, it is sending an ‘OPTIONS’ request.

Server logs show: “OPTIONS /api/message HTTP/1.1” vs desktop version of “POST /api/message HTTP/1.1”

Here is the JavaScript code:

  const options = {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify( params )  
  };
  fetch('https://myUrl.com/api/message', options )
      .then( response => response.text() )
        .then(response => {
          if (response == 'SUCCESS') {
            console.log(response)
            sessionStorage.setItem("success", "true"); 
            window.location.reload()
          } else {
            sessionStorage.setItem("error", response)
            window.location.reload()
          }
      })

Chrome DevTools “isSystemKey” Debugger Attribute

While looking into chrome.debugger.sendCommand documentation, I came across an attribute, isSystemKey. I wonder whether this could be used to verify whether a key is typed by a human or program (similar to the isTrusted event attribute), but there doesn’t appear to be any documentation on it, in the linked URL or elsewhere. Not a mention of its usage, as far as I can see.

So what does this boolean attribute do?

Some example code to illustrate, given a character c, a tab id tab_id and the debugger currently attached to that same tab:

let options = {
    'key': c,
    'type': 'keyDown',
    'nativeVirtualKeyCode': c.charCodeAt(),
    'windowsVirtualKeyCode': c.charCodeAt(),
    'macVirtualKeyCode': c.charCodeAt(),
    'isSystemKey': true // What does this change, compared to its falsy default?
}
// Pressing key
chrome.debugger.sendCommand({tabId: tab_id}, "Input.dispatchKeyEvent", options, () => {
    // Releasing key
    options.type = 'keyUp';
    chrome.debugger.sendCommand({tabId: tab_id}, "Input.dispatchKeyEvent", options, () => {
        // Detaching debugger
        chrome.debugger.detach({tabId: tab_id});
    });
});

How can Javascript’s regular expressions filter strings with multiple rules at the same time?

I need to process a piece of text into an array of words.

Delimiters between words are newlines, spaces, and various punctuation marks, and &nbsp;.

The code I wrote was able to handle other cases, but not the &nbsp; case.

Notice:I need to handle all cases within the same regex and cannot replace &nbsp; with spaces.


This code doesn’t go wrong, it just runs in chrome and the result is not the expected value.

In the generated word array, "break up test the words" is a value(wrong), I need it to be 5: [break,up,test,the,words](right)


my code:

<!DOCTYPE html><html><head>
<script>
window.onload = function(){
  var text = document.getElementById('text').textContent
  // &nbsp; of below regex doesn't work
  var word_array = text.split(/[ tnr.?,"';:!(){}<>/]|&nbsp;/)
  console.log(text)
  console.log(word_array)
}
</script>
</head><body>
<div id="text">this   is text,break&nbsp;up&nbsp;test&nbsp;the&nbsp;&nbsp;words!ok</div>
</body></html>

Anchor tab is not opening an external link in the same tab. If I replace the external link with my domain. it behave correctly

I am trying to make link to another site open in the same tab. but it doesn’t work

<a target="_self" href="https://www.someotherdomain.com/"></a>

However if I change the link to that of my website, It works fine.

<a target="_self" href="https://www.mywebsite.com/"></a>

Is there a way to force the external link to open in the same tab. like it does with internal links?

How To Get Previous Data-Color Attribute?

The question is:

Write code in YOUR CODE HERE that logs the current and previous values of the data-color attribute on the #cro-headline element each time that the attribute changes. Your log statement should look something like this:
console.log('Current color: ' + currentColor + ' | Previous Color: ' + previousColor);

My answer so far:

var oldFunction = window.changeHeadlineColor;
window.changeHeadlineColor = function(croHeadline) {
  oldFunction(croHeadline);
  var currentElement = document.querySelector('#cro-headline');
  var currentColor = currentElement.dataset.color;
  var previousElement = currentElement.previousElementSibling;
  var previousColor = previousElement.dataset.color;
  console.log('Current color: ' + currentColor + ' | Previous Color: ' + previousColor);
}

I’m just not entirely sure how to log the previous value of the data-color attribute. Any help would be greatly appreciated!

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        [data-color="red"] { color: red; }
        [data-color="blue"] { color: blue; }
        [data-color="green"] { color: green; }
        [data-color="orange"] { color: orange; }
        [data-color="purple"] { color: purple; }
    </style>
    <script>
        window.myHandler = function () {
            console.log('Click!');
        };

        window.getRandomNumber = function (max) {
            return Math.floor(Math.random() * max)
        }

        var colors = ['red', 'blue', 'green', 'orange', 'purple'];
        window.changeHeadlineColor = function (croHeadline) {
            var random = getRandomNumber(5000);
            var randomString = random.toString();
            setTimeout(() => {
                var colorKey = (randomString.length < 4) ? 0 : parseInt(randomString.charAt(0));
                croHeadline.setAttribute('data-color', colors[colorKey]);
                changeHeadlineColor(croHeadline);
            }, random);
        };
    </script>
    <script>
        ////////////////////
        /* YOUR CODE HERE */
        ////////////////////
    </script>
</head>

<body>
    <div id="myDiv">OMG Click me!</div>
    <script>
        document.querySelector('#myDiv').addEventListener('click', myHandler);

        setTimeout(() => {
            myDiv.insertAdjacentHTML('beforebegin', '<h1 id="cro-headline" data-color="red">Cro Metrics</h1>');
            var croHeadline = document.querySelector('#cro-headline');
            changeHeadlineColor(croHeadline);
        }, getRandomNumber(5000));
    </script>
</body>

</html>

Change SVG Circular Progress Bar stroke according to colour in linear gradient

I’m trying to make an SVG circular progress bar change color according to progress/percentage from a linear gradient using CSS and JavaScript (react too).

So far, every solution I find has hard coded color codes or using jQuery which I cannot use.
My code and CSS is following.

  <svg viewBox="0 0 36 36" className="circular-chart">
  <path className="svg-back"
    fill='none'
    stroke={props.theme.colors.Neutral.Gray1}
    strokeWidth={3}
    d="M18 2.0845
  a 15.9155 15.9155 0 0 1 0 31.831
  a 15.9155 15.9155 0 0 1 0 -31.831"
  />
  <path className="circle"
    stroke-dasharray={`${props.percentage} 100`}
    d="M18 2.0845
  a 15.9155 15.9155 0 0 1 0 31.831
  a 15.9155 15.9155 0 0 1 0 -31.831"
  />

  <text
    x={18}
    y={21}
    className="svg-circle-text">
    {props.percentage}%
  </text>
</svg>

CSS:

    .svg-circle-text {
      font-size: 0.5rem;
      text-anchor: middle;
      fill: ${theme.colors.Primary.Black}
      font-weight: bold;
  }

  .circular-chart {
    display: block;
    margin: 10px auto;
    max-width: 80%;
    max-height: 250px;
  }
  
  .circle {
    stroke: #99DA98;
    fill: none;
    stroke-width: 3;
    stroke-linecap: round;
    animation: progress 1s ease-out forwards;
  }
  
  @keyframes progress {
    0% {
      stroke-dasharray: 0 100;
    }
  }

In another component, I have the following background which serves as kind of a key to this circular progress bar:

 background: linear-gradient(
      90deg,
      #99da98 0%,
      #f8b66a 51.56%,
      #cf6767 100%
    );

So if the percentage is, say, 60%, it should show the value of the gradient at 60%. A little help would be appreciated. Thanks.