Moving Average Line in Highcharts Scattered Chart

I am trying to implement a Moving Average line in a Highachart’s Scattered chart. The x Axis is a Date and y axis is days but when I try to calculate the Moving average its is referring to date with year 1970.

Here is js fiddle link for my code:
enter link description here

I also have code without moving Average and the link is enter link description here

Here is the Highchart code with Moving average I am using :

Highcharts.chart('container', {
chart: {
    type: 'scatter',
    zoomType: 'xy'
},
title: {
    text: 'Height Versus Weight of 507 Individuals by Gender'
},
subtitle: {
    text: 'Source: Heinz  2003'
},
xAxis: {
  title: {
    enabled: true,
    text: 'PR Creation'
  },
  startOnTick: true,
  endOnTick: true,
  showLastLabel: true,
  type: 'datetime',
  dateTimeLabelFormats: {
  second: '%Y-%m-%d<br/>%H:%M:%S',
  minute: '%Y-%m-%d<br/>%H:%M',
  hour: '%Y-%m-%d<br/>%H:%M',
  day: '%Y<br/>%m-%d',
  week: '%Y<br/>%m-%d',
  month: '%Y-%m',
  year: '%Y'
}
},
 yAxis: {
title: {
  text: 'duration'
},
type: 'datetime', //y-axis will be in milliseconds
dateTimeLabelFormats: {
minute: '%H:%M'
                      }
 },
legend: {
    layout: 'vertical',
    align: 'left',
    verticalAlign: 'top',
    x: 100,
    y: 70,
    floating: true,
    backgroundColor: Highcharts.defaultOptions.chart.backgroundColor,
    borderWidth: 1
},
plotOptions: {
    scatter: {
        marker: {
            radius: 5,
            states: {
                hover: {
                    enabled: true,
                    lineColor: 'rgb(100,100,100)'
                }
            }
        },
        states: {
            hover: {
                marker: {
                    enabled: false
                }
            }
        },
        tooltip: {
            headerFormat: '<b>{series.name}</b><br>',
            pointFormat: '{point.x}'
        }
    }
},
 
series: [{
    name: 'PR',
    color: 'rgba(223, 83, 83, .5)',
     data: [{x:st4,y:3},{x:st5,y:7},{x:st6,y:8},{x:st7,y:9},{x:st8,y:9},{x:st9,y:7},{x:st10,y:7},{x:st11,y:3},{x:st12,y:2}]

},
{
   name: 'PR',
    color: 'green',
     data: [{x:st,y:5},{x:st3,y:7},{x:st11,y:1}]
}]
}
 ,function() {
            var Highcharts = this;
            var series = Highcharts.series[0];
            var data = [];
            var period = 2;
            var sumForAverage = 0;
            var i;
            for(i=0;i<series.data.length;i++) {
                sumForAverage += series.data[i].y;
                if(i<period) {
                    data.push(null);
                } else {
                    sumForAverage -= series.data[i-period].y;
                    data.push([series.data[i].x, sumForAverage/period]);
                }
            }
            Highcharts.addSeries({
                name: 'Moving Average',
                data: data
            });
        });

Please suggest if you have an idea on calculating the moving average . I am trying to implement something similar to the cycle time widget in Azure Devops

Why is my CSS stylesheet not working using NodeJS and Express?

I am using EJS and Express for an application I am doing just for fun.
In my application, I am utilizing partials from a folder called views/partials. My css stylesheet is located in a directory called public. I have included app.use(express.static(path.join(__dirname, 'public'))); in my express routes directory. And it is working on all other pages besides this one, (edit.ejs):

<%- include('partials/head') %>


<div id="updatecustomer">
    <h1>Update Customer Profile</h1>

    <form method="post" action="/<%=customer.id%>?_method=PATCH">
        <label for="firstname">First Name</label>
        <input type="text" name="firstName" id="firstname" placeholder="<%= customer.firstName %>">
        <label for="lastname">Last Name</label>
        <input type="text" name="lastName" id="lastname" placeholder="<%= customer.lastName %>">
        <label for="phonenumber">Phone Number</label>
        <input type="text" name="contactNumber" id="phonenumber" placeholder="<%= customer.contactNumber %>">
        <label for="address">Address</label>
        <input type="text" name="address" id="address" placeholder="<%= customer.address %>">
        <label for="city">City</label>
        <input type="text" name="city" id="city" placeholder="<%= customer.city %>">
        <label for="state">State</label>
        <input type="text" name="state" id="state" placeholder="<%= customer.state %>">
        <label for="zipcode">Zipcode</label>
        <input type="text" name="zipcode" id="zipcode" placeholder="<%= customer.zipcode %>">
        <button type="submit">Update Customer</button>
    </form>
