Why does this random walk I wrote look suspiciously non-random?

I’m trying to write a random walk in JavaScript using P5 js. My goal is to let it walk randomly in the x or y direction and randomly through a subset of color-space (just the hue section of HSV). I added modular division into the walk so that it just loops around at the edges.

The problem is nearly all of the random walks seem to move in a very similar way – in a sort of stair-step diagonal pattern. The exact shape of the stairstep is random but it’s very clearly not even random to the level of a typical pseudorandom generator. The color walk seems to work but it also tends to spend a suspicious amount of time clustered around red (hue=0). I did very similar code with Python and OpenCV earlier the same day and it produced exactly what one would expect for a random walk (I know python uses a Mersenne twister and JavaScript likely uses something else for their pseudorandom RNG but I suspect that something else is at play here).

The page is hosted here and the code is here I would include it in the post directly but stackoverflow is giving me a weird issue about my code not being formatted like code even though I have tried fencing it with triple backticks and 4 space indenting it etc and I’ve posted code on SO before without issue but that’s not my main concern here my main concern here is fixing the random walk.

I got the issue in both Chrome and Firefox (I didn’t test another browser). Attached are some screenshots in case the behavior doesn’t occur on your device

First example
Second example

how to render common using mixin in vue.js?

Can i render common using mixin in vue.js?

for example

<template>test: {{ test }}</template>

<script>
export default {
  data() {
    return {
      test: 1,
    }
  },
}
</script>
// mixin
export default {
  data() {
    return {
      mixinData: 10,
    }
  },
  render() {
    if (this.mixinData === 10) {
      // mixin render, not component render
    } else {
      // component render, not mixin render
    }
  }
}

can i do this using mixin in vue.js?
i want to know way about common render using mixin.

DataTable date range filter shows incorrect results

I have implemented version 1.13.1 of the DataTable. Which I have the filter by date range, and I have created two buttons, one to proceed with the filter, and the other to reset it (In the guide of the datatable web page, there are not these buttons).

Date Range Filter Datatable

The problem is that when filtering and resetting several times (trying various combinations in the date picker), there are some results that are displayed erroneously.

I don’t know if the algorithm that I implemented is the correct one for the functionalities (the two buttons) that I want.

Thanks in advance.

var minDate, maxDate;

$(function() {
    // Create date inputs
    minDate = new DateTime($('#min'), {
        format: 'DD / MM / YYYY'
    });
      maxDate = new DateTime($('#max'), {
        format: 'DD / MM / YYYY'
    });
 
    // DataTables initialisation
    var table = $('#example').DataTable();

    $("#filter_date").click(function() {

       if ( $("#min").val() !== "" || $("#max").val() !== "") {
            // Custom filtering function which will search data in column four between two values
            $.fn.dataTable.ext.search.push(
                function( settings, data, dataIndex ) {
                    var min = minDate.val();
                    var max = maxDate.val();
                    var date = new Date( data[4] );
             
                    if (
                        ( min === null && max === null ) ||
                        ( min === null && date <= max ) ||
                        ( min <= date   && max === null ) ||
                        ( min <= date   && date <= max )
                    ) {
                        return true;
                    }
                    return false;
                }
            );

            table.draw();
        }
    });

    $("#reset_filter_date").click(function() {

        if ( $("#min").val() !== "" || $("#max").val() !== "" ) {
            $("#min, #max").val("");
            $.fn.dataTable.ext.search = [];
            table.draw();
        }
    });
});
<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Demo</title>

  <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
  <script src="https://cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.2/moment.min.js"></script>
  <script src="https://cdn.datatables.net/datetime/1.2.0/js/dataTables.dateTime.min.js"></script>


  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.12.1/css/jquery.dataTables.css">
  <link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">

  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css">
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/datetime/1.2.0/css/dataTables.dateTime.min.css">


</head>

