How to make a webpage different based on whether or not someone has visited other parts of the site?

I’m rather new to html/css and almost know nothing too big on javascript so I’m not sure where to start on this. (And forgive me if I have improper use of terms!)
I basically am working on a piece of hypertext fiction that is told entirely through html/css and the user will be directed to read through it based on the locations in a town. There is a webpage called places.html which has hyperlinks to:

  • sheriff.html
  • saloon.html
  • stables.html
  • clocktower.html
  • bank.html
  • store.html

However, there is one more webpage I want to add, but I only want it to appear after the user has visited at least three of those webpages listed above. The new addition that would be able to be seen would be graveyard.html, but again, this is only after the user has gone through at least three of the other webpages.
I tried to find an answer to this and it seems as if cookies may be the solution? However, I only found one that changes what the index/first page appears to the user, so I don’t understand it and searching on google doesn’t seem to help me figure out a solution.
Hopefully this explanation is enough and I would appreciate any help I can get!

How to fix “Cannot read properties of null (reading ‘addEventListener’)”? Already checked “duplicated” questions [closed]

I have this js code, where i try to make an item appear and disappear when i go on the top of it with my mouse, but for some reason this ain’t working and it keeps giving me back this error in the console: Cannot read properties of null (reading 'addEventListener').

I don’t know if i can use element.onmouseover = function () {... too, but i’d like it to work first of all!

I was expecting it to make appear and disappear the item ongoing_p.
I have my script LINKED to the bottom of the body, INSIDE the body, and a onload: MainJs () on the body tag.

I have already checked this: Why does jQuery or a DOM method such as getElementById not find the element?

and this: How to fix “Cannot read properties of null (reading ‘addEventListener’)”?

but i didn’t understand how to fix my code.

function MainJs() {
    var ongoing = document.getElementById("ongoing");
    var ongoing_p = document.getElementById("ongoing-p");

    ongoing.addEventListener("mouseover", function () {
        ongoing_p.style.display = "block";
    });
    ongoing.addEventListener("mouseout", function () {
        ongoing_p.style.display = "none";
    });
}
<header>
        <ul>
            <li>
                <a href="#">home</a>
                <div class="parall"></div>
            </li>
            <li>
                <a href="pages/purecss.html">pure css</a>
                <div class="parall"></div>
            </li>
            <li>
                <a href="pages/nextprojects.html">next projects</a>
                <div class="parall"></div>
            </li>
        </ul>
    </header>

    <section class="main">
        <nav class="lateral">
            <ul>
                <li id="ongoning">
                    <a href="">ongoing projects</a>
                    <div class="underline"></div>
                </li>
                <li id="latest">
                    <a href="">latest release</a>
                    <div class="underline"></div>
                </li>
                <li id="templates">
                    <a href="">my templates</a>
                    <div class="underline"></div>
                </li>
            </ul>
        </nav>

        <span class="preview">
            <p id="ongoing-p" style="display: none;">there isn't any ongoing project at this moment, you can
                retry in a few time!
            </p>
            <p id="latest-p" style="display: none;">nothing released yet, come back soon!</p>
            <p id="templates-p" style="display: none;">templates are being loaded up at this time,
                some more day of patient!
            </p>
        </span>
    </section>

Convert list to array in JavaScript

x = array_to_list([10, 20]);
console.log(JSON.stringify(x));

function list_to_array(list) {
  arr = [];
  for (const property in list) {
    if (property == "value") {
      arr.push(property);
    } else if (property == "rest") {
      for (const property in rest) {
        arr.push(property);
      }
    }
  }
}
console.log(JSON.stringify(list_to_array(x)));

but I get the error Uncaught ReferenceError ReferenceError: rest is not defined how can I iterate in the rest object ? or how would you do this function

this functions transform a list to an array

How do I make a program that can react to/detect changes in my screen? (preferably in python)

I wanted to automate fishing in a game, so that when the pop-up shows up, the program would detect the change in the screen and performs a certain action. Then reseting and waiting for the pop up again.

I need the to detect the changes because the wait time is random and I couldn’t find anything in the game about changing the player state during the fisihing (egs:snagged or notsnagged).

onChange not working as intended without callback

this snippet of code gives me a bad setState error. I want the code in onChange to run immediately without a callback ()=> after onChange, as I want a button to disable if all the form fields are not filled out. If I use a callback, onChange is always one change behind. Is there a way around this?

          <FormControl
            onChange={
              Object.keys(formik.errors).length === 0 &&
              Object.keys(formik.touched).length >= 2
                ? setErrorState(false, formik.values)
                : setErrorState(true)
            }
          >

Here is the full code

import {
  Box,
  FormControl,
  Flex,
  Heading,
  VStack,
  Stack,
  Text,
  Radio,
  RadioGroup,
  Tooltip,
} from "@chakra-ui/react";
import { Formik } from "formik";
import * as Yup from "yup";
import TextField from "./TextField";
import { useDispatch } from "react-redux";
import { setExpress } from "../redux/actions/cartActions";
import { useState } from "react";
import {
  setShippingAddress,
  setShippingAddressError,
} from "../redux/actions/orderActions";

const ShippingInformation = () => {
  const dispatch = useDispatch();

  //formik
  const [formStateChanged, setFormStateChanged] = useState(false);

  // function
  const setErrorState = (errorState, data) => {
    //dispatches shipping info if the user has filled in all field with at least two characters (errorState === false),
    if (errorState === false) {
      dispatch(setShippingAddress(data));
    }
    if (
      (!formStateChanged && !errorState) ||
      (formStateChanged && errorState)
    ) {
      return;
    } else {
      setFormStateChanged(errorState);
      dispatch(setShippingAddressError(errorState));
    }
  };

  return (
    <Formik
      initialValues={{ address: "", postalCode: "", city: "", country: "" }}
      validationSchema={Yup.object({
        address: Yup.string()
          .required("This field is required.")
          .min(2, "This address is too short."),
        postalCode: Yup.string()
          .required("This field is required.")
          .min(2, "This postal code is too short."),
        city: Yup.string()
          .required("This field is required.")
          .min(2, "This city name is is too short."),
        country: Yup.string()
          .required("This field is required.")
          .min(2, "This country name is too short."),
      })}
    >
      {(formik) => (
        <VStack as="form">
          <FormControl
            onChange={
              Object.keys(formik.errors).length === 0 &&
              Object.keys(formik.touched).length >= 2
                ? setErrorState(false, formik.values)
                : setErrorState(true)
            }
          >
            <TextField
              name="address"
              placeholder="Street Address"
              label="Street Address"
            />
            <Flex>
              <Box flex="1" mr="10">
                <TextField
                  name="postalCode"
                  placeholder="Postal Code"
                  label="Postal Code"
                />
              </Box>
              <Box flex="2">
                <TextField name="city" placeholder="City" label="City" />
              </Box>
            </Flex>
            <TextField name="country" placeholder="Country" label="Country" />
          </FormControl>
          <Box width="100%" height="180px" pr="5px">
            <Heading fontSize="2xl" fontWeight="extrabold" mb="10px">
              Shipping Method
            </Heading>
            <RadioGroup
              defaultValue="false"
              onChange={(event) => {
                dispatch(setExpress(event));
              }}
            >
              <Stack
                direction={{ base: "column", lg: "row" }}
                align={{ lg: "flex-start" }}
              >
                <Stack pr="10" spacing={{ base: "8px", md: "10px" }} flex="1.5">
                  <Box>
                    <Radio value="true">
                      <Text fontWeight="bold">Express Shipping $14.99</Text>
                      <Text>Shipped within 24 hours</Text>
                    </Radio>
                  </Box>
                  <Stack spacing="6px">
                    <Text>Express</Text>
                  </Stack>
                </Stack>
                <Radio value="false">
                  <Tooltip label="Free shipping for all orders over $1,000.">
                    <Box>
                      <Text fontWeight="bold">Standard Shipping $4.99</Text>
                      <Text>Shipped within two to three business days</Text>
                    </Box>
                  </Tooltip>
                </Radio>
              </Stack>
            </RadioGroup>
          </Box>
        </VStack>
      )}
    </Formik>
  );
};

export default ShippingInformation;

How can I make jest spied function internally store arguments that the function was called with by deep copy and not by reference

I’m trying to test a class that is combining fetching, caching, geocoding and returning a list of places. The code that is being tested looks something like this (this is not a full working executable code, but enough to illustrate the problem):

interface Place {
  name: string;
  address: string;
  longitude: number | null;
  latitude: number | null;
}

class Places {
  findAll(country: string): Place[] {
    let places = this.placesCache.get(country)
    if (places === null)
      places = this.placesExternalApiClient.fetchAll(country);
      // BREAKPOINT no.1 (before store() call)
      this.placesCache.store(country, places);
      // BREAKPOINT no.2 (after store() call)
    }
    
    for (const place of places) {
      // BREAKPOINT no.3 (before geocode() call)
      const geocodedAddress = this.geocoder.geocode(place.address);
      place.longitude = geocodedAddress.longitude;
      place.latitude = geocodedAddress.latitude; 
    }  

    return places;
  }
}