</div>

A snippet from index.js of my get/patch request, (I’m not using a database, simply an array of objects.):

app.get('/:id/edit', (req, res) => {
    const { id } = req.params;
    const customer = customers.find(c => c.id === id)
    res.render('edit', { customer })
})

app.patch('/:id', (req, res) => {
    const { id } = req.params;
    const foundCustomer = customers.find(c => c.id === id);

    const customerFirstname = req.body.firstName;
    foundCustomer.firstName = customerFirstname;

    const customerLastname = req.body.lastName;
    foundCustomer.lastName = customerLastname;

    const customerAddress = req.body.address;
    foundCustomer.address = customerAddress;

    const customerCity = req.body.city;
    foundCustomer.city = customerCity;

    const customerState = req.body.state;
    foundCustomer.state = customerState;

    const customerZip = req.body.zipcode;
    foundCustomer.zip = customerZip;

    const customerContactNum = req.body.contactNumber;
    foundCustomer.contactNumber= customerContactNum;

    res.redirect('/');
})
        

I have tried adding the styles manually to the page, clearing my browser data, and spent hours looking up a solution and remained stumped on this issue. Any ideas?

Having trouble with this drill: Find the most expensive item name [duplicate]

I’m supposed to find the most expensive item with a function and return the .itemName. I’m struggling to find what’s wrong the example of the array is :

let items = [
  {
    itemName: "Effective Programming Habits",
    type: "book",
    price: 13.99
  },
  {
    itemName: "Creation 3005",
    type: "computer",
    price: 299.99
  },
  {
    itemName: "Finding Your Center",
    type: "book",
    price: 15.00
  }
]
function mostExpensiveItemName(items){
  let highestPrice = 0;
  let expensiveItem ;
  
  
  for(let i = 0 ; i < items.length; i++){
   if (items[i].price > highestPrice) 
    
 highestPrice = items[i].price ; 
    expensiveItem = items[i].itemName;
  }
  
  return expensiveItem;
}

im making a circle follow the cursor which is working fine but how do i add a smoother effect and avoid the circle going out of the page

I have made a circle that follows the cursor using jquery which works fine but i want to give it a smoother effect, i have tried using timeout but that wont work which is kinda obvious so is there any other way to achieve this ?

Also whenever the cursor is close to the border of the webpage or crosses it the circle also goes outside the webpage creating a scrollbar can this be avoided by any way ?

My code –

var mouseX = 0, mouseY = 0;
  var xp = 0, yp = 0;
  let mouseMovementStoppedTimer;
  const mouseMovementStopped = function() {
  $("#circlecc").css({ opacity: 0});
 }  

  $(document).mousemove(function(e){
    
    $("#circlecc").css({opacity: 1}) 
    mouseX = e.clientX - 12;
    mouseY = e.clientY - 12;
    setTimeout(() => {
    $("#circlecc").css({left: mouseX +'px', top: mouseY +'px'});
    }, 50)
    clearTimeout(mouseMovementStoppedTimer);
    mouseMovementStoppedTimer = setTimeout(mouseMovementStopped, 120);
  });

My Website

Objects are not valid as a React child [object Promise]

I’m new using reactjs. First case I want to get a json data from fetch url, but that json need async await to show all data. I managed to solve that problem, but now I want to append data from json to react return render. and then i get error like this Uncaught Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.. This is my code

  async function URL(url, id){
    return fetch(url+"/"+id)
    .then((response) => response.json())
    .then((responseJson) => {
        const myArrayresponse = responseJson.image.split("/");
        return "https://myurl.com/"+myArrayresponse[2]+"/"+myArrayresponse[3];
    })
    .catch((error) => {
       return "images/icon.png";
    });
  }

const posts = datas[0].map((mydata, i) => URL(mydata.uri, mydata.id).then(img => {
      return `<a href={"https://myurl.com/"+CONFIG.ADDRESS+"?a="+mydata.id} target="_blank" className="mybtn"><div className="title">{mydata.name} ({mydata.symbol} - {mydata.id})</div><img src={img} /></a>`;
      })
    );
    
return (
<ResponsiveWrapper flex={1} style={{ padding: 24 }} test>
   <s.Container flex={1} jc={"center"} ai={"center"}>
       {posts}
   </s.Container>
</ResponsiveWrapper>
)

const post is [object Promise], how to append const post to react return render without [object Promise]?