<body>

  <div style="margin: 20px;">

    <table border="0" cellspacing="5" cellpadding="5">
      <tbody>
        <tr>
          <td>From:</td>
          <td>
            <input type="text" id="min" name="min">
          </td>
        </tr>
        <tr>
          <td>Until:</td>
          <td>
            <input type="text" id="max" name="max">
          </td>
        </tr>
        <tr>
          <td>
            <button id="filter_date">Filter</button>
            <button id="reset_filter_date">Reset</button>
          </td>
        </tr>
      </tbody>
    </table>

    <br><br>


    <table id="example" class="display dataTable cell-border" style="width:100%">
      <thead>
        <tr>
          <th>Name</th>
          <th>Position</th>
          <th>Office in Country</th>
          <th>Age</th>
          <th>Start date</th>
          <th>Salary</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Tiger Nixon</td>
          <td>System Architect</td>
          <td>Edinburgh</td>
          <td>61</td>
          <td>2011/04/25</td>
          <td>$320,800</td>
        </tr>
        <tr>
          <td>Garrett Winters</td>
          <td>Accountant</td>
          <td>Tokyo</td>
          <td>63</td>
          <td>2011/07/25</td>
          <td>$170,750</td>
        </tr>
        <tr>
          <td>Ashton Cox</td>
          <td>Junior "Technical" Author</td>
          <td>San Francisco</td>
          <td>66</td>
          <td>2009/01/12</td>
          <td>$86,000</td>
        </tr>
        <tr>
          <td>Sonya Frost</td>
          <td>Software Engineer</td>
          <td>Edinburgh</td>
          <td>23</td>
          <td>2008/12/13</td>
          <td>$103,600</td>
        </tr>
        <tr>
          <td>Donna Snider</td>
          <td>Customer Support</td>
          <td>New York</td>
          <td>27</td>
          <td>2011/01/25</td>
          <td>$112,000</td>
        </tr>
      </tbody>
    </table>

  </div>


</body>

</html>

How would i grey out the rest of the text in my table record when i select the 3rd option in my drop down menu?

I’m currently trying to make my other table items grey out when i select the third option in my table menu which is called “closed” with an id of 3.

This is in the status drop down menu as seen here.

I’m trying to figure out how to make the CaseID, date, name, details and Status sections become greyed out, when the status part of the table record is “closed”.

enter image description here

<% include ../partials/header.ejs %> 

<% include ../partials/main_nav.ejs %> 

<!-- MAIN CONTENT -->
<div class="jumbotron">
<div class="container">
  <div class="reportContainer">
  <div class="row">
    <div class="col-md-offset-1 col-md-10">
      <h1 class="display-4">Incident Reports</h1>  
      
      
      <br />
      <!-- Details of the table and how to submit new reports -->
      <p>The information below is the current incident reports that have been submitted.<p>
       <p> To add a new report, click <a href="/reports/add">here</a> or use the <strong>Create a Report</strong> button below.<br>
          To edit a report, a report, use the Edit button.<br>
          To delete a report, click the <strong>Delete</strong> button. This is instant, permanent, and will not ask for confirmation.</p>
      <div class="table-responsive">
        <table class="table table-bordered table-striped table-hover">
          <thead>
            <tr>
              <th>CaseID</th>
              <th class="text-center">Date</th>
              <th class="text-center">Name</th>
              <th class="text-center">Details</th>
              <th class="text-center">Status</th>
              <th class="text-center"></th>
            </tr>
          </thead>
          <tbody>
            <!-- Template Row -->
            <% for (let count = 0; count < incident_reports.length; count++) { %>
            <tr>
              <td><%= incident_reports[count].caseID %></td>
              <td class="text-center" for="payment-method"><%= incident_reports[count].date %></td>
              <td class="text-center"><%= incident_reports[count].name %></td>
              <td class="text-center"><%= incident_reports[count].details %></td>
              <td class="text-center"><%= incident_reports[count].Status %></td>

              <td class="text-center">
                <a href="/reports/edit/<%= incident_reports[count]._id %>" class="btn btn-primary" style="background-color: #f59e2e; border-color:#f59e2e;"
                  ><i class="fa fa-plus"></i> Edit</a
      >
      <a href="/reports/delete/<%= incident_reports[count]._id %>" class="btn btn-warning btn-sm" style="background-color: #ff3e3e; color: white; border-color: #ff3e3e;">
        <i class="fas fa-trash-alt"></i> Delete</a>


        <div class="btn-group">
          <button type="button" class="btn  dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
            Status
          </button>
          <ul class="dropdown-menu" onChange="selectChanged()">
            <li><a class="dropdown-item" href="/reports/inprogress/<%= incident_reports[count]._id %>" id="1">In Progress</a></li>
            <li><a class="dropdown-item" href="/reports/dispatched/<%= incident_reports[count]._id %>" id="2">Dispatched</a></li>
            <li><a class="dropdown-item" href="/reports/closed/<%= incident_reports[count]._id %>" id="3">Closed</a></li>
            <li><hr class="dropdown-divider"></li>
            <li><a class="dropdown-item" href="#">Separated link</a></li>
          </ul>
        </div>

              </td>
            </tr>
            <% } %>
          </tbody>
        </table>
      </div>
  </main>
  <a href="/reports/add" class="btn btn-primary"><i class="fa fa-plus"></i> Create a Report</a>

      <div class="col-md-offset-1 col-md-10 text-center">
        <ul class="pagination pagination-lg pager" id="myPager"></ul>
      </div>
      </div>
    </div>
  </div>
