Adding a cell value to another cell then deleting the original cell value

I have sheet that i’m using to track servicings on a machine.

I want to have a cell that I can put in hours the machine was used for. That value would then be added to another cell tracking total hours used and subtracted from another cell tracking when the next service is due. Finally I want the original cell to be deleted.

In the picture below I would enter hours used in cell D2. This value would be added to cell B2 and subtracted from cell C2 before clearing itself.

simplified Example of spreadsheet

Hope someone can help, many thanks.

I’ve tried adapting scripts i’ve seen on here, but I have almost no coding skill so have had no success

Remove product and update checkout trigger continuously loading with Ajax at WooCommerce checkout

I am attempting to integrate a product removal feature along with triggering the checkout update for my WooCommerce setup. However, upon clicking the ‘remove’ option, the process seems to be stuck in a loading state. How can I ensure that the remove function and the checkout update trigger work seamlessly together using Ajax?

add_action('woocommerce_checkout_cart_item_quantity', 'add_remove_product_link', 20, 3);

function add_remove_product_link($product_quantity, $cart_item, $cart_item_key) {
    $product_id = apply_filters('woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key);

    // Output existing quantity input
    echo $product_quantity;

    // Output Remove Product link with JavaScript click event
    echo '<br><a href="#" class="remove-product" data-product-key="' . $cart_item_key . '">Remove</a>';

    // Add JavaScript for handling the removal and updating the checkout
    ?>
    <script type="text/javascript">
        jQuery(function ($) {
            $('.remove-product[data-product-key="<?php echo $cart_item_key; ?>"]').on('click', function (e) {
                e.preventDefault();

                var productKey = $(this).data('product-key');

                $.ajax({
                    type: 'POST',
                    url: wc_checkout_params.ajax_url,
                    data: {
                        action: 'remove_product_and_update_checkout',
                        cart_item_key: productKey,
                        security: wc_checkout_params.update_order_review_nonce,
                    },
                    success: function (response) {
                        // Update the checkout section without reloading the page
                        $(document.body).trigger('update_checkout');
                    },
                });
            });
        });
    </script>
    <?php
}

// AJAX action to remove product from checkout and update checkout
add_action('wp_ajax_remove_product_and_update_checkout', 'remove_product_and_update_checkout');

function remove_product_and_update_checkout() {
    if (isset($_POST['cart_item_key'])) {
        WC()->cart->remove_cart_item(sanitize_text_field(wp_unslash($_POST['cart_item_key'])));
        WC()->cart->calculate_totals();
        wc_print_notices(); // Include this line to display notices if any

        // Output the updated cart totals and checkout section
        echo json_encode(array(
            'result' => 'success',
            'cart_totals' => WC()->cart->get_totals(),
            'html' => WC()->cart->cart_contents_count,
        ));
        die();
    }
}

Why won’t my code work? No issues found when troubleshooting [closed]

This is my Javascript code, but the memory game is not working correctly. What am I doing wrong?

// array that holds all elements with class "card"
var cards = document.getElementsByClassName("card");

// deck of all cards in game
const deck = document.getElementById('card-deck');

// the number of moves made
var move = 0;

// variable "counter" that will hold the element with class "moves"
var counter = document.querySelector("span.moves");

// declaring variable of matchedCards
let matchedCard = document.getElementsByClassName('match');

// variable "openedCards" as an empty array
var openedCards = [];

// a number value for seconds/minutes elapsed
var startTime = new Date();
var second = 0;
var minute = 0;

// variable "timer" that will hold the element with class "timer"
var timer = document.querySelector("div.timer");

// Use this variable for assigning the setInterval()
var interval;

// @description shuffles cards
// @param {array}
// @returns shuffledarray
function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;

    while (currentIndex !== 0) {
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;
        temporaryValue = array[ currentIndex ];
        array[ currentIndex ] = array[ randomIndex ];
        array[ randomIndex ] = temporaryValue;
    }
    return array;
};

// @description reset/initialize the game when page is refreshed / loads
document.body.onload = startGame();