In React, can you use useState variable_1 as default value for another useState variable_2?

  1. Can you use useState variable_1 as default value for another useState variable_2, especially when variable_1 is being set by useEffect?

  2. Even simpler, can you use useState variable_1 as default value for another useState variable_2 (without the useEffect dependency)?

To elaborate, here’s an example

const [firstName, setFirstName] = useState("DEFAULT_NAME");
const [fullName, setFullName] = useState(firstName); //is doing this permissible?

useEffect(() => {
  setFirstName("REAL_NAME")
}, []);

console.log(fullName); // what would be printed here?

What would the value of fullName be? Would it be set to "DEFAULT_NAME" (signaling that it was set BEFORE the useEffect was called) or be set to "REAL_NAME" (signaling that it was set AFTER the useEffect was called)?

Alternative to OnClick for select tag

I have a javascript function that changes a dropdown menu’s options based on some radio buttons that have been selected. I originally had the radio buttons set to “Onclick” to run the function but as it is based on 2 different sets of radio buttons this does not work. I changed the OnClick to happen when the user selects the drop down however now you cannot select an actual option as it just resets the dropdown when a selection is made. Is there and alternative I can use?

Genotype <select name="dropdown" id="dropdown" onClick = "DROPDOWN(father);"></select>

Where am I going wrong in this PRNG generator algorithm in JavaScript?

So I started off with this as a base How to get this PRNG to generate numbers within the range? Now I modified it like so (sorry for the messy code):

// https://primes.utm.edu/curios/index.php?start=5&stop=5

const fs = require('fs')
const startParts = `mi
ma
mo
ne
nu
di
da
do
be
bu
ti
te
ta
to
tu
ki
ke
ka
ko
ku
si
sa
so
ze
zu
fi
fa
fo
ve
vu
xe
xu`.split(/n+/)
const endParts = `le
ru
mu
ne
du
be
te
tu
ke
ku
su
ze
fu
ve
xe
xu`.split(/n+/)
const parts = startParts.concat(endParts)
const pattern = new RegExp(parts.map(x => `${x}${x}${x}`).join('|'))

const fetch = (x, o) => {
  if (x >= o) {
    return x
  } else {
    const v = (x * x) % o
    return (x <= (o / 2n)) ? v : o - v
  }
}

const SIZES = {
  64: {
    fetch: 41223334444555556666667777777888888889999999997n,
    xor: 2030507011013017019023n,
    j: 272261127249452727280272961627319532734291n,
  },
  32: {
    fetch: 3132343537383103113163n,
    modulo: BigInt(Math.pow(32, 15)),
    xor: 541613713n, // possibly half the size or less, and prime.
    j: 975319753197531975319n // almost as big as the other.
  },
  // total: 68,719,476,736
  // total: (32 * 16) * (32 * 16) * (32 * 16) * 32 = 4,294,967,296
  14: {
    fetch: 3778888999n,
    modulo: BigInt(Math.pow(32 * 16, 3) * 32),
    xor: 54121n,
    j: 1012639687n,
    max: 14
  },
  12: {
    // 134,217,728
    fetch: 134095867n,
    modulo: BigInt(Math.pow(32 * 16, 3)),
    xor: 7333n,
    j: 118818811n,
    max: 12
  }
}

const SIZE = SIZES[12]

const fetchLarge = (x) => fetch(x, SIZE.fetch)

// the last number can be anything.
// MODIFIED THIS
const buildLarge = (x, o) => fetchLarge((fetchLarge(x) + o) % SIZE.modulo ^ SIZE.xor)
// )
function createArray(n, fn) {
  if (!n) return [0]
  let arr = []
  let i = 0
  while (n) {
    let mod = fn(i++)
    arr.push(Number(n % mod))
    n /= mod
  }
  return arr
}

let i = 1n
let matched = {}
let matchedI = 1
const write = () => {
  let maxSize = SIZE.max
  const x = buildLarge(i++, SIZE.j)
  let chunks = createArray(x, i => i % 2 === 0 ? 32n : 16n).map((x, i) => {
    if (i % 2 === 0) {
      return startParts[x]
    } else {
      return endParts[x]
    }
  }).join('')
  if (chunks.length < (maxSize - 2)) {
    chunks = `mimi${chunks}`
  } else if (chunks.length < (maxSize)) {
    chunks = `mi${chunks}`
  }
  if (chunks.match(pattern)) return write()
  if (matched[chunks]) throw new Error(chunks + ' ' + Object.keys(matched).length + ' ' + matched[chunks])
  matched[chunks] = matchedI++
  const chunked = chunk(chunks.split(''), 4).map(x => x.join('')).join(':')
  return chunked
}