</div>
</div>



<script>
function selectChanged() {
  var x = document.getElementById("payment-method").value;
  document.getElementById("creditcard").disabled = (x == 1);
}
// selectChanged();
</script>
<% include ../partials/bottom_nav.ejs %>

<% include ../partials/footer.ejs %>

Thank you in advance.

Link inside table, reload entire page in reactjs

I try to create <Link> inside <td> in <table> reactjs.

When i click the link outside table it’s move to path without reload entire page.

But, when i click the link inside table, it’s move to the path and reload entire page.

Here is my code inside table:

<table className="table table-responsive" id="datatable-search">
   <thead className="thead-light">
      <tr> ...
      </tr>
   </thead>
   <tbody>
   {this.state.tableData.map((val, index) => {
      return (
         <tr key={index}>
             <td>...
             <td>
                 <Link to={url_edit}>
                     Edit
                 </Link>
              </td>
         </tr>
      )
    })}
    </tbody>
</table>

How can i make <Link> inside table is not reload entire page ?

React – axios fetching empty array [duplicate]

I could not fetch the data using axios, despite fetching it succesfully through postman. Not sure why this is happening

Here’s my function in react

import axios from "axios";

const url = "http://localhost:3001/tasks/";

const getDashboardData = async (setTasks) => {
  await axios.get(`${url}`, {
    uid: sessionStorage.getItem("uid")
  })
    .then((result) => {
      console.log(result.data);

      setTasks(result.data);
    })
    .catch((error) => {
      console.log(error);
    })
}

Web app side

import React, { useContext, useEffect, useState } from 'react'
import { UserContext } from '../layout/Layout';
import { getDashboardData, handleCreate } from './DashboardScripts';

const Dashboard = () => {
  const {user, setUser} = useContext(UserContext);
  const [tasks, setTasks] = useState(null);

  useEffect(() => { getDashboardData(setTasks) }, []);

...

Here’s my server side code

// Returns all tasks
router.get("/", async (req, res) => {
  let uid = req.body.uid;
  await db.collection("users").doc(uid).collection("tasks").get()
    .then((querySnapshot) => {
      let tasksTemp = [];
      querySnapshot.forEach((doc) => {
        // doc.data() is never undefined for query doc snapshots
        tasksTemp.push([doc.id, doc.data()]);
      });
      res.status(200).send(tasksTemp);
    })
    .catch((error) => {
      res.status(400).send(error.message);
    });
})

Postman screenshot
Postman

I’m not sure whether I’m writing the Axios request properly, or whether I’m calling it the function wrongly from the web app. I tried different ways of writing the Axios request to no avail

Angular Bootstrap import loads css but not JS

I have had lots of problems importing bootstrap using the npm modules.
I even tried updating my angular to v 15 to try fix the issue.

If I do not either include the assets manually or use an external CDN, the bootstrap routing and other functions stop working. Even explicitly including the ../node_modules/ ... files doesn’t work. I tried following the different steps here: https://www.techiediaries.com/angular-bootstrap/ without success either.

package.json

  "@popperjs/core": "^2.11.6",
  "bootstrap": "^4.6.2",
  "jquery": "^3.6.0"

angular.json

...
  "projects": {
    "my-project": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "assets": [
              "src/images",
              "src/js",
              "src/css",
              "src/assets",
              "src/favicon.ico"
            ],
            "styles": [
              "src/styles.css",
              "./node_modules/cookieconsent/build/cookieconsent.min.css",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css"
            ],
            "scripts": [
              "./node_modules/jquery/dist/jquery.min.js",
              "./node_modules/cookieconsent/build/cookieconsent.min.js",
              "./node_modules/popper.js/dist/popper.min.js",
              "./node_modules/bootstrap/dist/js/bootstrap.min.js"
            ]
...

index.html


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyProject</title>
  <base href="/">
    
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body">
  <div class="container">
    <div>
      <app-root></app-root>
    </div>
  </div>
   <!-- Bootstrap core JavaScript
    ================================================== -->
    <!-- Placed at the end of the document so the pages load faster -->
    <script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
    <!-- <script src="../node_modules/jquery/dist/jquery.min.js"></script> -->
    <!-- <script src="../../../../assets/js/popper.min.js"></script> -->
    <script src="../../../../assets/js/bootstrap.min.js"></script>  
    
    <!-- <script src="../node_modules/bootstrap/dist/js/bootstrap.min.js"></script> -->

</body>
</html>

Scroll to reveal elements one by one

I’d like to have elements in an array be consecutively revealed as the user scrolls. I found some code from here which sort of does what I want, and modified it like this:

var unit = document.querySelectorAll("span");
var i = 0;
var currentID = 0;
var slideCount = unit.length;

document.addEventListener("scroll", (e) => {
  let scrolled =
    document.documentElement.scrollTop /
    (document.documentElement.scrollHeight -
      document.documentElement.clientHeight);

  unit.forEach(function (l, i) {
    if (i / unit.length < scrolled) {
      l.style.setProperty("--percentage", 1);
    } else {
      l.style.setProperty("--percentage", 0);
    }
  });
});
:root {
  --percentage: 0;
}

#reveal span {
  opacity: var(--percentage);
}

body {
  height: 2000px;
}

#reveal {
  position: fixed;
  top: 0;
  left: 0;
}
<div id="reveal">
  <span>Scrolling</span>
  <span>should</span>
  <span>reveal</span>
  <span>elements</span>
  <span>one</span>
  <span>by</span>
  <span>one</span>
