Animation with framer motion layouts not working

I have an image gallery with a filtering function. I want to animate the shifting of the images when they get filtered. I read online about using framer motion’s layout feature. I saw examples emulating exactly what I want to do like this one. When I set it up in my workspace it does not work, it does weird stretch animations and looks horrible. I created a code sandbox to demonstrate the issue. I would like to fix the animation so the tiles re-order properly. Any help would be appreciated thanks!

making a calculator and trying to display the values, help appreciated

const decimal = document.getElementById("decimal");
const equals = document.getElementById("equal-sign");
const clear = document.getElementById("all-clear");
const operand = document.getElementById("operand");
const digits = document.querySelectorAll("button");
const button = document.querySelectorAll("button");
const add = (num1, num2) => {
  return num1 + num2;
};

const subtract = (num1, num2) => {
  return num1 - num2;
};

const multiply = (num1, num2) => {
  return num1 * num2;
};

const divide = (num1, num2) => {
  return num1 / num2;
};

const operate = (operator, num1, num2) => {
  switch (operator) {
    case "+":
      return add(num1, num2);

    case "/":
      if (num2 == 0) {
        return "ERROR";
      } else {
        return divide(num1, num2);
      }

    case "-":
      return subtract(num1, num2);

    case "*":
      return multiply(num1, num2);
  }
};

for (const digit of digits) {
  digit.addEventListener("click", () => {
    if (digit.classList.contains("number")) {
      operand.textContent += String(digit.textContent);
    }
  });
}
clear.addEventListener('click', () => {
  operand.textContent = '';
})

I’m making a calculator and trying to display the values on a constant called operand, this works, but I want it so that when I click an operator the screen clears and displays the numbers, help will be appreciated.

How can I grab a word in an iframe src?

This js allows copying a clicked word in an html element to var “str”. But I want to grab a word in an iframe src. I modified the js to target the iframe id #USCF_CUST and grab the clicked word, but it doesn’t seem to work. The clicked word is not selected and copied to var “str”. Can anyone tell me why?

<div class = "clickable">The rain in Spain falls mainly in the plane.</div>

 $(".clickable").click(function(e) {
 s = window.getSelection(); var range = s.getRangeAt(0); var node = s.anchorNode;
 while (range.toString().indexOf(' ') != 0) {range.setStart(node, (range.startOffset - 1));}
 range.setStart(node, range.startOffset + 1);
 do {range.setEnd(node, range.endOffset + 1);}
 while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');
 str = range.toString().trim(); alert (str);
});

But the above js doesn’t work (it does nothing) in this instance:

<iframe id = 'USCF_CUST' src= url_2 ></iframe>

 $("#USCF_CUST").click(function(e) {
 s = window.getSelection(); var range = s.getRangeAt(0); var node = s.anchorNode;
 while (range.toString().indexOf(' ') != 0) {range.setStart(node, (range.startOffset - 1));}
 range.setStart(node, range.startOffset + 1);
 do {range.setEnd(node, range.endOffset + 1);}
 while (range.toString().indexOf(' ') == -1 && range.toString().trim() != '');
 str = range.toString().trim(); alert (str);
});

Como alterar o valor do objeto em um arquivo JSON com fs/nodejs? [closed]

Eu preciso armazenar algumas id’s de mensagens que foram criadas pelo meu bot do Discord. Porém eu não estou conseguindo de nenhuma forma manipular meu arquivo JSON, eu preciso de alguma forma que seja alterado somente o valor do ID da mensagem específica que eu quero alterar, já tentei utilizar o
fs.WriteFile só que ele substitui o arquivo por inteiro, também utilizei o fs.appendFile e ele adiciona toda uma nova estrutura (acabando com a sintaxe do JSON).

Como eu poderia manipular essa estrutura da melhor forma possível?

Estrutura do meu Json: { "msg1": { "id": "1" }, "msg2": { "id": "2" }, "msg3": { "id": "3" } }

Function that takes an array and returns elements inside rotated n spaces in js

Create a function named “rotate” that takes an array and returns a new one with the elements inside rotated n spaces.