// @description function to start a new play
function startGame() {
    // empty the openCards array
    openedCards = [];
    // shuffle deck
    cards = shuffle(cards);
    // Resets "deck" innerHTML
    deck.innerHTML = '';
    for (var i = 0; i < cards.length; i++) {
        const card = cards[i];
        // Appends each "card" (from cards array) to the "deck" element
        deck.appendChild(card);
        
        // removes dynamic classes from cardre
        card.classList.remove('show', 'open', 'match', 'disabled');
    }

// Resets the moves counter and value displayed in HTML
// Resets the timer counter variables: second, minute
// Sets the innerHTML for the "timer" element to display starting time
// Stops the "interval" timer
    function reset () {
        move = 0;
        counter.innerHTML = move;
        clearInterval(interval);
        second = 0;
        minute = 0;
        timer.innerHTML = '0 mins 0 secs';
    }
}

// @description toggles open and show class to display cards
var displayCard = function () {
    this.classList.toggle('open');
    this.classList.toggle('show');
    this.classList.toggle('disabled');
}

// @description add opened cards to OpenedCards list and check if cards are match or not
function cardOpen() {
    const selectedCard = this;
    // Appends "selectedCard" to the "openedCards" array
    openedCards.push(selectedCard);
    // Adds conditional to check if 2 cards are "open"
    if (openedCards.length == 2) {
        // Increments the number of "moves" and start the "timer" if it was the first move
        startTimer();
        move ++;
    // Calls matched() or unmatched() depending on whether both cards have the same "type" attribute
        if (openedCards[0].getAttribute('type') === openedCards[1].getAttribute('type')) {
        matched();
    }  
    else {
        unmatched();
    }
    }
}

// @description when cards match
function matched() {
    openedCards[0].classList.add('match', 'disabled');
    openedCards[1].classList.add('match', 'disabled');
    openedCards[0].classList.remove('show', 'open', 'no-event');
    openedCards[1].classList.remove('show', 'open', 'no-event');
    openedCards = [];
}

// description when cards don't match
function unmatched() {
    openedCards[0].classList.add('unmatched');
    openedCards[1].classList.add('unmatched');
    disable();
    setTimeout(function() {
        openedCards[0].classList.remove('show', 'open', 'no-event', 'unmatched');
        openedCards[1].classList.remove('show', 'open', 'no-event', 'unmatched');
        enable();
        openedCards = [];
    }, 1100);
}

// @description disable cards temporarily
function disable() {
    Array.prototype.filter.call(cards, function (card) {
        card.classList.add('disabled');
    });
}

// @description enable cards and disable matched cards
function enable() {
    Array.prototype.filter.call(cards, function (card) {
        card.classList.remove('disabled');
        for (var i = 0; i < matchedCard.length; i++) {
            matchedCard[i].classList.add('disabled');
        }
    });
}

// @description game timer
function startTimer() {
    interval = setInterval(function () {
        timer.innerHTML = minute + ' mins ' + second + ' secs';
        second++;
        if (second == 60) {
            minute++;
            second = 0;
        }
        if (minute == 60) {
            hour++;
            minute = 0;
        }
    }, 1000);
}

// @description congratulations when all cards match, show details
function congratulations() {
    if (matchedCard.length == 16) {
        // Stop the "interval" timer
        clearInterval(interval);
        document.querySelector('.popup').classList.add('show');
        // Updates HTML for element with id "finalMove" to show "moves" value
        document.getElementById('finalMove').innerHTML = move;
        // Updates HTML for element with id "totalTime" to show innerHTML from "timer" element
        document.getElementById('totalTime').innerHTML = timer.innerHTML;
    };
}

// @desciption for user to play Again
function playAgain() {
    // call the existing "startGame()" method to start a new game
    startGame();
}

