How to save an object in redux?

I build an app in React with Redux and I try to send to my state an object and I try to save it in ‘thisUser’ but I don’t know how to write that ‘return’ because mine doesn’t work.

My Redux state:

const initialState = {
    thisUser: {}
}

export function usersReducer(state = initialState, action) {
    switch (action.type) {
        case 'users/addUser':
            return { ...state, thisUser: { ...state.thisUser, ...action.payload} }  //the problem
        default:
            return state
    }
}

Dispatch method:

dispatch({ type: "users/addUser", payload: new_user });

Can you tell me how to write that return, please?

Map function not working for properly while querying from Mongodb

I have a few mongodb documents like this

{'_id':'1',
 'year':2020,
 'season':'Summer',
 'status':'Over'},

{'_id':'2',
 'year':2020,
 'season':'Winter',
 'status':'Pending'},

{'_id':'3',
 'year':2020,
 'season':'Rainy',
 'status':'Pending'},

{'_id':'4',
 'year':2021,
 'season':'Summer',
 'status':'Pending'}
........
...
.

If I give an input of array of years [2020,2021], then my expected output should be

[{year:2020,sesason:['Winter','Rainy']},{year:2021,sesason:['Summer','Winter','Rainy']}]

where season array should only contain values whose status is ‘Pending’.
I tried this code,but not getting the expected output

var arr =[];
var yearsArray = [2020,2021]
var seasonArray = ['Summer','Rainy','Winter']
var pendingSeasons = [];
return await Promise.all(
   yearsArray.map(async(year) =>{
      return await Promise.all(
         seasonArray.map(async(tP) =>{
             await db.collection('CC')
              .find({'year':year,'season':tP})
              .toArray()
              .then((data) =>{
                    if(data.status != 'Over'){
                        pendingSeasons.push(tP)
                    }
                })
            })
        ).then(arr.push({"year":year,"season":pendingSeasons}))
        })
        ).then(() =>{
            return arr
        })

Sync an html5 video with an highchart.js line chart

I have a one minute long video of a train moving and some data series about his position, onboard accelerometer etc.

My goal is to make line charts (with Highcharts.js) of those measurements that are dynamically drawn with the video at a rate of 20points per second.
I was wondering if there’s a way to attach an event to the video progress bar and redraw the chart every x milliseconds and/or every time that the user play/stop the video

Change colour based on data set (d3)

I have two dataset d1 and d2 as follows:

const d1 = [
 {group: "H", value: 6},
 {group: "I", value: 2},
 {group: "M", value: 3}
];
const d2 = [
 {group: "H", value: 1},
 {group: "I", value: 12},
 {group: "M", value: 2}
];

and a function called makethisgraph where the “data” that is sent is either d1 and d2 based on a button I click. In this function, based on the data I select, the bars change to match the values. I want to make it in such a manner that if I select d1 then the color of the bar changes to red and if d2 then it turns to green

