useAnimatedValue is not a function

I’m working on a small React Native project and I’m using the animated api for the first time. I’m attempting to make a small animated View that is pretty similar to the example given in their Docs. The issue I’m running into though is that when trying to run the project, I get this error:

TypeError: (0 , _index.useAnimatedValue) is not a function

I’m not sure what is happening, the component looks identical to what is being used in the example Docs

Here is the component:

import { Animated, useAnimatedValue } from "react-native";


const CookingView = (props) => {
  
  const cookAnim = useAnimatedValue(0);

  useEffect(() => {
    Animated.timing(cookAnim, {
      toValue: 1,
      duration: 10000,
      useNativeDriver: true,
    }).start();
  },[cookAnim]);

  return (
    <Animated.View 
      style={{
        ...props.style,
        opacity: cookAnim
      }}
    >
      { props.children }
    </Animated.View>
  );
}

export default CookingView;

Any ideas on to what is going on would be helpful. Thanks!

How to change MUI-X default Datagrid scrollbar styles?

I’m using MUI-X datagrid in my application. The default scrollbar looks bad and I don’t see any way to customize it. I saw a few threads in github and tried the code below but that doesn’t seem to work. Is there any fix for this at all?

sx={{
  '& .MuiDataGrid-virtualScroller::-webkit-scrollbar': {
    width: '0.4em',
  },
  '& .MuiDataGrid-virtualScroller::-webkit-scrollbar-track': {
    background: '#f1f1f1',
  },
  '& .MuiDataGrid-virtualScroller::-webkit-scrollbar-thumb': {
    background: '#6BADCE',
    background: '-webkit-linear-gradient(to bottom, #6BADCE, #d7dde8)',  
    background: 'linear-gradient(to bottom, #6BADCE, #d7dde8)',
    borderRadius:'10px',
  },
  '& .MuiDataGrid-virtualScroller::-webkit-scrollbar-thumb:hover': {
    background: '#555',
  },
}}

How to disable gyroscope window prompt aframe

Every time the page loads on mobile a window prompting the user to allow or deny gyroscope access appears (window). My website doesn’t need gyroscope so I turned “look-controls=”magicWindowTrackingEnabled: false;” ” and while it did fully disable the gyroscope, the dreaded window still pops up. On a page on which there is one aframe I got away with writing an extra bit of javascript which clicks the Deny button as soon as it loads, therefore the window doesn’t even have time to pop up and eveything looks fine, but on a different page with more aframes, this method failed, with it only clicking the first “Deny” button no matter what i tried. I haven’t found anything that helped on the internet and this is my first Stackoverflow question. Thanks!

P.S. I am using aframe 1.7.0 if that helps at all

Can’t find JavaScript method in generated TypeScript file

When I am submitted a form, one of my Javascript methods is showing as undefined.

I have a form I am using that is defined like this:

// Index.cshtml

<script src="~/js/compiled/site.js" asp-append-version="true"></script>
<script src="~/js/compiled/errors.js" asp-append-version="true"></script>

<form id="f1" method="post" data-ajax="true" data-ajax-method="post" data-ajax-complete="formSubmitted" onsubmit="formSubmitting();">
    <button class="btn btn-primary" type="submit" id="btnSubmit">
        <span>Click here!!!</span>
    </button>
</form>

The methods formSubmitting() and formSubmitted are defined in a TypeScript file:

// Javascript/site.ts

import { hideErrorMessage } from './errors';

export function formSubmitted(result: object): void {
    console.log("This gets hit");
    hideErrorMessage();
    console.log("This does not get hit");
}

export function formSubmitting(): void {
    console.log("hitting form submitting");
}

As you can see above, there isn’t much happening in formSubmitting() – it is just outputting to the log letting us know if finds this function, which it does.

The function formSubmitted is referencing another function called hideErrorMessage which is defined in the TypeScript file errors.ts:

// Javascript/errors.ts

export function hideErrorMessage(): void {
    console.log("Is this ever hit? The answer is no...");
}

The function hideErrorMessage() never gets hit, and instead produces this error in the logs:

Uncaught TypeError: Cannot read properties of undefined (reading 'hideErrorMessage')
    at HTMLFormElement.formSubmitted (site.ts:5:5)
    at Object.complete (jquery.unobtrusive-ajax.js:101:92)
    at fire (jquery.js:3223:31)
    at Object.fireWith (jquery.js:3353:7)
    at done (jquery.js:9642:21)
    at XMLHttpRequest.<anonymous> (jquery.js:9888:9)