const map = fs.readFileSync('tmp/taxon.txt', 'utf-8')
  .trim()
  .split(/n+/)
  .map(x => x.split(/t+/)[3])
  .reduce((m, x) => {
    let p = x.trim().split(/s+/).join(' ')
    if (p.match(/d/)) return m
    m[p.toLowerCase()] = true
    return m
  }, {})

const list = chunk(Object.keys(map).map(key => `${write()},${key}`).sort(), 5000)

list.forEach((l, i) => {
  fs.writeFileSync(`tmp/taxon/${i + 1}.csv`, l.join('n'))
})
fs.writeFileSync('tmp/code.csv', String(i))

function chunk (arr, len) {

  var chunks = [],
      i = 0,
      n = arr.length;

  while (i < n) {
    chunks.push(arr.slice(i, i += len));
  }

  return chunks;
}

The taxon.txt looks like this (I greatly truncated the taxon file).

It is throwing this duplicate error:

$ node tmp/taxon2
/Users/me/tmp/taxon2.js:135
  if (matched[chunks]) throw new Error(chunks + ' ' + Object.keys(matched).length + ' ' + matched[chunks])
                      ^

Error: mikukenekeku 56542 7490
    at write (/Users/me/tmp/taxon2.js:135:30)
    at /Users/me/tmp/taxon2.js:152:51
    at Array.map (<anonymous>)
    at Object.<anonymous> (/Users/me/tmp/taxon2.js:152:37)
    at Module._compile (node:internal/modules/cjs/loader:1095:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1124:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:816:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at node:internal/main/run_main_module:17:47

Why is it running into duplicates?

If I comment out these lines, it passes however:

  if (chunks.length < (maxSize - 2)) {
    chunks = `mimi${chunks}`
  } else if (chunks.length < (maxSize)) {
    chunks = `mi${chunks}`
  }

But, there is an error in that case too: the text of some of the lines/strings is not long enough. I basically tried padding it with the zero element, but for some reason it’s erroring now, any ideas?

Inside the write function I fetch the next pseudo-random number from the fancy mathematical sequencer at const x = buildLarge(i++, SIZE.j). Then I do createArray(x, i => i % 2 === 0 ? 32n : 16n) which either divides by 32 on even index or 16 on odd index, so the value can be fetched from the startParts or endParts arrays respectively.

I tried doing .reverse() after createArray, but that doesn’t seem to help.

I think it just has something to do with the padding but not sure yet.

Fetching data from JSON file returning nothing

I am building a solar system app and I want to have all of my planet’s info in a JSON file for easy access. The JSON file is in the following format

Planet-info.json, in the public folder of my React app

  "planets": [
        {
            "Name": "Mercury",
            "Description": "The smallest planet in our solar system and closest to the Sun—is only slightly larger than Earth's Moon. Mercury is the fastest planet, zipping around the Sun every 88 Earth days.",
            "Moons": 0,
            "Habititable": "false"
        },
        {
            "Name": "Venus",
            "Description": "is hot",
            "Moons": 0,
            "Habititable": "false"
        }
    ]

And I am fetching the data with the useEffect hook

 const [planetData, setPlanetData] = useState();
  useEffect(() => {
    const fetchData = () => {
      fetch("/planet-info.json").then((result) => {
        setPlanetData(result);
      });
    };
    fetchData();
    console.log(`planet data is ${planetData}`);
  }, []);

However when this code runs and the console.log statement runs it returns the line
planet data is
It does not say undefined, or even [Object object] it is simply blank and I am unable to troubleshoot from there.

Javascript Phaser3 Assets Not Loading In Create Function

I’m trying to do what seems to be basic image loading into my phaser3 game outside Phaser’s preload function, but nothing is working.

I tried:

  • Lazy loading function in my utils.js:
dynImgLoader(textureKey,x,y,asset)
{
    let loader = new Phaser.Loader.LoaderPlugin(this.scene);
    loader.image(textureKey,asset);
    loader.once(Phaser.Loader.Events.COMPLETE, ()=>
    {
        console.log('sprite ready for usage');
    })
    loader.start();
}

When called it still gives me the default phaser asset image (not loaded)

  • I tried what this tutorial told me in index.js in create function:
    this.load.image('arc_red', arc_red);
    this.load.onLoadComplete.add(this);
    this.load.start();

Still does not work.

Question:

How do I “dynamically” load assets for a multiplayer web socket game without using the preload function? And why is it that I am doing wrong?

I’m new to phaser and I desperately need to learn, thanks.

Revert button text if error message is triggered

Why won’t this code revert the button text back to Place Order if an error message is triggered?

The text was changed upon clicking the button, which works fine.
But it should change back if an error message occurs upon clicking the button.
There are no console messages for the error.
This is a Stripe payment button, it’s Woocommerce.

        add_action( 'wp_footer', 'custom_checkout_jquery_script' );
        function custom_checkout_jquery_script() {
          if ( is_checkout() && ! is_wc_endpoint_url() ) :
        ?>
          <script type="text/javascript">
          jQuery( function($){
              jQuery('form.checkout').on('submit', function(event) {
                jQuery('button#place_order').text('Please Wait');
                event.preventDefault();
              });
          });
    
         //To detect woocommerce error trigger JS event
          jQuery( document.body ).on( 'checkout_error', function(){
                    var wooError = $('.woocommerce-error');
                    jQuery('button#place_order').text('Place Order');
            } );

</script>
 <?php
  endif;
}

Slider value isn’t increasing on site, looked through HTML/CSS/JS and can’t figure it out [duplicate]

This is the code i have been using. Am i missing something obvious here? The slider itself works, and so does the amount when you hit the button to continue, but the actual value does not increase. Example, if i slide it to the end it stays at (1) instead of (5)

 <!-- Start of Slider Code -->
    <div class="slidercontainerdiv">
            <span id="rangeValue">1</span>
            <Input id="amount" type="range" value="1" min="1" max="5" onChange="rangeSlide(this.value)" onmousemove="rangeSlide(this.value)">
            
    </div>
    
    
      <script>
             type="text/javascript">
             function rangeSlide(value) {
                document.getElementById('rangeValue').innerHTML = value;
              }
         </script>
         
    <!-- End of Slider HTML/JSCode --> 
    
    
    <!-- Start of Slider CSS -->
      <style> 
      
      .slidercontainerdiv {
        width:25%;
      }
      
      
        #rangeValue {
        width: auto%;
        display: block;
        text-align: center;
        font-size: 25px;
        color: white;
        font-weight: 100;
        
      }
      .range {
        width: 25%;
        height: 15px;
        -webkit-appearance: none;
        background: white;
        outline: none;
        border-radius: 15px;
        overflow: hidden;
        box-shadow: inset 0 0 5px white;
      }
      .range::-webkit-slider-thumb {
        -webkit-appearance: none;
        width: 15px;
        height: 15px;
        border-radius: 50%;
        background: white;
        cursor: pointer;
        border: 1px solid blue;
        box-shadow: -407px 0 0 400px white;
      }
    </style>
    <!-- End of Slider CSS -->