function makethisgraph(data) {
 var u = svg.selectAll("rect")
 .data(data)
 u .enter()
 .append("rect")
 .merge(u)
 .transition()
 .duration(1000)
 .attr("x", function(d) { return x(d.group); })
 .attr("y", function(d) { return y(d.value); })
 .attr("width", x.bandwidth())
 .attr("height", function(d) { return height - y(d.value); })
 .attr("fill", function(d, i) {
    //  if ( data = d1)
    //  {
    //      return "red"
    //  }
    //  else
    //  {
    //      return "green"
    //  }
  return "blue"
});

I tried writing if the data I got is d1 then it will be red but it doesn’t work. Is there any other way to solve this?

print receipt using a pos printer in Chrome [closed]

I have a receipt to print by using an Epson 220 printer. The print look pretty much decent when i use a laser printer, but can’t get a clear print on POS printer. I found that Chrome prints documents as an image and that’s the reason for this. How can i achieve this without using Firefox?

Api call in Next JS

Reading the documentation of NextJs i noticed that this framework has this feature:

function Page({ data }) {
  // Render data...
}

// This gets called on every request
export async function getServerSideProps() {
  // Fetch data from external API
  const res = await fetch(`https://.../data`)
  const data = await res.json()

  // Pass data to the page via props
  return { props: { data } }
}

export default Page

So, this getServerSideProps allows to make http requests using SSR approach.
Question: It is correct if i will say that SSR requests are available only for get requests? I say this because only this function allows us to make SSR requests and i can not imagine how to make a POST request using NEXT JS, like the user submit a form and want to send on back-end, so how in this case to use getServerSideProps? Also, it is correct that NEXTJs allows us to make SSR requests only within pages but not components?

Angular loading icon from material Registery is not preloaded

I have registered some svg’s in app.component

public static MAT_ICONS_TO_REGISTOR: { name: string, url: string }[] = [
    {name: 'galaxy-icon', url: '../assets/imgs/galaxy.svg'},
    {name: 'sources-icon', url: '../assets/imgs/camera_in.svg'}
 ];  



AppComponent.MAT_ICONS_TO_REGISTOR.forEach(icon => {
      this.matIconRegistry.addSvgIcon(icon.name,
        this.domSanitizer.bypassSecurityTrustResourceUrl(icon.url));
    });

But its not loaded on component init, ex:

  <div *ngIf="!isApproval">
            <mat-icon  svgIcon="broom"
                      (click)="onResubmitAction()">
            </mat-icon>
</div> 

In this case when the condition becomes true a get request will be sent to get the icon from assets (‘http://localhost:4200/assets/imgs/broom.svg’) but it should load it on component init.

code debugger:the Array.split() function split ‘foo-the’ to [‘the’] but not [‘foo’,’the’]

let see line 81,the value of words is ‘foo-the’

enter image description here

and step next see line 69,split ‘foot-the’ with ‘-‘ ,it turns out ‘the’

enter image description here

the problem comes from when solving the leetcode algorithm question
description :
You are given a string s and an array of strings words of the same length. Return all starting indices of substring(s) in s that is a concatenation of each word in words exactly once, in any order, and without any intervening characters.

You can return the answer in any order.

full code as follows:

 var s = "barfoofoobarthefoobarman"

var words = ["bar", "foo", "the"]
var arr = []
var position = []

function dfs(index, temp, words) {

    var wordsP = words.split('-')

    if (wordsP.length) {
       temp = temp.concat(wordsP[index])
        wordsP.splice(index, 1)
    }
    if (!wordsP.length) {
        arr.push(temp)
        return;

    }

    for (var i = 0; i < words.length; i++) {
        dfs(i, temp, wordsP.join('-'))
    }
}

for (k = 0; k < words.length; k++) {
    dfs(k, '', words.join('-'))
}
//
arr.forEach((item) => {
    if (s.indexOf(item) != -1) {
        position.push(s.indexOf(item))
    }

})

Url from webview in react native

I want to know the URL everytime it changes in webview. I searched online a lot. And according to that, I have done these changes. But it is still not working.

What am I doing wrong here. Why its not working.

It only logs for the first time. or it works when I click some other button on the screen.
What am I missing?

import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';

const initialUrl = 'https://www.youtube.com/';
let url = '';

class App extends Component {

  state = {
    url: initialUrl,
  };

  onNavigationStateChange = navState => {
    console.log("navstate=== ",navState)
    if (url!==navState.url) { 
      url = navState.url;
      alert(url);
      this.setState({
        url: url
      })
    }
  };

  render() {
    const { url } = this.state;
    const injectedJs = `
      var linkElements = document.getElementsByTagName("a");
        
      linkElements[0].addEventListener("click", function() {
        window.postMessage("addAccountSuccess?token=abc1234");
      });
      
      linkElements[1].addEventListener("click", function() {
        window.postMessage("addAccountError");
    `;
    return (
      <View style={{paddingTop: 24, flex: 1}}>
        <Text style={{backgroundColor: 'black', color: 'white'}}>{ url }</Text>
        <WebView
          style={{ flex: 1}}
          source={{
            uri: initialUrl,
          }}
          injectedJavaScript={injectedJs}
          startInLoadingState
          scalesPageToFit
          javaScriptEnabledAndroid={true}
          javaScriptEnabled={true}
          domStorageEnabled
          startInLoadingState={false}
          onNavigationStateChange={this.onNavigationStateChange.bind(this)}
          onMessage={event => {
            alert('MESSAGE >>>>' + event.nativeEvent.data);
          }}
          onLoadStart={() => {
            console.log("LOAD START ");
          }}
          onLoadEnd={() => {
            console.log('LOAD END');
          }}
          onError={err => {
            console.log('ERROR ');
            console.log(err);
          }}
        />
      </View>
    );
  }
}

export default App;

How do I fetch login data from PHP script to my MainActivity?

This is my PHP script:

<?php
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

    $con=mysqli_connect($server,$username,$pass);
    $connection=mysqli_select_db($con,$database);

    $sql="SELECT * FROM `electric_database_users` WHERE 
    `User name/no`='".$_POST["username"]."' AND `Password`='".$_POST["password"]."'";
    $result = $con->query($sql);
    if ($result->num_rows > 0)
        echo "login found";
    else
        echo "Invalid login";

    $con->close();
 ?>

In javascript, I could fetch the data using $ajax call:

$.ajax({
    url: '/login_screen/backend.php',
    type: 'POST',
    data: { "input": "sign in",
          "username":  username,
          "password": password},
    success: function(response) {
        if(response=="login found")
            //Login successful
    },
    complete: function() {}
  });

Now I want to implement the same logic from my android app i.e., I want to fetch the login details from my backend.php. Is there something equivalent to $ajax call in android?

  empno=(EditText) findViewById(R.id.empno);
  pass=(EditText) findViewById(R.id.pass);
  login=(Button) findViewById(R.id.login);

  login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

             //how do I proceed here?
        }
  });       