I have my tsconfig.json set to compile the ts files here:

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",
    "outDir": "wwwroot/js/compiled",
    "moduleResolution": "node",
    "allowUnreachableCode": false,
    "alwaysStrict": true,
    "esModuleInterop": true,
    "types": [ "jquery" ]
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

And that appears to be working, because it compiles the files the way I would expect:

// wwwroot/js/compiled/site.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formSubmitted = formSubmitted;
exports.formSubmitting = formSubmitting;
var errors_1 = require("./errors");
function formSubmitted(result) {
    console.log("This gets hit");
    (0, errors_1.hideErrorMessage)();
    console.log("This does not get hit");
}
function formSubmitting() {
    console.log("hitting form submitting");
}
//# sourceMappingURL=site.js.map
// wwwroot/js/compiled/errors.js

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.hideErrorMessage = hideErrorMessage;
function hideErrorMessage() {
    console.log("Is this ever hit? The answer is no...");
}
//# sourceMappingURL=errors.js.map

So looking at the compiled output, hideErrorMessage() exists. So I don’t understand why it is showing as undefined?

I set up an example in GitHub if that is helpful.

Use the return value of a function for future evaluations [closed]

The table below is pulled from a database.
When I change the contents of a cell, I can see the result in the browser.
However, I can’t access the value of $newvalue outside the function, which prevents me from doing all my subsequent processing.

index.html

<html>
    <head>
        <link href="styles/styles.css" rel="stylesheet" />
        <script src="jquery-3.7.1.min.js"></script>
        <link rel="stylesheet" href="jquery-ui.min.css">
        <title>****________****</title>
    </head>
<body>

   
<?php
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    ?>
    <div text-align="center">
    <table>
        <tr>
            <?php
            while ($row = $result->fetch_array()) { ?> 
                <td contenteditale=false;><?php echo $row["name"]?></td>
                <?php 
                $i = 1;
                while ($i <= 31) {
                    $day = "d" . $i;  
                    $val = $row[$day]; 
                    ?>
                    <td contenteditable=true><?php echo $val ?></td>
                    <?php $i++; } ?>
        </tr>
        <?php
} 
$conn->close();
?>
</table>
</div>  
<script src="js/_main.js"></script>  
</body>
</html>

_main.js

$(document).ready(function() {
$(function(newdata) {
            var $newvalue ='';
            $('table td').blur(function() {
                console.log("new value: " + $(this).text()); // show the new value
                $newvalue = $(this).text();
                return $newvalue
            });
});
})

Trying to use Dom method to fetch messages [closed]

I am trying to use the fetch() method to fetch

get.php to load messages:

The problem is: ( 1.) messages are duplicated or sometime triplicated when loaded.

(2)The messageBox container is stable, it can play uploaded video alright.

The scrolling is stable ,but the messages keep duplicating or triplicating.

(3) When a new message is submitted by the user the message is displayed twice.What can I do?

Here is my code.

get.php

header(‘ Content-type: application/json’);

$lastId=isset($_GET[‘last_id’])?intval($_GET[‘last_id’]):0;

$groupID=$_GET[‘clubid’];

$qry=”select *from grp_messages where grpID=’$groupID’ and Id>’$lastId’ order by Id asc “;

$result= mysqli_query($link,$qry);

$output =” “;

while ($row=mysqli_fetch_assoc($result)){

$msgId=$row[‘Id’];

$clubid=$row[‘grpID];

$gpname=$row[‘grpName’];

$userid=$row[‘id_user’];

$first=$row[‘firstname’];

$last=$row[‘lastname’];

$usernamd=$row[‘username’];

$member_photo=$row[‘userProfPhoto’];

$message=$row[‘messages’];

$sent_on=$row[‘created_at’];

$dateMod=$row[‘created_at_modify’];

$message_photo=$row[‘grpMsgPhotos’];

$message_video=$row[‘grpMsgVideos’];

$message_video_ext=$row[‘grpMsgExtentions’];

$profile_photo_path=”usersPphotos/”;

$message_photo_path=”grpChatPhotos/”;

$message_video_path=”grpChatVideos/”;

video_show=”grpChatVideos/$message_video”;

$trc=$message_photo_path.$message_photo;

$Tsrc=$profile_photo_path.$member_photo ;

$imagalt=”Loading Image ….”;

$redirect=
”<a id=”refN”href=”mem_profile.php?…….”>”;

If($message_video==” “){

$msgvideo=” “;

}
else{

$msgvideo = “

<video onerror=”this.style.display=’none’” id=’msg_videotag’ loop muted controls><source src=’$video_show’type=’video/$message_video_ext’> Your browser doesn’t support the video tag.
”;

}

if(($message_video !=’’)&&($message_photo ==’’ )){

$output.=””;

$output.=”

$redirect

$first $last:

$msgvideo$message

Sent:”.$dateMod.””;

$output.=””;

}

$lastId=$msgId;

}