</div>

I’m wondering how I can rework this code so it doesn’t rely on the height of the body in order to operate. I’d like to eliminate all scrollbars (which is proving difficult on iOS).

My search query box doesnt automatically recommend places in vue and with vs code

When you run my code, it is supposed to open up a website. This works fine and all, however, whenever I try to go to the input box it is supposed to immediately recommend places with the characters given. This isn’t working. I am doing a tutorial and am currently on 12:41 of this video.
https://www.youtube.com/watch?v=5pTzHoliXUQ&list=PL4cUxeGkcC9hfoy8vFQ5tbXO3vY0xhhUZ&index=5

This is my code:

`

<template>
  <main class="container text-white" >
    <div class="pt-4 mb-8 relative">
      <input type="text" 
      v-model = "searchQuery"
      @input="getSearchResults"
      placeholder="Search for city or state" 
      class="py-2 px-1 w-full bg-transparent border-b
       focus:border-weather-secondary focus:outline-none focus:shadow-[0px_1px_0_0_#004E71]">
       <ul class="absolute bg-weather-secondary text-white w-full shadow-md py-2 px-1 top-[66px]">
        <li v-for="searchResult in mapboxSearchResults" :key ="searchResult.id" class="py-2 cursor-pointer">
          {{searchResult.place_name}}
        </li>
       </ul>
    </div>
  </main>
</template>

<script setup>
import { ref } from 'vue';
import axios from 'axios';

const mapboxAPIkey ="pk.eyJ1IjoiYWhhbmFhYSIsImEiOiJjbGJqc3d5NG0xNGd5M3BtbWppcmgyNzE4In0.L-HsHWAbshfvVY_xixizNw"

const searchQuery = ref("");
const queryTimeout = ref(null)
const mapboxSearchResults = ref(null)

const getResults = () => {
  clearTimeout(queryTimeout.value)
  queryTimeout.value = setTimeout(async() => {
    if(searchQuery.value !== ""){
      const result = await axios.get(
        `https://api.mapbox.com/geocoding/v5/mapbox.places/${searchQuery.value}.json?access_token=${mapboxAPIkey}&types=place`
      )
      mapboxSearchresults.value = result.data.features
      return;
    }
    mapboxSearchresults.value = null
  }, 300)

}
</script>

