Can’t access data from miragejs and redux

It’s the first time i use miragejs and maybe i did something wrong,but in console i get my data which i need to be in a sort of time line dynamically. I created the redux slice,async thunk,and when i try to access the state i get get this erro in console TypeError: Cannot read properties of undefined (reading ‘educationList’) And the app doesnt work. If i put the data as a prop from component,it works,but with redux thunk it doesnt.. Could you tell me what i’m doing wrong please?
Here is my mirage server:

import { createServer,Model } from "miragejs"

export const makeServer =({ environment = 'test' } = {})  => {
    let server = createServer({
      environment,
        models: {
          educations: Model,
         skills:Model
        },

        seeds(server) {
            server.create("education", { date: 2001, title: "Title 0", text: "Elit voluptate ad nostrud laboris. Elit incididunt mollit enim enim id id laboris dolore et et mollit. Mollit adipisicing ullamco exercitation ullamco proident aute enim nisi. Dolore eu fugiat consectetur nulla sunt Lorem ex ad. Anim eiusmod do tempor fugiat minim do aliqua amet ex dolore velit.rn" });
            server.create("education", { date: 2000, title: "Title 1", text: "Et irure culpa ad proident labore excepteur elit dolore. Quis commodo elit culpa eiusmod dolor proident non commodo excepteur aute duis duis eu fugiat. Eu duis occaecat nulla eiusmod non esse cillum est aute elit amet cillum commodo.rn" });
            server.create("education", { date: 2012, title: "Title 2", text: "Labore esse tempor nisi non mollit enim elit ullamco veniam elit duis nostrud. Enim pariatur ullamco dolor eu sunt ad velit aute eiusmod aliquip voluptate. Velit magna labore eiusmod eiusmod labore amet eiusmod. In duis eiusmod commodo duis. Exercitation Lorem sint do aliquip veniam duis elit quis culpa irure quis nulla. Reprehenderit fugiat amet sint commodo ex.rn" });
          },
    
        routes() {
            //this.namespace = 'api/educations';
            this.get('api/educations', (schema, request) => {
              return schema.educations.all();
            });

            // this.namespace = 'api/skills';
            this.get('api/skills', (schema, request) => {
              return schema.skills.all();
            });
    

          this.post('api/skills', (schema, request) => {
            let attrs = JSON.parse(request.requestBody);
            return schema.skills.create(attrs);
          });
        },
      })
      return server;
    }  

redux store:

import { createStore, combineReducers, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension'
import { persistStore, persistReducer } from 'redux-persist'
import { toggleButtonReducer } from './reducers/toggleButtonReducer'
import storage from 'redux-persist/lib/storage'
import thunk from 'redux-thunk'
import { postSlice } from '../features/education/educationSlice';

const rootReducer = combineReducers({
    visibilityState: toggleButtonReducer,
    educationState: postSlice,
})

const persistConfig = {
    key: 'root',
    storage,
}

const persistedReducer = persistReducer(persistConfig, rootReducer)

export const store = createStore(persistedReducer, composeWithDevTools(applyMiddleware(thunk)))

export const persistor = persistStore(store)

educationSlice :

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import axios from 'axios'

const initialState = {
    educationList: []
}


export const getEducation = createAsyncThunk(
    'educations/getEducations',
    async (_, { rejectWithValue, dispatch }) => {
        const res = await axios.get('api/educations')
        dispatch(setEducations(res.data))
        console.log(res.data)
    })


export const postSlice = createSlice({
    name: 'educations',
    initialState,
    reducers: {
        setEducations: (state, action) => {
            state.educationList = action.payload
        },
    },
    extraReducers:{
        [getEducation.fulfilled]:()=> console.log('fullfiled'),
        [getEducation.pending]:()=>console.log('fullfiled'),
        [getEducation.rejected]:() =>console.log('rejected'),
    },
})

export const {setEducations} = postSlice.actions
export default postSlice.reducer;

And the component were i need data:

import '../../assets/styles/css/TimeLine/base.css'
import { useDispatch } from 'react-redux'
import { getEducation } from '../../features/education/educationSlice'
import { store } from '../../store'
import { useSelector } from 'react-redux'

const TimeLine = () => {

const dispatch = useDispatch()
dispatch(getEducation())
const data = useSelector(state => state.educationState.educationList)

    return (
        <>
            <section id='timeLine'>
                <h1 className='educationSection'>Education</h1>
                <div id="timeline" className='timelineWrapper'>
                    {data.map((info) => (
                        <div className="timeline-item" key={info.id}>
                            <span className="timeline-icon">
                                <span>&nbsp;&nbsp;</span>
                                <span className="year">{info.date}</span>
                            </span>
                            <div className='timeline-content'>
                                <h2>{info.title}</h2>
                                <p>{info.text}</p>
                            </div>
                        </div>
                    ))}
                </div>
            </section>
        </>
    )
}

export default TimeLine  

This is what i have in console:
enter image description here

but can’t acces the data.. please help,i’m stuck.. thanks in advance!

If JavaScript is disabled in developer tools, I want to run noscript on the screen immediately

If JavaScript is disabled in developer tools, I want to run noscript on the screen immediately.

<noscript> this page is wrong </noscript>

If you disable JavaScript in developer tools and go to another page, noscript is applied.
I want the noscript content to be applied immediately when JavaScript is disabled, but is there any way?

Or is there anything else I can do to disable javascript mode?

Jest mock jsonwebtoken sign : NestJs

I’m trying to write unit test for my authenticateUser method.In side that method i’m generating private key signed jwt token and return to the user.But my signToken method seem not mocked properly.it return Promise {}.

userService.ts

  async authenticateUser(authDto: AuthDTO): Promise<AuthResponse> {
  
  const formatedMobile = this.commonHelper.formatMobile(
        decodedIdToken.Mobile,
      );
      
    const userData = await this.userRepository.findOne({
        msisdn: formatedMobile,
      });
  if (!userData) {
        //save user info
        const user = new UserEntity();
        user.firstName = decodedIdToken['first_name'];
        user.lastName = decodedIdToken['last_name'];
        user.msisdn = formatedMobile;
        await this.userRepository.save(user);
      }
    const jwtPayload={createdTime: moment(),msisdn: formatedMobile}
    
    const jwtToken = this.commonHelper.signToken(jwtPayload);
    
     return new AuthResponse(
        HttpStatus.OK,
        STRING.SUCCESS,
        `${STRING.USER} ${STRING.AUTHENTICATE} ${STRING.SUCCESS}`,
        {jwtToken},
      );
  }

userService.specs.ts

  it('authenticateUser should return success response (User Exist)', async () => {
    const mockJWTToken = {
    jwtToken:"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2NDgyNjIzMDYsImRhdGEiOnsiY3JlY"
    }
    const mockAuthBody = { authCode: 'c79da50f-4eb1',platform:'MOBILE' };
    const mockSuccessResponse = new AuthResponse(
      HttpStatus.OK,
      STRING.SUCCESS,
      `${STRING.USER} ${STRING.AUTHENTICATE} ${STRING.SUCCESS}`,
      mockJWTToken,
    );

    jest.spyOn(commonHelper, 'formatMobile');
    jest.spyOn(userRepository, 'findOne').mockResolvedValueOnce(userEntity);
    jest.spyOn(commonHelper, 'signToken').mockResolvedValueOnce(mockJWTToken);

    expect(await userService.authenticateUser(mockAuthBody)).toEqual(
      mockSuccessResponse,
    );
  });

enter image description here

GraphQL error adding chinese charactor in Gatsbyjs

I’m new Gatsbyjs.
I use this template

https://www.gatsbyjs.com/starters/netlify-templates/gatsby-starter-netlify-cms

I have question about changing gatsby-node.js file and srcpagesindex.md file.

Actually I asked before and Mr.Ferran Buireu helped me. so I could success to change some text and photos.

“gatsby develop” can’t run After adjusting image data

Currently I’m adjusting around LINE 16 of srcpagesindex.md file
text: > I would like to change this sentence.

intro:
  blurbs:
    - image: /img/coffee.png
      text: >
        日本語を入力したい I would like to change this sentence.
        

I use Japanese sentence and Chinese characters. When I save the file then run gatsby develop Many error show up such as below.

There was an error in your GraphQL query:
Field “image” must not have a selection since type “String” has no
subfields.

but I can see http://localhost:8000/ but with this error message.
And sentence are not changing.
enter image description here

I know there are problem but I tried to deploy at Netlify the sentence are changed.

I searched solution and tried that gatsby-node.js file non changing save(type space save and delete it and save again).

And restart gatsby develop but it doesn’t work.

Could someone teach me solution please?

Someone at the company I work for clicked on a phishing email attachment. This opens up a link in the browser [closed]

Someone at the company I work for clicked on a phishing email attachment. We here in the IT department are extremely concerned about what this may have done to our systems. I will be including source code from the website here in hopes someone may be able to provide a good understanding of what it might have done. Here’s the source code
https://drive.google.com/file/d/1eXcVp_pw9ZFC-BcK3yrnWQ0iRDpUqPhv/view

Cannot Read properties of undefined React. Log only works on object

I’m currently trying to create a weather website using weatherapi, but I’m running into a problem. If I log the object of location there’s no error, but if I try to log anything deeper than that object, like the name of the city it cannot read properties of undefined. If I comment out the log when it’s using the name of the city, then uncomment it again and don’t reload the page, then it will log the name of the city without error.

import React from 'react';
import './index.css';
import Navbar from "./components/Navbar"
import {useState} from "react"
import Weather from './components/Weather';


function App() {
  const [inputData, setInputData] = useState({})
  const [currentWeather, setCurrentWeather] = useState([])
  const [loc, setLoc] = useState({loc:"Arlington"})
  let apiKey = "7ab98e97faa64c4d8b4104902222202"
  // console.log("Location: "+ loc.loc)

  React.useEffect(() =>{///Finds weather data of certain location
    console.log(loc.loc)
    fetch(`https://api.weatherapi.com/v1/current.json?key=${apiKey}&q=${loc.loc}&aqi=no`)
    .then(res => {
      if(res.ok){
        return res.json()
      }
    })

    .then(data => {
      if(data !=null){//Only change currentWeather when there is data for it
        setCurrentWeather(data)
      }else{
        alert(`${loc.loc} was not found`)
      }
    })
  }, [loc])

  React.useEffect(() =>{///Finds locations with search bar
    fetch(`https://api.weatherapi.com/v1/search.json?key=${apiKey}&q=${loc.loc}&aqi=no`)
    .then(res => res.json())
    .then(data => {
      if(data.loc == null){
      }else{
        setLoc(data)
      }
    })
  }, [])

  
  //console.log(currentWeather.location.name)
  

  return (
    <div className="App">
      <Navbar inputData={inputData} setLoc={setLoc} setInputData={setInputData}/>
      <Weather currentWeather={currentWeather}/>
    </div>
  );
}

export default App;


Any way to execute javascript to modify the dom of website using python

Any way to execute javascript to modify the dom of website(that you do manually by using inspect element) and fill in forms etc using python. Only one I saw was selenium webdriver execute script but I don’t want to use it because it is very slow. Any alternatives I would prefer directly in browser opposed to using apps like chromedriver as a medium.

 Windows 7 Python 3.8.8

Generating all possible combinations of multiple arrays based on percentages

I have an array with this layout:

const arrayOfSections = [{chance: 100, items: [1,2,3,4]}, {chance: 49, items: [7,9]}, {chance: 100, items: [0,5]}];

And I am trying to find the best way in just javascript no libraries to basically find all possible combinations of the items value in each array inside arrayOfSections, while also taking into consideration the chance percentage that is in the chance key for that specific array. So for example, if there is a 49% chance for the array with the items value [7,9], it would only generate the possible combinations with only 49% of the combinations having the items inside this array.

I am currently using this function here:

    const allPossibleCases = (arraysToCombine) => {
      console.log(arraysToCombine);
      const divisors = [];

      let permsCount = 1;

      for (let i = arraysToCombine.length - 1; i >= 0; i--) {
        divisors[i] = divisors[i + 1]
          ? divisors[i + 1] * arraysToCombine[i + 1].items.length
          : 1;

        permsCount *= arraysToCombine[i].length || 1;
      }

      let totalOutputs = permsCount;

      const getCombination = (n, arrays, divisors) =>
        arrays.reduce((acc, arr, i) => {
          acc.push(arr[Math.floor(n / divisors[i]) % arr.length]);

          return acc;
        }, []);

      const combinations = [];

      for (let i = 0; i < permsCount; i++) {
        combinations.push(getCombination(i, arraysToCombine, divisors));
      }

      return combinations;
    };

To basically find all the possible combinations based on just

const arraysToCombine = [[1,2,3,4], [7,9], [0,5]]

and its working fine but im having a really hard time figuring out how I could do this while also taking into consideration the chance percentages.

Hopefully this isnt too sloppy of a post and I appreciate any help lol.

Is it possible to verify nodemon.json is being read correctly?

I’m trying to use a simple regular expression as follows:

{
  "verbose": false,  
  "ignore": [
    ".git",
    "bundle.*"
  ]
}

However, it appears the nodemon restarts when bundle.js is updated.

I have seen the form *.js where the filename is a catchall, but I wanted the extension to be a catch all as follows bundle.*.

I would like to use nodemon.json to configure my nodemon. I found this SO Q/A but it did not help.

Problem with Request URL in production in React

I am working on the React App project, In env file – I have declared

REACT_APP_URL = 'http://localhost:8080/'

and using axios to make HTTP request

and here is my code

export const ADMIN_URL = process.env.REACT_APP_URL;
export const api = axios.create({
  baseURL: ADMIN_URL,
  headers: {
    'Content-Type': 'application/json',
  },
});

But when I deployed I could see frontend url and backend url in the request url

example : "http://localhost:3000/login'http://localhost:8080/'/logged

How to show data in a select/option based on input picker plugin choice using jQuery, ajax and PHP?

I need to get data from database and display it in a select/option based on input value of a chosen choice of an input picker plugin. I have this code in invoice.php:

  <div class="form-group">
     <input type="text" class="form-control form-control-sm" id="items" name="items" value="">
  </div>
  <div class="form-group">
       <select class="form-select form-select-sm" id="uom" name="uom">
             </select>
      </div>

 <script>
 var myData = JSON.parse(
 $.ajax({
 method: "GET",
 url: "parsers/items_select.php",
 async: false
 }).responseText);

 $(document).ready(function () {
  $('input#items').inputpicker({
   data: myData,
   fields:['itemNo','title'],
   fieldText:'itemNo',
   fieldValue:'id',
   headShow: true,
   filterOpen: true,
   autoOpen: true
   });
   });
</script>

and this is items_select.php:

<?php
require_once '../init.php';
$data = [];
$q = ((isset($_GET['q']) && $_GET['q'] != '')?sanitize($_GET['q']):'');
$item_select = $db->query("SELECT id, itemNo, title FROM products");
while($item = mysqli_fetch_assoc($item_select)){
$data[] = $item;
}
echo json_encode($data);
?>

The input picker plugin works 100% fine.
Now I have did it perfectly if I use a regular select/option rather than input picker. Here is my code in invoice.php:

<?php
$itemQuery = $db->query("SELECT * FROM products ORDER BY title DESC");
?>
            <div class="form-group">
              <select class="form-select form-select-sm" id="items" name="items">
                <option value=""<?=(($items == '')?' selected':'');?>></option>
                <?php while($item = mysqli_fetch_assoc($itemQuery)): ?>
                  <option value="<?=$item['id'];?>"<?=(($items == $item['id'])?' selected':'');?>><?=$item['uom'];?></option>
                <?php endwhile; ?>
              </select>                    
            </div>

<script>
 function get_child_options(selected){
   if(typeof selected === 'undefined'){
     var selected = '';
   }

   var itemsID = jQuery('#items').val();
   jQuery.ajax({
     url: 'parsers/uom_select.php',
     type: 'POST',
     data: {itemsID : itemsID, selected: selected},
     success: function(data){
       jQuery('#uom').html(data);
     },
     error: function(){alert("Something went wrong with the child options.")},
   });
 }
 jQuery('select[name="items"]').change(function(){
   get_child_options();
 });

 jQuery('document').ready(function(){
   get_child_options('<?=$uom;?>');
 });
 </script>

and in uom_select.php:

<?php
require_once '../init.php';
$itemsID = (int)$_POST['itemsID'];
$selected = sanitize($_POST['selected']);
$item_childQuery = $db->prepare("SELECT * FROM products WHERE id = ? ORDER BY uom");
$item_childQuery->bind_param('i', $itemsID);
$item_childQuery->execute();
$result = $item_childQuery->get_result();
ob_start(); ?>
   <option value=""></option>
   <?php while($item_child = mysqli_fetch_assoc($result)): ?>
     <option value="<?=$item_child['id'];?>"<?=(($selected == $item_child['id'])?' selected':'');?>><?=$item_child['uom'];?></option>
   <?php endwhile; ?>
 <?php echo ob_get_clean();?>

But the above code will not work on input picker plugin, since it is not a select/option element and it displays data in divs and table. What is the solution?

Function in useEffect continues to fire after component unmounts [duplicate]

I’m learning React and having trouble with component lifecycle, or some kind of memory leak. In the code below I’ve using [this codepen][1] in React, and it works, until my Preloader unmounts, and I continually get error below.

Is this a place for a cleanup function? How do I stop animate() from firing after the Preloader has been removed from the dom?

Error

"Uncaught TypeError: text2.current is null
setMorph Preloader.jsx:47
doMorph Preloader.jsx:42
animate Preloader.jsx:83"

In Parent Component

  const { initialLoad, setInitialLoad } = useGlobalState();

    useEffect(() => {
        if (initialLoad) {
          setTimeout(() => {
          setInitialLoad(false);
        }, 4600);
        }
      }, [initialLoad]);
    
    return (
        <div className='browser-wrapper'>
            {initialLoad &&
            <Preloader initialLoad={initialLoad} />
            }
           ...
    )

Preloader Component

const Preloader = ({ initialLoad }) => {
    const text1 = useRef(null)
    const text2 = useRef(null)

    // Insert Text String and Morph tuning adjusments
    const morphTime = .68;
    const cooldownTime = 0.12;
    let textIndex = texts.length - 1;
    let time = new Date();
    let morph = 0;
    let cooldown = cooldownTime;
    text1.current = texts[textIndex % texts.length];
    text2.current = texts[(textIndex + 1) % texts.length];

    function doMorph() {
        morph -= cooldown;
        cooldown = 0;

        let fraction = morph / morphTime;

        if (fraction > 1) {
            cooldown = cooldownTime;
            fraction = 1;
        }
        setMorph(fraction);
    }

    // A lot of the magic happens here, this is what applies the blur filter to the text.
    function setMorph(fraction) {
        text2.current.style.filter = `blur(${Math.min(8 / fraction - 8, 100)}px)`;
        text2.current.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`;

        fraction = 1 - fraction;
        text1.current.style.filter = `blur(${Math.min(8 / fraction - 8, 100)}px)`;
        text1.current.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`;

        text1.current.textContent = texts[textIndex % texts.length];
        text2.current.textContent = texts[(textIndex + 1) % texts.length];
    }

    function doCooldown() {
        morph = 0;

        text2.current.style.filter = "";
        text2.current.style.opacity = "100%";

        text1.current.style.filter = "";
        text1.current.style.opacity = "0%";
    }

    // Animation loop, which is called every frame.
    function animate() {
        requestAnimationFrame(animate);
        let newTime = new Date();
        let shouldIncrementIndex = cooldown > 0;
        let dt = (newTime - time) / 1000;
        time = newTime;

        cooldown -= dt;

        if (cooldown <= 0) {
            if (shouldIncrementIndex) {
                textIndex++;
            }

            doMorph();
        } else {
            doCooldown();
        }
    }

    useEffect(() => {
        if (text2.current !== null || undefined) {
        animate();
        } else {
            console.log('current text.2 is ' + text2.current)
        }
    }, [text2.current])
    

    return ( --- JSX follows
    ```


  [1]: https://codepen.io/Valgo/pen/PowZaNY?ref=devawesome.io

Why is the Kendo UI (AngularJS) affected by an NGX update?

I work on an enterprise application that has a mix of AngularJS (v1) and NGX (v2+) pages. We employ Kendo UI to construct Grids for list pages in the app.

Recently, we updated the the NGX portion of our application to Angular 12 via these update steps. After doing so however, the “items per page” text that usually appears at the bottom of the Kendo Grid next to the page size drop down disappeared from grids that are on AngularJS pages.

I’ve tried reverting the i18n migration step in the Angular upgrade guide which changes message IDs (“items per page” is one of the messages in messages.xlf) but this didn’t help.

I also tried modifying the $scope‘s gridOptions that set the messages on the grid based on these docs i.e.

pageable: {
   .
   .
   .
   messages: {
      itemsPerPage: "items per page"
   }
}

but this also didn’t work.

What’s interesting is that if I modify the display or empty properties in messages, I do actually end up seeing a change. It’s itemsPerPage (among other properties) whose updates can’t be seen on the front-end. This might be a symptom of the same issue.

Anyone have ideas as to why this might be happening? Are there any incompatibility issues with certain versions of @progress/kendo-angular-<package_name> with version 12 of Angular?