echo json_encode([“last_id”=>$lastId,”messages”=>
$output]);

JavaScript script.js
messageBox= document.getElementById(‘messages’);

var clubID=document.getElementById(‘clubid’). value;

var lastMessageId=0;

setInterval(()=>{

var isAtBottom=messageBox.scrollTop + messageBox.clientHeight >=messageBox.scrollHeight-10;

fetch(‘get.php? last_id=’ + lastMessageId + ‘&clubid=’ + clubID)

.then(response=>response.json())

.then(data=>{

if(data.messages){

document.getElementById(‘contbox’).style.display=”none “;

var tempDiv= document.createElement(‘div’);

temDiv.innerHTML= data.messages;

lastMessageId=data.last_id;

var lastChild=tempDiv.lastElementChild;

var lastMsgId=lastChild? lastChild.getAttribute(‘data-id):null ;

Array.from(tempDiv.children).for each(msg=>{

var msgId=msg.getAttribute(‘data-id’);

if(!msgId.includes(lastMsgId+1)){

messageBox.appendChild(msg);

}

});

if(isAtBottom){

messageBox.scrollTop = messageBox.scrollHeight ;

}

}

})

},1000);

PCIbex sequence of trials resulting in blank screen

I have been trying to code an experiment in PCIbex farm, where stimuli are kept in a .csv file. Prime and target trials are created from a pair of sentences (in the .csv file they’re located in the same row).

The problem is – there always is only a blank screen when I try running this code. In the logs it’s OK: the sentences are read and all. I’ve also tried generating unique IDs for each trial created from a template, but it didn’t help + the .csv is too long to write the sequence manually. Naming the trials within the template differently (training_prime and training_target)

As my experimental trials have the same structure as the training ones, here is the simplified version of the script. It is supposed to generate “training_prime” and “training_target” trials dynamically from the training_trials.csv file. Each “training_prime” is immediately followed by its corresponding “training_target”, maintaining the pairing from the same row:

PennController.ResetPrefix(null)

Sequence(
    randomize("training"),
    SendResults()
)

Template("training_trials.csv", row =>
[
  newTrial("training",
    newText("PRIME: " + row.prime_sentence).print(),
    newController("AcceptabilityJudgment", {
        s: row.prime_sentence,
        as: ["1", "2", "3", "4", "5", "6", "7"],
        presentAsScale: true,
        instructions: "Evaluate the sentence",
        leftComment: "weird",
        rightComment: "good"
    }).center().print().wait(),
    newTimer("pause", 300).start().wait()
  ),

  newTrial("training",
    newText("TARGET: " + row.target_sentence.replace("___", "<input type='text' id='gap'>")).print(),
    newButton("Next").print().wait()
  )
])

And here is training_trials.csv:

pairID,prime_sentence,target_sentence
t1,PRIME 1.,In a hole in the ground there lived a ___.
t2,PRIME 2.,A mouse took a stroll through the ___ dark wood.

I’ve spent an inadequately long time on this…

Detect when Dropdown is open or closed

I need to be able to detect when the Flowbite Dropdown opens and closes from its parent component. When opened, I need to call an API endpoint and update the state of one of its items, but only when opened. The reason for this is I have dozen’s of these dropdowns present on the page at once and running these update functions all at once is detrimental to the performance.

Here’s a minimal example component. Populate would be an async call to the backend. This works, and does what I want, but this runs for every item for every RowOptions component rendered on the screen. This is a lot of processing. I want this to happen lazily only for the items in the open dropdown.

export default function RowOptions() {
  return (
    <>
      <Dropdown label={<div><DotsIcon/></div>}>
        <Dropdown.Header>Actions</Dropdown.Header>
        {items.map(item => (
          <Dropdown.Item>{populate()}</Dropdown.Item>
        ))}
      </Dropdown>
    </>
  )
}