Selecting a element by it’s css selector

I’m trying to select an image element using its style selector. I wrote the line of code in Python but I’m having problems translating it to JavaScript. Here’s my attempt so far.

if driver.find_element_by_css_selector("img[style='object-fit: cover;']") is not None:
        download_url = driver.find_element_by_css_selector("img[style='object-fit: cover;']").get_attribute('src')

And here is my js attempt.

let imageArr = []

for(let post of posts) {
    await page.goto(post)
    await page.waitForTimeout(6000)

    if (await page.type("img[style='object-fit: cover;']") !== null) {

        const image = await page.evaluate(() => {
            document.querySelectorAll("img[style='object-fit: cover;']").forEach(img => {
                let imageUrl = img.getAttribute('src');
                imageArr.push(imageUrl)
            })
        })
    }
}

Disable OPTIONS request before POST in React

I have a React application based on Typescript which is hosted on my PC.
I use Spring gateway to forward requests to another microservice. GET requests are working fine but for POST requests I get:

Access to XMLHttpRequest at 'http://1.1.1.1:8080/api/support/tickets/create' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I’m hitting this Spring Cloud Gateway issue: https://github.com/spring-cloud/spring-cloud-gateway/issues/229

Spring cloud configuration:

@Bean
public RouteLocator routes(RouteLocatorBuilder builder, LoggingGatewayFilterFactory loggingFactory) {

    return builder.routes()
            .route("route_id",
                    route -> route
                            .path("/api/support/tickets/**")
                            .filters(f -> f.rewritePath("/api/support/tickets/(?<RID>.*)", "/support/tickets/${RID}"))
                            .uri("lb://merchant-hub-admin-service")
            )
            .build();
}

React code:

export async function getTicket(id: string) {
  return await axios.get(`${baseUrl}/support/tickets/ticket/${id}`);
}

export async function postTicket(
    data: TicketFullDTO
): Promise<AxiosResponse<TicketFullDTO>> {
  return await axios.post<TicketFullDTO>(
      `${baseUrl}/support/tickets/create`, data);
}

Do you know how I can disable OPTIONS request before POST and DELETE requests?