// loop to add event listeners to each card
for (var i = 0; i < cards.length; i++) {
    const card = cards[i];
    // Add 'click' event listener to call existing "displayCard" method
    card.addEventListener('click', displayCard);
    card.addEventListener('click', cardOpen);
    card.addEventListener('click', congratulations);
};
`

I’ve tried using the developer tools, a validation site, and even chatgpt. Everything says my code is correct, but its obviously not if it’s not working. I was provided the HTML so I don’t think that’s the issue.

It’s not possible to read the Y property of the context element from a Chart.js BoxAnnotation

I’m new to using Chart.js and I’ve done a lot of research, but haven’t found anything that could help me, so I’m reaching out to the community for assistance.

I’m working on a project using Chart.js version 3.2.1 and chartjs-plugin-annotation version 1.0.1. Unfortunately, updating the libraries is not possible at the moment.

Here’s the scenario: I need to fill the background of a BoxAnnotation plugin with a gradient. Okay, I’ve figured out how to do that. The challenge is that this BoxAnnotation varies in location based on the user-applied filter. Therefore, the Y coordinate of the createLinearGradient needs to be obtained from the BoxAnnotation at runtime.

Now the problem is that I can’t read the Y property of the context element. It always returns undefined. Consequently, I can’t correctly set where the gradient should start.

Here’s the code for the BoxAnnotation:

              boxDeficitStatus: !this.onlyVirtualSensors && {
                type: 'box',
                yScaleID: 'right-y-axis',
                drawTime: 'beforeDatasetsDraw',
                yMin: 0,
                yMax: $this.moistureCritical,
                backgroundColor: function(context) {
                  const chart = context.chart;
                  const {ctx, chartArea} = chart;
          
                  return getGradient(ctx, chartArea);
                },
                borderWidth: 0,
                display: !this.onlyVirtualSensors,
              }

And here’s the code for the getGradient function:

function getGradient(ctx, chartArea) {
  const chartHeight = chartArea.bottom - chartArea.top;

  //Instead of 246, the Y coordinate value I'm trying to obtain should go there.
  const gradient = ctx.createLinearGradient(67.7, 246, 67.7, chartHeight);
  gradient.addColorStop(0, "rgba(255, 255, 255, 0.3)");
  gradient.addColorStop(1, "rgba(255, 0, 0, 0.3)");
  
  return gradient;
}

When running a console.log('$context', context.element['$context'])

The result in the browser terminal is as shown in the image you provided:

enter image description here

However, when trying to access the Y property using any of the following:

console.log('y', context.element['$context']['element'].y)
console.log('y', context.element.y)
console.log('y', context.element['y'])

The result is always undefined.

My question then is whether it’s possible to access this Y property somehow or if there’s another way to obtain the coordinate I need.

You’re welcome! I appreciate your patience in advance!

Updating objects from multiple documents when element matches but push when there is no match in MongoDB

I have these 2 documents. I need to update the “booksBought” arrays of the 2 documents at the same time with updateMany / update of MongoDB.

Here’s the scenario:
My query as of now is I select both users Josh and Carl with $in, then increment the quantity of a specific booktitle, in this example “harry potter”. I filter the object using the [$] identifier and the arrayFilter condition to select the object. However, the other user isn’t included in the filter since he doesn’t have an object with “harry potter” in it. How do I push it on the other user’s “booksBought” array if the object doesn’t exist although the user is part of the selection under $in?

Query

db.collection.update({
  "userId": {
    $in: [
      "10000001",
      "10000002"
    ]
  }
},
{
  $inc: {
    "booksBought.$[elem].quantity": 10
  }
},
{
  arrayFilters: [
    {
      "elem.booktitle": "harry potter"
    }
  ]
})

Document

[
  {
    "userId": "10000001",
    "name": "Josh",
    "booksBought": [
      {
        "booktitle": "harry potter",
        "quantity": 1
      },
      {
        "booktitle": "game of thrones",
        "quantity": 2
      }
    ]
  },
  {
    "userId": "10000002",
    "name": "Carl",
    "booksBought": [
      {
        "booktitle": "lord of the rings",
        "quantity": 4
      }
    ]
  }
]

Playground link: https://mongoplayground.net/p/Aby5lhRckJT

Kalman filter with remote touchpad

I’ve created a simple Python HTTP + WS server for a remote touchpad control app. The server allows users to control the mouse on their PC by interacting with a <div /> acting as a touchpad on their mobile phones. It sends touchmove events to the server, which then moves the actual mouse using the deltaX and deltaY values.

However, I’m facing an issue where, during the initial touchpad movement, there’s noticeable jitter or lag in the mouse, almost like some noise. Once the user continues to move their finger on the touchpad, everything works smoothly.

To address this, I’m considering implementing a Kalman filter to reduce noise and improve the initial mouse movement. I would appreciate any guidance or code examples on how to integrate a Kalman filter into my existing Python server for this purpose.

Additionally, even after the user has been moving for a while and everything is relatively smooth, there is still a notable sensitivity issue. Even a slight movement of the top of the finger results in significant mouse movement. Are there strategies or adjustments I can make to fine-tune the sensitivity?

I’m also interested in optimizing the data transfer since my end goal is to implement this over Bluetooth Low Energy, which has a smaller bandwidth compared to WiFi. Is there a way to reduce the rate and amount of data being sent without compromising the user experience?

Any insights, code snippets, or resources related to implementing a Kalman filter for mouse movement and optimizing data transfer in a Python server for a touchpad control app would be greatly appreciated.

main.py

from flask import Flask, render_template # pip install Flask
from flask_socketio import SocketIO # pip install flask_socketio
import autopy # pip install autopy. python3.8 recommended for precompiled wheel
import logging
import socket
import time


logging.basicConfig(level=logging.INFO)
app = Flask(__name__, template_folder='./')
socketio = SocketIO(app)

@app.get('/')
def index():
    return render_template('index.html')


@socketio.on('message')
def handle_message(data):
    # delta x, delta y
    dx, dy = data['dx'], data['dy'] 
    print(dx, dy)
    
    # Move actual mouse
    x, y = autopy.mouse.location()
    autopy.mouse.move(x + dx, y + dy)
    

if __name__ == '__main__':
    host_ip = socket.gethostbyname(socket.gethostname())
    socketio.run(app, port=8000, host="0.0.0.0")

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      html,body {
        overflow: hidden; width: 100vw; height: 100vh; margin: 0; padding: 0; box-sizing: border-box;
      }
      body {
        display: flex; justify-content: center; align-items: center; width: 100vw; height: 100vh;
      }
      .touchpad {
        width: 80vw; height: 65vh; background: rgb(92, 92, 92); border-radius: 25px;
      }
    </style>
  </head>
  <body>
    <div class="touchpad"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js" integrity="sha512-q/dWJ3kcmjBLU4Qc47E4A9kTB4m3wuTY7vkFJDTZKjTs8jhyGQnaUrxa0Ytd0ssMZhbNua9hE+E7Qv1j+DyZwA==" crossorigin="anonymous"></script>
    <script type="text/javascript" charset="utf-8">
      const touchpad = document.querySelector(".touchpad");
      const socket = io();
      
      const deltaScale = 1.8
      let previousTouch = null;
      function onTouchMove(event) {
        const { clientX, clientY } = event.touches[0];
        // claculate delta X and delta Y
        if (previousTouch) {
          const deltaX = clientX - previousTouch.clientX;
          const deltaY = clientY - previousTouch.clientY;
          if ((deltaX !== 0 || deltaY !== 0)) { // don't send if both zeros
            // send mouse move event
            socket.send({dx: deltaX * deltaScale, dy: deltaY * deltaScale})
          }
          console.log(deltaX, deltaY);
        }
        // Update the previous touch position for the next event
        previousTouch = { clientX, clientY };
      }
      socket.on("connect", () => touchpad.addEventListener("touchmove", onTouchMove))
    </script>
  </body>
</html>

javascript – Chart.js change x unit to add Data

First time using chart.js.
There are many good features, but we are having difficulty with the contents below.

            chart = new Chart(ctx, {
                type   : 'line',
                data   : {
                    labels  : category,
                    datasets: [
                        {
                            label: "data1",
                            data : data1
                        },
                        {
                            label: "data2",
                            data : data2
                        },
                        {
                            label: "data3",
                            data : data3
                        }
                    ]
                },
                options: {
                    scales: {
                        x: {
                            type: 'time',
                            time: {
                                unit          : 'hour',
                                displayFormats: {
                                    second: 'HH:mm:ss',
                                    minute: 'HH:mm',
                                    hour  : 'HH'
                                }
                            }
                        }
                    }
                }
            });
            
            
    function addChartData(label, newData) {
        chart.data.labels.push(label);
        chart.data.datasets.forEach((dataset) => {
            Object.keys(newData).forEach(type => {
                if (type === dataset.label) {
                    dataset.data.push(newData[type]);
                }
            });
        });

        if(chart.data.datasets[0].data.length > 24){
            chart.data.labels.shift();
            chart.data.datasets.forEach((dataset) => {
                dataset.data.shift();
            });
        }
       
        chart.update();
    }

I want to leave the existing x data as ‘hour’ and change it to ‘second’ only for the added data.
I tried this code but this was a code that changed the unit of the whole x.

 chart.options.scales.x.time.unit = 'second';
//or
chart.options.scales.xAxes[0].time.unit = 'second';

please help me

Setting an attribute of the Next.js response object

The question involves setting an attribute on the response object inside a Next.js API handler and also accessing that attribute later between requests. I didn’t realize this was possible, and I couldn’t find anything in the documentation or by searching online.

I’m looking at implementing Socket.io in a Next.js environment and I came across this question on StackOverflow. Here is the code snippet in question:

import { Server } from "socket.io";

export default function SocketHandler(req, res) {
    if (res.socket.server.io) {
        console.log("Already set up");
        res.end();
        return;
    }
    const io = new Server(res.socket.server);
    ...
    res.socket.server.io = io;
    res.end();
}

As you can see the handler is checking for the existence of res.socket.server.io, which if found suggests that the socket is already set up. Later it sets res.socket.server.io to equal the newly created Server instance.

So do attributes on the res object get preserved between requests? And if so, what are the requirements for them to be preserved? Like I assume that it’s per client.

File in Vite Build Manifest disappears after one page load. (Unable to locate file in Vite manifest)

So, this is a rather interesting situation I am facing.

Everything works great locally (“npm run dev“) but, after running build (“npm run build“) on my production server, ONE specific file is misbehaving. The project contains hundreds of other vue components, but this one in specific is where I am having the following issue…

I can initially access the route where the inertia file is used (it has a unique route parameter that binds to a database row.) The route works ONCE, and once only. Subsequent attempts to load the page result in a 500 Server Error:

Unable to locate file in Vite manifest: resources/js/Pages/FileNameHere.vue

I will reiterate, that FileNameHere.vue works the FIRST TIME that I load the route (“/viewfilename/1”). If I have another database model, it will work the first time (“/viewfilename/2”). No matter, every attempt afterwards STOPS working and results in the above here that it is not in the Vite manifest.

I also took a look at the manifest.json file. Under the dynamicImports key, the vue component file is not listed correctly:

"_FileNameHere.2b295b07.js",

All other files are listed correctly:

"resources/js/Pages/Documents/ViewAndSignV3.vue",
"resources/js/Pages/Documents/ViewAndSignV4.vue",
"resources/js/Pages/Documents/ViewAndSignV45.vue",
"resources/js/Pages/Documents/ViewAndSignV5.vue",

I can’t make sense of this. Can anyone shed light on this issue? Any help is greatly appreciated.

Custom Grommet TextArea not changing rows prop on initial input

I have created the a custom Grommet TextArea component, with the idea of it having the ability to change its rows prop based on the input. In the current usage it is also autopopulated on form load.

The first time around it was working inside the parent form with the expected behavior, however once it was exported it would not change the rows property in on the initial input population, only if the input is changed afterwards.

I can see that the rows property is calculated correctly on the initial load as well, however it would not change the height of the TextArea.

The exported custom component:

import React, { useState } from 'react'
import PropTypes from 'prop-types'

import { FormField, TextArea } from 'grommet'

export const TextAreaExpandable = ({
  name,
  onChange,
  minRows,
  maxRows,
  ...rest
}) => {
  const calculateRowCount = value => {
    const valueRowsCount = (value.match(/n/g) || '').length + 1
    return valueRowsCount < minRows
      ? minRows
      : valueRowsCount > maxRows
        ? maxRows
        : valueRowsCount
  }

  const initRowCount = calculateRowCount(rest.value) // TODO: does not change row count when initialized with value
  const [rows, setRows] = useState(initRowCount)

  const changeRowCount = value => setRows(calculateRowCount(value))

  const onChangeHandler = (e) => {
    const { target: { value } } = e
    changeRowCount(value)
    onChange && onChange(e)
  }

  return (
    <FormField
      style={{ display: 'flex' }}
      plain
      resize='vertical'
      margin={{ horizontal: 'xxsmall' }}
      name={name}
      label={name}
      onChange={onChangeHandler}
      component={TextArea}
      rows={rows}
      {...rest}
    />
  )
}

TextAreaExpandable.propTypes = {
  name: PropTypes.string.isRequired,
  onChange: PropTypes.func,
  minRows: PropTypes.number,
  maxRows: PropTypes.number
}

TextAreaExpandable.defaultProps = {
  required: true,
  onChange: undefined,
  minRows: 2,
  maxRows: 10
}

The usage in the form:

<TextAreaExpandable
  name={name}
  placeholder={placeholder}
  value={value}
  onChange={onChange}
/>

Restrict CloudFront signed URL usage to a specific HTTP method

I have an S3 bucket that can only be accessed via a CloudFront distribution. Some users should be able to upload certain files to the S3 bucket, and other users should be able to download certain files from the S3 bucket (all via CloudFront).

I’m using pre-signed CloudFront URLs with a custom policy in my API to control the access. But, I need to specify in the policy whether the signed URL is valid for download (GET) or upload (PUT).

I had hoped there would be a key in the policy statement that would control which HTTP method the URL can be used for, but I haven’t had any luck finding that. Here’s an example policy statement from the documentation:

{
    "Statement": [
        {
            "Resource": "https://d111111abcdef8.cloudfront.net/game_download.zip",
            "Condition": {
                "IpAddress": {
                    "AWS:SourceIp": "192.0.2.0/24"
                },
                "DateLessThan": {
                    "AWS:EpochTime": 1675159200
                }
            }
        }
    ]
}

Does anyone know how I might specify the HTTP method in the policy? If not, I would also love other out-of-the-box ideas of how to accomplish this goal! I know it can be done when signing S3 URLs, but I would prefer to go through CloudFront since these files will be downloaded frequently.

how to build a modal / full screen component that will always be fixed relative to the viewport?

I have a custom modal / full screen react component that uses position: fixed to ensure that it always take up the full screen.

However, this component will break if one of its ancestor components has a css property that breaks the position: fixed. For example a transform, etc.

How do I build modal / full screen component that is guaranteed to always be position: fixed relative to the viewport regardless of any ancestor component?

Fix a row while sorting in ag grid react

There is a dropdown and based on the values of the dropdown I am sorting the ag grid here but I want to fix a row at top when doing sorting with id 956306 how can I achieve it ??

const handleApplyQuickSort = (selectedSort: string) => {
    const colId = SORT_MAP[selectedSort];
    if (colId && gridRef.current) {
      gridRef.current?.columnApi?.applyColumnState({
        state        : [{ colId: colId, sort: 'desc' }],
        defaultState : { sort: null },
      });
      initialSortAppliedRef.current = true;
      const rowIndexToKeepOnTop = gridRef?.current?.props?.rowData?.findIndex((row:UIModel) => String(row.id) === '956306');
      if (rowIndexToKeepOnTop !== -1 && rowIndexToKeepOnTop) {
        const rowToKeepOnTop = gridRef?.current?.props?.rowData?.splice(rowIndexToKeepOnTop, 1)[0];
        gridRef?.current?.props?.rowData?.unshift(rowToKeepOnTop);
      }    
    }
  };

Seeking Advice on Customization Process for Image and Video Templates in React App

I’m working on a React web application and would love to hear your recommendations on how to implement the customization process for image and video templates by filling out a form.

Have any of you successfully implemented customization features for videos or images in your projects? What approaches or libraries do you suggest to achieve a smooth and engaging user experience?

I appreciate any advice or experiences you can share. Thanks in advance!

I tried with the remotion library but I feel it is very slow and difficult to program what I require.