I’d hoped it would have an onOpen or onClose property I could hook to, but it does not. Is there a wrapper I can use to get this functionality? I tried using a ref to track when it’s visible, but that only worked partially.
For example, I added a div within the dropdown with a ref <div ref={myRef}><div> and then connected that to the state within the dropdown label’s onClick:

export default function RowOptions() {
  const [isOpen, setIsOpen] = useState(false);
  const myRef = useRef(null);

  return (
    <>
      <Dropdown label={<div onClick={() => { setIsOpen(myRef === null) }}><DotsIcon/></div>}>
        <div ref={myRef}><div>
        <Dropdown.Header>Actions</Dropdown.Header>
        {items.map(item => (
          <Dropdown.Item>{populate()}</Dropdown.Item>
        ))}
      </Dropdown>
    </>
  )
}

This worked partially. I could essentially track the state changing if the button was clicked…but this fall apart as soon as you clicked an item or out of the dropdown. Then the state would get all messy. So this approach clearly wasn’t the best option.

My last thought was using a Mutation observer, hooking up to the Dropdown, and then watching the updating of the classes. I’m not sure if this is the best approach, specifically for React, but that’s what I’m working on now.

React Input Issue: Can’t Delete First Character or Replace Default Value in Input Fields

I am encountering an issue with input fields in my React app. When I try to replace a default value in the input field (e.g., “0” or “1”), I am unable to completely clear the value. Specifically, I cannot delete the first character (whether it’s a number or letter). For example:

If the input is “USD” by default and I try to replace it with “SGD”, I cannot delete the “U” and the input still shows “USD” or “0120” when trying to type “120” instead of “0”.

This happens across multiple input fields, whether I am trying to replace numeric values (e.g., 1 to 120) or currency symbols (e.g., USD to EUR).

   <div className="alert-devise-choice">
    <label htmlFor="symbol" className="alert-deviseLabel">Choisir une devise:</label>
     <input
       type="text"
       id="symbol"
       value={symbol}
       onChange={(e) => handleChange("symbol", e.target.value)}
       className="alert-devise-input"
       required
       autoComplete="off"
       />
    </div>
    {errors.symbol && <small className="error-message">{errors.symbol}</small>}

const handleChange = (field, value) => {

let updatedErrors = { ...errors};

 if (field === 'symbol') {
    const isNumeric = !isNaN(value);
    const validSymbols = filteredDevises.map(devise => devise.symbol);
    const isInList = validSymbols.includes(value.toUpperCase());
 if (isNumeric) {
       updatedErrors.symbol = "Please enter a valid currency symbol.";
    } else {
       updatedErrors.symbol = "";
       setSymbol(value); // or however you store the selected symbol
    }
}
   if (field === 'valueLimit') {
        if (isNaN(value) || value < 0.1) {
           updatedErrors.valueLimit = "Value limit must be a number and at least 0.1.";
        } else {
            updatedErrors.valueLimit = "";
            setValueLimit(value);
       }
    }

setErrors(updatedErrors);
};

Automa workflow

enter image description here

Where do I save the value to use it later in the ‘Form’ block? I added this JavaScript code but I don’t know where to store the result and where to insert the variable. I tried putting the variable in the ‘form’ but it doesn’t work

I’m using the Automa Chrome extension to build an automation flow.
I want to extract a value from a web page (for example, a product name or ID), save it, and then reuse it later in the same flow or even in another flow.

I’m confused about where and how variables are stored in Automa.
Should I use the Set Variable block or the Set Data to Storage block?
What’s the difference between them?

Also, is it possible to access a saved variable across different flows or sessions?

enter image description here

Speed issues with chrome.storage.local API

I have recently migrated my old MV2 exentension to MV3. While it is ‘done’ and out in the store, I have noticed that when the chrome.storage.local is fairly large, then the extension becomes very slow to load between pages of the extension.

Clearing the data incrementally does help, but users of the extension have notced the threshold we built into the extension is hit very easily and frequently without heavy use. We currently display a warning to clear it off to avoid speed issues as a ‘band-aid’ solution for the interim.

I have not noticed any indication that others are experiencing this type of issue, but that may be down to my use of the API. I use it as in the MV2 version we saved lots of request data for our audit tools into JS objects/arrays and then read them when the user prompts to see the audit. As MV3 uses a service worker, and after doing lots of reading on here and of the official extension documentation; I went with the API to store the data and read on execution. It of course works, but this speed issue is causing some grumbles and I am keen to not have loads of loading wheels in the extension as that doesn’t really solve the issue.