If n is greater than 0 it should rotate the array to the right. If n is less than 0 it should rotate the array to the left. If n is 0, then it should return the array unchanged.

Example:

var data = [1, 2, 3, 4, 5];

rotate(data, 1) // => [5, 1, 2, 3, 4]
rotate(data, 2) // => [4, 5, 1, 2, 3]
rotate(data, 3) // => [3, 4, 5, 1, 2]
rotate(data, 4) // => [2, 3, 4, 5, 1]
rotate(data, 5) // => [1, 2, 3, 4, 5]

rotate(data, 0) // => [1, 2, 3, 4, 5]

rotate(data, -1) // => [2, 3, 4, 5, 1]
rotate(data, -2) // => [3, 4, 5, 1, 2]
rotate(data, -3) // => [4, 5, 1, 2, 3]
rotate(data, -4) // => [5, 1, 2, 3, 4]
rotate(data, -5) // => [1, 2, 3, 4, 5]

Furthermore the method should take ANY array of objects and perform this operation on them:

rotate(['a', 'b', 'c'], 1)     // => ['c', 'a', 'b']
rotate([1.0, 2.0, 3.0], 1)     // => [3.0, 1.0, 2.0]
rotate([true, true, false], 1) // => [false, true, true]

Finally, the rotation shouldn’t be limited by the indices available in the array. Meaning that if we exceed the indices of the array it keeps rotating.

Example:

var data = [1, 2, 3, 4, 5]
rotate(data, 7)     // => [4, 5, 1, 2, 3]
rotate(data, 11)    // => [5, 1, 2, 3, 4]
rotate(data, 12478) // => [3, 4, 5, 1, 2]

How to throttle or debounce controlled input?

I am attempting to throttle this input field. The reason is because I want to save the input value into redux state and I read that you should not use redux state with onChange handlers because redux is not meant for high frequency state changes as opposed to local state. I tried the following but because it is a controlled input where the value is equal to the state the value is not updating.

 class Information extends Component {
    state = { 
myvalue:''
     }
     
changeHandler = (e) =>{

setTimeout(()=>{
    this.setState({
        myvalue:e.target.value
    })  

},1000)

}

    render() { 
        return (<div>
            <textarea value={this.state.myvalue} onChange={this.changeHandler} />


        </div>);
    }
}
 
export default Information;

 

Proper way to render orbit circles with electrons evenly spaced in React js

I am a bit rusty with JavaScript and React, but I have an assignment and I’m trying to draw some orbits with some evenly spaced electrons on each of them.

I think it should look something like this:

<div style="orbitStyle">
  <div style="electronStyle"></div>
  <div style="electronStyle"></div>
</div>
<div style="orbitStyle">
 <div style="electronStyle"></div>
 <div style="electronStyle"></div>
 <div style="electronStyle"></div>
</div>

This is what I have so far. I know I’m missing something quite elementary, but can’t put my finger on it.

   orbits = (radius, orbitsNumber, numberOfElectrons) => {
        const renderOrbit = [];
        let orbitalRadius = 100;
        let orbitNumber = 2;
        let electronTotal = 5;
        let viewportWidth = orbitNumber * orbitalRadius;
        let layerColor;
        let layerBorder;
        let electronSize = orbitalRadius / 3;
        let electronColor;
        let electronX;
        let electronY;
        for (let i = 0; i <= orbitNumber; i++) {
           let  viewportXY = viewportWidth / 1.5 - orbitalRadius + 'px';
            let electronMaxNumber = parseInt(`${maxNumberOfElectrons[i]}`);
            let numNodes;

            let angle;
            for (let j = 1; j <= numNodes; j++) {
                let viewportXY2 = viewportWidth / 1.5 - orbitalRadius + 'px';
                angle = ((Math.PI * 2) / numNodes) * j;
                electronX = orbitalRadius + (orbitalRadius * Math.cos(angle)) / 2 + 'px';
                electronY = orbitalRadius + (orbitalRadius * Math.sin(angle)) / 2 + 'px';
              
                let electronStyle = {
                    left: electronX,
                    top: electronY,
                    position: 'relative',
                    display: 'block',
                    width: electronSize,
                    height: electronSize,
                    borderRadius: '100%',
                    background: electronColor,
                };
                renderOrbit.push(<div style={electronStyle}></div>);
            }
            let orbitStyle= {
                top: viewportXY,
                left: viewportXY,
                position: 'absolute',
                display: 'block',
                width: 2 * orbitalRadius,
                height: 2 * orbitalRadius,
                borderRadius: '100%',
                background: layerColor,
            };

            renderOrbit.unshift(<div style={orbitStyle}></div>);
            orbitalRadius += 50;
        }
        return renderOrbit;
    };