class PlacesExternalApiClient {
  fetchAll(country: string): Place[] {
    // makes a request to some external API server, parses results and returns them
  }
}

class PlacesCache {
  store(country: string, places: Place[]) {
    // stores country and places in database with a relation
  }

  get(country: string): Place[] | null {
    // if country is in database, returns all related places (possibly []),
    // if country is not in db, returns null
  }
}

interface GeocodedAddress {
  address: string;
  longitude: number;
  latitude: number;
}

class Geocoder {
  geocode(address: string): GeocodedAddress {
    // makes a request to some geocoding service like Google Geocoder,
    // and returns the best result.
  }
}

And this is the test (kinda, illustrates the problem):

mockedPlaces = [
  { name: "place no. 1", address: "Atlantis", longitude: null, latitude: null },
  { name: "place no. 2", address: "Mars base no. 3", longitude: null, latitude: null },
]

mockedPlacesExternalApiClient = {
  fetchAll: jest.fn().mockImplementation(() => structuredClone(mockedPlaces))
}

mockedGeocodedAddress = {
  address: "doesn't matter here",
  longitude: 1337,
  latitude: 7331,
}

mockedGeocoder = {
  geocode: jest.fn().mockImplementation(() => structuredClone(mockedGeocodedAddress))
}

describe('Places#findAll()', () => {
  it('should call cache#store() once when called two times', () => {
    const storeMethod = jest.spyOn(placesCache, 'store');
    
    places.findAll('abc');
    places.findAll('abc');

    expect(storeMethod).toHaveBeenCalledTimes(1);
    expect(storeMethod).toHaveBeenNthCalledWith(
      1,
      'abc',
      mockedPlaces, // ERROR: expected places have lng and lat null, null
                    //    but received places have lng and lat 1337, 7331
    );
  })
})