Main question here is, has anyone found more intuitive or alternative ways to store and read lots of data within the extension without compromising the speed of the extension?

Drag and drop, dropping issue Javascript

I am trying to make a drop box, but I only seem to make it draggable and rearrange the items. And therefore, I can’t have a separate list for containers1 for dropping the items in from containers.

const draggables = document.querySelectorAll('.draggable')
const containers = document.querySelectorAll('.img-box')
const containers1 = document.querySelectorAll('.container1')

draggables.forEach(draggable => { 
    draggable.addEventListener('dragstart', () => { 
        draggable.classList.add('dragging')
    })
    draggable.addEventListener('dragend', () => {
        draggable.classList.remove('dragging')
    })
})

containers.forEach(container => { 
    container.addEventListener('dragover', e => {
        e.preventDefault()
        const afterElement = getDragAfterElement(container, e.clientY)
        const draggable = document.querySelector('.dragging')
        if (afterElement == null) {
            container.appendChild(draggable)
        } else {
            container.insertBefore(draggable, afterElement)
        }
    })
})

containers1.forEach(container => {
    containers1.addEventListener('dragover', function (e) {
        e.preventDefault();
    });
    containers1.addEventListener("drop", function (e) {
        e.appendChild(selected);
        selected = null;
    });
});

function getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')]
    return draggableElements.reduce((closest, child) => {
        const box = child.getBoundingClientRect()
        const offset = y - box.top - box.height / 2
        if (offset < 0 && offset > closest.offset) {
            return { offset: offset, element: child }
        } else {
            return closest
        }
    }, { offset: Number.NEGATIVE_INFINITY }).element
} 
<body>
    <div class="box">
        <div class="glass-container2">
            <div class="container3">
                <div class="scroller" data-animated="true">
                    <ul class="img-list scroller-inner">
                        <div class="img-box">
                            <div class="draggable" draggable="true">hello</div>
                        </div>
                        <div class="img-box">
                            <div class="draggable" draggable="true">hello</div>
                        </div>
                        <div class="img-box">
                            <div class="draggable" draggable="true">hello</div>
                        </div>
                        <div class="img-box">
                            <div class="draggable" draggable="true">hello</div>
                        </div>
                        <div class="img-box">
                            <div class="draggable" draggable="true">hello</div>
                        </div>
                        <div class="img-box">
                            <div class="draggable" draggable="true">hello</div>
                        </div>
                        <div class="img-box">
                            <div class="draggable" draggable="true">hello</div>
                        </div>
                        <div class="img-box">
                            <div class="draggable" draggable="true">hello</div>
                        </div>
                        <div class="img-box">
                            <div class="draggable" draggable="true">hello</div>
                        </div>
                    </ul>
                </div>
            </div>
        </div>

        <div class="glass-container3">
            <div class="container1"></div>
            <div class="container4">
                <button class="button">
                    Submit
                </button>
            </div>
        </div>
    </div>
</body>

I attempted to make containers1 with a dropping attribute to drag and drop into it from containers.

containers1.forEach(container => {
    containers1.addEventListener('dragover', function(e) {
        e.preventDefault();
    });
    containers1.addEventListener("drop", function(e) {
        e.appendChild(selected);
        selected = null;
    });
});

Cypress not intercepting a request with mock data while seemingly detecting the request

I am trying to modify a Cypress test to use a similar URL from the same provider but by changing the URL, Cypress does not seem to intercept the request anymore. The original test with the original URL works.

According to my understanding if the webpage makes any request to that URL that Cypress is trying to intercept, it will intercept it. Currently, it times out with the error “No request ever occurred”.

I have tried to add delays, have checked that the intercepts would happen before the tests are made, confirmed the file the test would test works correctly and requests the same URL’s.

cypress_error_image

Structure of the Code:


describe("the_test", () => {
  beforeEach(() => {
    cy.intercept(
      "URL_1",
      { fixture: "URL1_mockdata.json" }
    ).as("getPopulation");

    cy.intercept(
      "URL_2",
      { fixture: "URL2_mockdata.json" }
    ).as("getEmployment");
  });

  it("Table should be populated if JS is enabled", () => {
    cy.visit("/");
    cy.wait("@getPopulation");
    cy.wait("@getEmployment");

    cy.get("table tbody tr").should("have.length", 10); // Or however many are in your fixture
  });
});