JS alter element with certain id and class name

I’m trying to change the style of a div with vanilla JS. The div should have a certain id and the class name tab-content:

function showTabContent() {
    document.getElementById(tabID).classList.contains("tab-content").style.display = "block";
}

HTML:

<div id="1" class="tab-content">Test...</div>
<div id="2" class="tab-content">Test...</div>
<div id="3" class="tab-content">Test...</div>

If for example I run:

showTabContent(2);

It should set the tab-content div with id 2 to style display block. It is not working. What am I doing wrong?

How do I insert loaders to my inversifyjs project?

I’m learning inversifyjs, and I’m trying to do the example from inversify package.
And I stumble upon an issue that you can see below:

Module parse failed: Unexpected character '@' (30:14)
File was processed with these loaders:
 * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ./node_modules/babel-loader/lib/index.js
 * ./node_modules/react-scripts/node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| 
| let Ninja = (_dec3 = injectable(), _dec3(_class3 = class Ninja {
>   constructor(@inject(TYPES.Weapon)
|   katana, @inject(TYPES.ThrowableWeapon)
|   shuriken) {

In this row (30:14) it does not recognise the @ from @inject(..).

How do I insert the loaders to my project for that to work?

Fabric.js: pinch to zoom bad stuttering

I am trying to enable smooth pinch to zoom on mobile devices on my fabric.js canvas. I have a solution that technically works, the problem is that it is very stuttery, the zoom happens in distinct stages, almost frame by frame, so it is not a good experience. It also seems to get worse as time goes on. Is there any way I can make it stutter less and scale more smoothly? I am testing on a good smartphone.

Here is the code:

canvas.on('touch:gesture',function(event) {
        if (event.e.touches && event.e.touches.length == 2) {
          if (event.self.state == "start") {
            zoomStartScale = self.canvas.getZoom();
          }
          // Calculate delta from start scale
          var delta = zoomStartScale * event.self.scale;
          // Zoom to pinch point
          self.canvas.setZoom(delta);
        }
      })

Delete even/odd occurance numbers in an array with For Loop

I have an array as shown below, containing 6 numbers. I’m trying to create a function that deletes a value if it’s an even/odd occurance. For example, if I type the function deleteData(myArr,"even"), it will remove data number 0th, 2nd, and 4th. And the other way around if it’s “odd”. But when I tried running my code, it didn’t work the way i wanted it to go. Can anybody tell me why?

const myArr=[90,34,28,19,26,22];


function deleteData (array,occuranceType){
    switch (occuranceType){
        case "odd":
            for (let i=0;i<array.length;i++){
                if (i%2!==0){
                    array.splice(i,1);
                };
            };
            break;
        case "even":
            for (let i=0;i<array.length;i++){
                if (i%2==0){
                    array.splice(i,1);
                };
            };
            break;
    };
};

deleteData(arr,"odd")
console.log(arr)

This is the result in the console : [ 90, 28, 19, 22 ]

loading=’lazy’ vs Intersection Observer?

I’m building a React app which is very image heavy, all from API calls. I’ve got loading='lazy' on all of them but it got me wondering if more can be done? I know you can achieve a similar result using intersection observers and only rendering them when in view.

My question is better/are there any further benefits to implementing intersection observers, or will it be a waste of time since loading='lazy' does enough?

Thanks!

Populate form fields ending in number from pdo mysql using ajax

Here is my basic form:

<form id="mgstaskvuephonecall" name="contactform" method="POST" >
    <div class="mb-3">
        <div class="input-group" id="fld1">
            <input type="text" name="contact1" id="contact1" class="form-control tvc username" placeholder="Contact" aria-label="Username" alt="1">
            <input type="text" name="phone1" id="phone1" class="form-control phone-number tvp" placeholder="Ex: +(000) 000-00-00" alt="1">
        </div>
    </div>
    <div class="mb-3">
        <div class="input-group" id="fld1">
            <input type="text" name="contact2" id="contact2" class="form-control tvc username" placeholder="Contact" aria-label="Username" alt="2">
            <input type="text" name="phone2" id="phone2" class="form-control phone-number tvp" placeholder="Ex: +(000) 000-00-00" alt="2">
        </div>
    </div>
 <!-- ... a total of 5: contact1-contact5, phone1-phone5 -->
</form>

I am using AJAX to call php to pull data from the database, how then would I use the result to populate my form. I am stuck on handling the fields with same names just differenced by the sequential number on the end of it. Here’s what I have so far, just stuck on how to manipulate results:

        // fetch table data based on date
        $("#form-date").on('change', function(){
            var date = $(this).val();
            $.ajax({
               url: 'dynamic-pop-form.php',
               method: 'POST',
               data:{
                "date":date
               },
               success: function(data){
               var len = data.length;
                ...
                }
               }
            });
        }); 

dynamic-pop-form.php:

include('connection.php');
$formDate = $_POST['date'];
$formDate = strtotime($formDate);
$formDate = date('Y-m-d', $formDate);
$stmt = $conn->prepare("SELECT * FROM `my_table` WHERE `form_date` = ? LIMIT 5");
$stmt->bindParam(1,$formDate,PDO::PARAM_STR);
$stmt->execute();

$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode( $result );

ANLTR4 grammar throws extraneous/mismatched input errors and returns an incorrect result

I would like to parse a toy language using ANTLR4. The Demo.g4 file looks like this:

grammar Demo;

/*
 * Lexer Rules
 */

fragment DIGIT   : [0-9] ;
fragment CHAR    : [a-zA-Z] ;
fragment WSCHAR  : [ tn] ;

FUNCTION    : 'function' ;
IF          : 'if' ;
THEN        : 'then' ;
ELSE        : 'else' ;

OPEN        : '(' ;
CLOSE       : ')' ;

KEYWORD     : CHAR+(DIGIT|CHAR)* ;
NUMBER      : DIGIT+ ;

COLON       : ':' ;
PLUS        : '+' ;
MINUS       : '-' ;
LESS        : '<' ;

WS          : WSCHAR+ -> skip ;

/*
 * Parser Rules
 */

root        : def+ EOF ;
def         : FUNCTION KEYWORD OPEN KEYWORD CLOSE COLON exp ;
exp         : NUMBER | exp PLUS exp | exp MINUS exp | exp LESS exp | call | OPEN exp CLOSE ;
call        : KEYWORD OPEN exp CLOSE ;

The string I wanted to parse is this:

"function fibonacci(number) : if number < 2 then number else fibonacci(number - 1) + fibonacci(number - 2)n"

The result is this:

(root (def function fibonacci ( number ) : (exp (exp if (call number)) < (exp 2))) then number else fibonacci ( number - 1 ) + fibonacci ( number - 2 ) <EOF>)

The if number < 2 part is parsed as exp if (call number)) < (exp 2))), which is strange, because a single number cannot turn into call according to my rules. And the second part was left unprocessed.

In addition to that, I get these warnings as well, that may be related, but I have no idea how to get rid of them:

line 1:29 extraneous input 'if' expecting {'(', KEYWORD, NUMBER}
line 1:39 mismatched input '<' expecting '('
line 1:43 extraneous input 'then' expecting {<EOF>, 'function'}
(root (def function fibonacci ( number ) : (exp (exp if (call number)) < (exp 2))) then number else fibonacci ( number - 1 ) + fibonacci ( number - 2 ) <EOF>)

I was able to find a similar question, but I do define tokens in the correct order.

What do I do wrong in my grammar file?