I found during debugging that, during first iteration over places.findAll() (when there is cache miss):

  • on BREAKPOINT no.1: places (var) has null as coordinates
  • on BREAKPOINT no.2:
    • places (var) still has null as coordinates
    • placesCache.store (which is a Spied jest object) has .mock.calls[0][1] which is an array where there a two places, both with null for lng and lat as expected
  • on first hit of BREAKPOINT no.3: nothing changed in .mock.calls and nothing changed in places (var)
  • on second hit of BREAKPOINT no.3: first place in both arrays: places (var) and array .mock.calls[0][1] had changed their coordinates to 1337, 7331!

because of that, later when I ask jest what argument storeMethod was called with, it incorrectly thinks it was called with latitude and longitude 1337, 7331 and not null, null.

It does not work as I expected it to work because spyOn simply assigns/pushes arguments that it got to .mock.calls[], it does not perform a deep copy, and therefore when the argument is an object that is later mutated, that change is also affecting what the spied object recorded as its call argument.

How can I make spyOn deep clone the arguments it gets?
or, How can I make this test work some other way, without changing the implementation of business logic (first snippet)?

I want to test that store() was called with longitude and latitude set to null. Now my test gives me a false negative.

Regex Match on Multiple Sets

I hate to ask another Regex question since there are a bunch out in the world of stack overflow. However, I am trying to do the following

Match a word or phrase that can have characters in the following sets:

in

u00C0-u1EF3

and in

x20-xFF

but not in

/:<>|?"*´§¤°¸¨'

I have tried various combinations of the following but can’t quite get it:

Here is one attempt:

^([\u00C0-\u1EF3]|[\x20-\xFF](?=[^\/:<>|?"*´§¤°¸¨']))$

The following lists of words or phrase should work

  • kajslkfjsld
  • alksdj laksjdflksd laksj22332
  • 1234
  • $asdf123
  • alksjdf#09092

but the following should not match

  • ?”*majslkdfjslk
  • ¤°¸¨

I am using javascript for this.

Detecting if a site is refreshed on a mobile phone

I developed this js code, that should detect when a site is loaded for the first time or is refreshed. I send this information tho a django view.
The problem is that it works on PC but not on mobile devices like phones, tablets, etc…
Here is the javascript code:

window.addEventListener('load', function() {
            // Check if the page has been reloaded
            var isReloaded = sessionStorage.getItem('isReloaded');

            if (!isReloaded) {
                // It's the first visit or a new session
                sessionStorage.setItem('isReloaded', 'true');
                // Perform actions for the first visit here
                
            }

            // Send the reload information to the server
            var isRefreshed = isReloaded ? 'true' : 'false';
            var csrfToken = '{{ csrf_token }}'; 
            $.ajax({
                type: "POST",
                url: '',
                data: {
                    'is_refreshed': isRefreshed,
                    'csrfmiddlewaretoken': '{{ csrf_token }}' // Include CSRF token for security
                },
                dataType: 'json',
                success: function(data) {
                    // Handle the response from the server here, if needed
                    console.log(data.message);
                },
                error: function(xhr, status, error) {
                    // Handle errors here, if needed
                    console.error(error);
                }
            });// Replace with your CSRF token
            // Make an AJAX request here to send 'isRefreshed' and 'csrfToken' to the server.
        });

Reactstrap component cannot be used as a JSX component

I created a simple typescript react app with react-create-app library.

After that, I installed reactstrap and bootsrap and tried implement a simple reacstrap button to my code

import React from 'react';
import {Button} from "reactstrap";
import 'bootstrap/dist/css/bootstrap.min.css';

function App () {
    return <Button>Button</Button>;
}

export default App;

After start I got the error

'Button' cannot be used as a JSX component.
  Its instance type 'Button' is not a valid JSX element.
    The types returned by 'render()' are incompatible between these types.
      Type 'React.ReactNode' is not assignable to type 'import("/Users/krolov/work/node_modules/@types/react/index").ReactNode'.
        Type 'ReactElement<any, string | JSXElementConstructor<any>>' is not assignable to type 'ReactNode'.
          Property 'children' is missing in type 'ReactElement<any, string | JSXElementConstructor<any>>' but required in type 'ReactPortal'.

vue3 app problem to access state’s variables in store file

I am trying to update in my store (index.js)file the array posts
but I get this error
enter image description here
Here the files

main.js

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'

createApp(App).use(store).use(router).mount('#app')

index.js


import { createStore } from 'vuex'
import { baseApiURL } from '@/config/env'
import axios from 'axios'



const store = createStore({
  state() {
      posts: [{}],
    }
  },
  // GETTERS
  getters: {
    // GET TOTAL PRODUCT ARRAY
    getPosts: (state) => {
      return state.posts
    },
    // GET TOTAL POSTS NUMBER
    getTotalPosts: (state) => {
      //console.log('This is the total post!' + this.totalPosts)
      return state.totalPosts
    },

  },
  // MUTATIONS
  mutations: {
    setCurrentPost(state, newPost) {
      state.currentPost = newPost
      console.log('product mutation -->    ' + state.currentPost.title)
    }
  },
  // ACTIONS
  actions: {
  
    actionLoadListPosts: (context, info) => {
      console.log(info)
      console.log(context)
      axios
        .get(`${baseApiURL}/blog/${info.page}/${info.recordsPerPage}`, {
          headers: {
            Authorization: 'System b24b3b0e-9257-466b-949e-8c0c3841eeb5'
          }
        })
        .then((response) => {
          info.showLoader = false
          console.log(response.data.posts)
          state.posts = response.data.posts  //<<<<<------- error ?????
          console.log(this.posts)
          // return true
        })
    }
    
  }
})
export default store


Please any edea about it? I am new with Vue3. Thanks.

I try to use a mutation for it but it doesn’t seem very logical since I am already inside the store…and I get error as well.
I used the same approach with another vue2 app and the access was completely fine.

Differences between new RegExp(pattern) and pattern.test(string) [duplicate]

I try to create a strong password rule for JavaScript with regex. However, i find a strange result using different approach.

First approach (worked):

const value = 'TTest90()';
const firstApproach = /^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()-_+?.]){2,}).{8,}$/.test(value);