Jquery GET Function Returning Previous Result

I’m running into a rather strange problem. When the webpage loads, I automatically run a jQuery GET request on an internal PHP script that essentially prints a JSON output from a backend application.

jQuery

$.get(urls.validateSession, function(data){

     console.log(data); //For debugging
     var response = JSON.parse(data);

     //Do more things with returned data

});

PHP

<?php

    include 'include/backend.php';
    
    //Send POST request to backend application
    $response = sendPostRequest($urls->session->validate, json_encode($defaultRequest));

    /* sendPostRequest Function Definition */
    /*
    function sendPostRequest($url, $data){
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($curl);
        curl_close($curl);
        
        return $response;
    }
    */

    echo $response;

?>

This works as expected in my local xampp server, and will print a JSON output to the console similar to the following:

{
   "status":"SUCCESS",
   "time":"02-21-2022 02:14:03",
   etc...
}

Though when I run this same code on a remote apache server, instead of jQuery running the GET request each time the webpage loads and writing the received data to the console, jQuery will not run the GET request again and write the data received from the previous GET request to the console. Almost like the previous result of the GET request was cached and used again for the subsequent request.

I know jQuery is not running the GET request each time the page is reloaded because the “time” field in the JSON output always stays the same. As well, I do not see subsequent requests reaching the backend application. So jQuery is not bothering to make a new GET request to fetch new data, and is just using the previous result.

Though when I force refresh the webpage (Shift + F5), this seems to force jQuery to run the GET request again, and the new expected JSON output with an updated timestamp is written to the console.

Any ideas about what could be happening here?

Prevent Defaults prevents whole document from been clicked

On my web site i listen for clicks on a href and swap my html using ajax using the code below

$(document).on('click','a', function (e){
e.preventDefault();
$.ajax({})
.........
})

but the prevent default prevents me from clicking any other thing on the page until the ajax complete.
I am listening to the click on tags while referencing the document as root because if the ajax swaps the content, using just and listening to events on that won’t be called because of the changes done by swapping the dom.
What can be done to fix this behavior. Thanks