`

I tried to run the code with npm run dev in the terminal and everything was working fine up until this point.

How to properly navigate a li tag to build a OBJECT in a HTA

I am trying to build a tool to dynamically build and edit a JSON file. I created a HTA that will dynamically create elements for each data type and build it out in the UI using li and ul. The basic format of these are

<li type='list'> 
   <span>Name</span>
   <div> bunch of html that has hidden edit pop up windows and other controls </div>
   <li><ul> sub entries </ul></li>
</li>

There is one for each type of entry. It pulls these templates out of a library of template files. The problem I am having is walking through the finished UI to build the JSON file. Even though the <li><ul></ul></li> is inside of the the parent li it seems when I try to walk through the DOM to fetch everything it treats all the li as if they are at the same level. Kind of hard to shave it down to a bite size example to put on here because the whole thing pulls on other files to work. I tried doing a mix of jquery and queryselects but all the ways I tried it grabs the sub li along with the first parent li. So clearly I don’t understand things as well as I thought I did.

Here is a image of what the placeholder UI looks like.

enter image description here

Also I have to use things as they are I cant use any other software or language for this particular project. I tried to build out the Object as the Entries were added but even though I got it kind of working it was hard to follow and I know for a fact that in a month or so when I have to update something I wont be able to understand what I was doing. So the question is am I going about the building of the list elements all wrong? Or am I going about getting the info from the finished UI all wrong? Should I be using something other than li and ul?

Potential reasons autocompleteclose event not available within a function?

I’m migrating some old code to a new site and there are lots of JS libraries being used so trying to pinpoint why this isn’t working has been difficult. In short within a function I need this code to run:

    $(tabID).on( "autocompleteclose", function() {
        some_function(var1, var2, var3, var4, var5);
    });

These variables are only available within this function so that’s why its being called within there.

If I define the event listener outside of the function in the main JS file, the event listener works. Overall, it appears to be some namespace issue as I’ve had issues getting other jQuery libraries working in this file when within functions, but in the main body of the file they work. I’m not terribly familiar with JS (and jQuery more specifically) so I’m looking at some starting points to figure out why it’s not working.

As mentioneed above, the autocompleteclose event listener will work within the body of the JS file, but not within any functions. It appears to be a namespace issue with the JS libraries but I’m having trouble figuring out what are some other steps I can do to narrow down the cause of the error.

Age predictor API, if statement not allowing user to just enter Name

so I’ve just started learning about API’s and implementing them. SO far I have got it working but have run across one problem that I can’t seem to figure out. Basically it is an API that takes in a users name and country code and predicts their age. The problem I am having is that If I leave the country Code empty it says you have to choose a country. I want it so it can just take in a name and it will predict the age as well as a name and country code. That works but inputting the name on it’s own doesn’t.

I think I have narrowed it down to this if statement but unsure how to proceed. Any help is appreciated Here’s my code below



function getage(){
    const user_name = document.getElementById('username').value;
    const country = document.getElementById('country').value;
    const guess = document.getElementById('guess');

    const link = 'https://api.agify.io?name='+user_name+'&country_id='+country;
    var request = new XMLHttpRequest();
    request.open('GET', link);
    request.send();
    request.onload = ()=>{
        data = JSON.parse(request.response)
        age = data['age']
        console.log(age)
        console.log(link)
        console.log(user_name)
        // console.log(JSON.parse(request.response))

        if (age == null || age == undefined){

            if (country == "") {
                document.getElementById('result').innerHTML = 'Please select a country.';
            }
            else { 
                document.getElementById('result').innerHTML = 'Enter a valid name.';
            }
        }

        else{
            document.getElementById('result').innerHTML = 'You are '+age+' years old!';
        }
    }
}

How do I center a dynamically-changing background image without CSS?

How do I center a dynamic background image? Tried using divs and center tags but it just breaks the code. Prefer to not use CSS. I’ve looked at the other threads and using the code in the html and body doesn’t work.

The code:

`

<html>
<head>
  <style>
    .day {
      background-image: url(day.jpg);
    }
    
    .night {
      background-image: url(night.jpg);
    }
  </style>
</head>
<body class="day" class="night">
  <script>
    setInterval(change_background, 1000 * 60 * 1);

    function change_background() {
      var d = new Date();
      var n = d.getHours();
      console.log(n);
      if (n == 19 || n < 7) {
        document.body.className = "night";
      } else {
        document.body.className = "day";
      }
      console.log("test");
    }

    change_background();
  </script>
</body>
</html>

`

How to get notified of a gj-dialog-md-close span X click

Heollo,

I have the following container:

<div id="volumesContainer" class="container-fluid scrollBox fluidCentrePosition close" style="display:none" title="Select Volumes">     
            <!--<label for="colorpicker">Colour Picker:</label>
            <input type="color" id="colourChoice" value="#2929d6">-->
            <div class="row">
                <div id="volTree"></div>
            </div>
            <div class="row">
                <div style="margin: auto; width: 95%;">
                    <div class="col-xs-4">
                        <button id="volTreeCheckAll" class="gj-button-md">Check All</button>
                        <button id="volTreeUncheckAll" class="gj-button-md">Uncheck All</button>
                        <div class="clear"></div>
                    </div>
                </div>
            </div>
        </div>

when I click on the volumesContainer ‘x’ or anywhere on the Title/header the following is called:

$('.close').click(function (e) {                
    if(e.currentTarget.id == "volumesContainer") {              
      //do stuff
    }
}

How do I get it so the .close is only called when the span ‘x’ is clicked? Should the close even be there? Or how do I access the gj-dialog-md-close? Will that help?

I am new to html so I expect that is a nicer/correct way to do this but I am unsure.

Thank you very much.

enter image description here