The variable firstApproach is true witch is intended result.

The next approach is using the new RegExp like:

const pattern = '/^(?=(.*[a-z]){3,})(?=(.*[A-Z]){2,})(?=(.*[0-9]){2,})(?=(.*[!@#$%^&*()-_+?.]){2,}).{8,}$/';
const regex = new RegExp(pattern);
const secondApproach = regex.test(value);

But, secondApprocach now is false with the same regex.

I can’t find why secondApproach variable isn’t true because is the same regex.

I am asking this question because I want to understand where I am going wrong. Thank you.

What is the correct way to map and print unique dataset objects in React?

I’m trying to create a filter section for my Side Nav where I can toggle each <li>on or off to show comics of that title only. Currently I am having issues with correctly looping my dataset in order to grab unique name values and printing those as an <li>.

What I’ve tried so far is mapping the PRODUCTS object, grabbing each name value and storing it in an array, looping through that array length with a seperate index value, and then returning that name value if it meets this condition (arr[i] !== arr[j]).

For example my PRODUCTS dataset might contain 15 different products or objects, 5 named Alita Battle Angel, 5 named Wolverine, and 5 named Spiderman.

expected output:
console.log this

(1) Array=[1:'Alita Battle Angel', 2:'Wolverine', 3:'Spiderman'] 

return this

<li> Alita Battle Angel</li>
<li> Wolverine </li>
<li> Spiderman </li>

actual output:
console.log this

(15) Array=[ 1:'Alita Battle Angel', 2:'Alita Battle Angel', 3:'Alita Battle Angel', 4:'Alita Battle Angel', 5:'Alita Battle Angel', 6:'Wolverine', 7:'Wolverine', 8:'Wolverine', 9:'Wolverine', 10:'Wolverine', 11:'Spiderman', 12:'Spiderman', 13:'Spiderman', 14:'Spiderman', 15:'Spiderman' ]

return this

<li>Alita Battle Angel</li>

This is my code: (I am also splitting the name value of each so that it returns only the characters before the ‘,’ to make sure that each comic title is entirely unique. Example: “Alita battle Angel, Vol. 1” —> “Alita Battle Angel”)

import React from "react";
import { PRODUCTS } from "../Utilities/PRODUCTS";
import "./SideNav.scss";

const SideNav = (props) => {
    let arr = [];
    return (
        <div className="sideNav-container">
            <div className="sideNav-title"></div>
            <ul>
                {PRODUCTS.map((product) => {
                    // map the PRODUCTS data

                    // loop products data while carrying a singular products 'name'
                    for (let i = 0; Object.keys(PRODUCTS).length > i; i++) {
                        // add that name value to array list
                        arr.push(product.name.split(",", 1));
                        console.log("products length: " + Object.keys(PRODUCTS).length);

                        // if array greater than 1 item
                        if (arr.length > 1) {
                            console.log(arr);
                            // loop the length of that array
                            for (let j = 0; j < arr.length; j++) {
                                // if array[j] not equal to previous array item return name
                                if (arr[i] !== arr[j]) {
                                    let title = `${product.name}`.split(",", 1);
                                    return <li key={[product.id]}>{title}</li>;
                                } else return null;
                            }
                        }
                    }
                })}
            </ul>
        </div>
    );
};

export default SideNav;

The issue is that my code is injecting the entire dataset as a single object. Basically returning my dataset 15 times as a single array. I don’t get why it is doing this.

I know using the filter method might be a possible solution and also using the useState hook from react. I’ve tried both of these but was received some sort of error specific to my file setup.

Any suggestions for solution would be appreciated.

why the dispatchEvent does not work in React

I want to create a list of product and user can input the value of quantity in a input element. The elementLitsener which is binded on the input works well, it can change the data which is stored in App.js acoordingly. I want set the quantity to ‘0’ by click the reset button, i tried to use dispatchEvent to trigger the change event binded on input element, but it does not work.
Why it behaves like this?

import React, { Component } from 'react'
import "bootstrap/dist/css/bootstrap.min.css";

import './index.css'
export default class Item extends Component {
  constructor(props){
    super(props);
    this.state={
        quantity:0
    }
    this.subtotalRef = React.createRef()
    this.quantityRef = React.createRef()
  }

  //change the quantity 
  handleQuantity=(id)=>{
    return ()=>{
      console.log(11);
      const quantity = this.quantityRef.current.value;
      this.subtotalRef.current.innerHTML = parseFloat(this.props.price*quantity).toFixed(2);
      this.props.changeQuantity(quantity,id);
    }
      
  }

  //reset the quantity
  handleReset=()=>{
    this.quantityRef.current.value = 0;
    // this.handleQuantity(this.props.id)();
    this.quantityRef.current.dispatchEvent(new Event("change",{bubbles:true}))
  }

  render() {
    const {id,quantity,name,price,index} = this.props
    return (
      <tr>
      <th scope="row">{index}</th>
      <td>{name}</td>
      <td>{price}</td>
      <td><input type="number" min="0" step="1" onChange={this.handleQuantity(id)} ref={this.quantityRef} value={quantity}/></td>
      <td ref={this.subtotalRef}>$ 0.00</td>
      <td>
        <button type="button" className="btn btn-warning" onClick={this.handleReset}>reset</button>
        <button type="button" className="btn btn-danger">delete</button>
      </td>
    </tr>    )
  }
}

Is there any way I could see the money I hacked in bit burner script

Is there any way I could see the money I hacked in bit burner script?
I am writing a script for bit burner and I want to see the amount of money I get from hacking the server the script weakens the server grows it and then hacks it with a few more steps.
the script is below

/** @param {NS} ns */

export async function main(ns) {

    var server = ns.args[0];
    var security = ns.getServerSecurityLevel(server);
    var min_s = ns.getServerMinSecurityLevel(server);
    var base_s = ns.getServerBaseSecurityLevel(server)
    var x = 0;
    var bar = "_________________________________________"
    var serverCM = ns.getServerMoneyAvailable(server);
    var server_thresh = 1000;
    while (true) {
        x += 1
        // clear the log

        ns.clearLog()
        ns.disableLog('ALL')
        // Showing how many times the program has run and display income
        ns.print("Ran ", x, ' times');
        ns.print(bar)
        ns.print("Money made from script currently: ", ns.getScriptIncome("weaken.js", server, server))
        ns.print(bar)
        ns.print("Current server money: ", ns.getServerMoneyAvailable(server))
        ns.print(bar)
        ns.print("Max server money: ", ns.getServerMaxMoney(server))
        ns.print(bar)
        ns.print("Base security: ", base_s)
        ns.print(bar)
        ns.print("Current security: ", security)
        ns.print(bar)
        ns.print("Min security: ", min_s)
        ns.print(bar)
        // Weaken the sever
        if (security != min_s) {
            ns.print("Weakening");
            await ns.weaken(server);
            ns.print('Weakened');
            ns.print(bar)
        }// Growing
        else {
            ns.print("Skipping weakening not needed")
            ns.print(bar)
        }
        ns.print("Attempting to grow ", server)
        ns.print(bar)
        ns.print("Growing")
        await ns.grow(server)
        // Attempt to hack
        ns.print(bar)
        ns.print("Attempting to hack ", server);
        ns.print(bar)
        if (serverCM >= server_thresh) {
            await ns.hack(server);
            ns.print("Hack succesfull")
        }
        else {
            ns.print("Hack unsucessful continuing script")
        }
    }
}

I looked at the documentation and didn’t see anything useful but I may not have looked thoroughly enough