How to detect correct object comparing same object in another array?

Here is what I went to do.

    const original = [
                      {label: 'test1', formUid: 211},
                      {label: 'test2', formUid: 204},
                      {label: 'test3', formUid: 258},
                      {label: 'test4', formUid: 1045},
                      {label: 'test5', formUid: 1096},
                      {label: 'test5', formUid: 1096},
                       
                   ];
                   
  const modified = [
                      {label: 'test1', formUid: 211},,
                      {label: 'test4', formUid: 1045},
                      {label: 'test6', formUid: 1025},
                      {label: 'test5', formUid: 1096},
  ]

I have two arrays, one is original array otherone is modified array from the original array. So what happen here is I checked original array obejct include in modified array

Considering above two deleted object I am going to modify my copy of original array, So I make copy from orginal array delete the two object that I consirder as deleted. so output is like this for now

   const CopyOforiginal = [
              {label: 'test1', formUid: 211},
              {label: 'test4', formUid: 1045},
              {label: 'test5', formUid: 1096},
              {label: 'test5', formUid: 1096},
               
           ];

this is happening in my code you can see It in snippet,

But this the problem now, you can see two same object in original array (I have set the index for example)

  original = [
                 [4]:{label: 'test5', formUid: 1096},
                 [5]:{label: 'test5', formUid: 1096},
                ]

and one object in modified array same object as above objects

modified = [ 
             [3]:{label: 'test5', formUid: 1096},
           ]

So How can I compare this ? See if we get first object from the original array and find modified array have an same object yeah there is a one it found same object from the modified array that finish

Then get second same object from the original array and check is modified array have any matching object with that , there have one but it counted before we cant get again and again same object So original array second object want to mark as deleted one

after fix all these problems final result want to be like this

const CopyOforiginal = [
                  {label: 'test1', formUid: 211},,
                  {label: 'test4', formUid: 1045},
                  {label: 'test5', formUid: 1096},

               ];

function testFunc(){
      
       const original = [
                          {label: 'test1', formUid: 211},
                          {label: 'test2', formUid: 204},
                          {label: 'test3', formUid: 258},
                          {label: 'test4', formUid: 1045},
                          {label: 'test5', formUid: 1096},

                       ];

      const modified = [
                          {label: 'test1', formUid: 211},,
                          {label: 'test4', formUid: 1045},
                          {label: 'test6', formUid: 1025},
                          {label: 'test5', formUid: 1096},
                          {label: 'test5', formUid: 1096},
      ]
      

    let originalCopy;
  let flag;
  let oForm , oIdx;
  let srcipt = [];
 
   originalCopy = [...original];
   
    original.forEach((originForm, originInx) => {
   
    let res = modified.some(item => item.formUid === originForm.formUid)
   
      if(!res){
srcipt.push(originForm.formUid + " DELETE_FROM " + (originInx+1)); //created the script for deleted form
     
        let res = originalCopy.findIndex(idx => idx.formUid === originForm.formUid); //get the index from copy of the original array
        originalCopy.splice(res, 1); //remove the object
      }
    })
   

    //document.getElementById("originalArray").innerHTML = JSON.stringify(original);
    //document.getElementById("modifiedArray").innerHTML = JSON.stringify(modified);
    document.getElementById("result").innerHTML = JSON.stringify(srcipt);
    document.getElementById("copyArray").innerHTML = JSON.stringify(originalCopy);
  }
<button onClick="testFunc()">Click</button>
originalArray : <p id="originalArray"></p>
modifiedArray : <p id="modifiedArray"></p>
result        : <p id="result"></p>
CopyOf original Array result        : <p id="copyArray"></p>

Firestore Array of map not updating

So I’m working on a personnal project to learn react-native and firestore.

I have a a DB like this:
Db image

and I want by code to add a new battery in the array batteries.
The elements in the array are just a map{string, string}

The problem is that when I update the array with a new brand that’s work but if I want to update it with the same brand again have,
so having by the end

batteries[0]: {'brand': 'cestmoi'}
batteries[1]: {'brand': 'cestmoi'}

the db doesn’t update, don’t have any error or so.

I don’t understand why and I followed their tuto. Here is my code:

async function addData(collection, doc, value) {
    console.log(`Add data ${value.brand}`)
    try {
        const result = await firestore()
                    .collection(collection)
                    .doc(doc)
                    .set({
                        batteries: firestore.FieldValue.arrayUnion(value)
                    })
        console.log(result);
        return result;
    } catch (error) {
        return error;
    }
}

I use try catch by habit but I don’t know if the then...catch is better or not…

Thanks

Clonar texto de un text area dentro de un div con saltos de linea [closed]

necesito que cuando se presione agregar se cree un div debajo con exactamente el mismo texto que el escrito dentro del text area, con los saltos de linea incluido.

imagen de la pagina y su mal funcionamiento

 <body>
     <div id="colorInterfas">
    <p>FONDO</p>
        <input type="color" name="color" id="colorFondo">
        <input type="color" name="color" id="colorLetra">
    <p>LETRA</p>
    </div>
   
        <textarea id="input" cols="30" rows="10"></textarea>
   

    <button id="button">agregar</button>
    </div>
    <ul id="container">

    </ul>
    </body>




let text = document.querySelector('#input');
let button = document.querySelector('#button');
let container = document.querySelector('#container');
let colorPickerFondo = document.querySelector('#colorFondo');
let colorPickerLetra = document.querySelector('#colorLetra');



colorPickerFondo.addEventListener('change', () => {

text.style.background = colorPickerFondo.value

})

colorPickerLetra.addEventListener('change', () => {
text.style.color = colorPickerLetra.value

})

if (text.style.background === '') {
text.style.background = colorPickerFondo.value;

}

if (text.style.color === '') {

    text.style.color = colorPickerLetra.value;

}

button.addEventListener('click', () => {

if (text.value.trim().length !== 0) {
    let CONTENT = document.createElement('il');
    CONTENT.classList.add('content');
    CONTENT.textContent = text.value;
    CONTENT.setAttribute('style', ` background: ${text.style.background} ; color: ${text.style.color};  width: 180px; height: 180px;`);
    container.appendChild(CONTENT);

}
});

Con este codigo el texto es copiado, pero todo junto, sin los saltos de linea.

este codigo es para hacer una pagina que cree anotaciones tipo “post-it” de diferentes colores
me faltaria hacer eso y despues lograr que se acomode de la manera correcta
porque ahora mismo se quedan todos pegados xd

Muchas gracias.

window onunload/onbeforeunload events don’t work?

I’ve used the event in other projects/games but it doesn’t seem to be working on this one. onload event is working fine tho.

Script is linked on the bottom of the html before the < /body > tag

the code in client.js

(() => {
    // Player Closes window
    window.addEventListener("beforeunload", function (e) {
        sock.emit('player-leave', player);
        alert('window.addEventListener');
    });
    window.onbeforeunload = function(event) {
        sock.emit('player-leave', player);
        alert('window.onbeforeunload');
    };
    window.onunload = function(event) {
        sock.emit('player-leave', player);
        alert('window.onunload');
    };
})();

Event doesn’t pass throu and no alert is shown.

Best way to restrict page access?

I’m designing a website with a form component that redirects to a “failure” or “success” component based on whether the form submits without an error or not. Here is the code I’m using:


                  await axios.post('/api/patients/', data, axiosConfig)
                  .then((response) => {
                    history.push('/success')
                  })
                  .catch((error) => {
                    history.push('/failure')
                  })

This works well even when I intentionally make a bad request by turning my network off or changing the route. However, I can type in the “/success” route in my browser and access it whether or not I’ve submitted the form. How do I restrict this behavior?

axios set custom cookies

Im trying to set a custom cookie, for axios requests. But it’s not working.

Thats my code

const axios = require('axios');
axios.defaults.withCredentials = true;

const client = axios.create({
    withCredentials: true
});

let url = 'https://google.de';

client
    .get(url, {
        headers: {
            Cookie: [
                'cookie1=value;'
            ],
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': true,
            'Access-Control-Allow-Headers': 'Origin, X-Requested-With, Content-Type, Accept',
        }
    })
    .then(res => {
        console.log(res.headers['set-cookie']); // Im getting "undefined"
    })
    .catch(err => console.error(err));

i tried different ways, but have no luck. maybee any one know how i can set custom cookies in axios? or recommend a better library to do that..

Filter timestamp from sql database and extract as a list in python

I have an sql database from node red. The table of the database contains a column with javascript date.now() timestamps e.g. 1641154320892. Another column of the table contains temperature values. I’d like to select temperature values of a specific time period.

I tried the following code:

import sqlite3
conn = sqlite3.connect('/home/ktm/Developing/test/home_automation.db')
print ("Opened database successfully")
conn.row_factory = lambda cursor, row: row[0]
c = conn.cursor()
ids = c.execute('SELECT Buero_temp FROM home_automation WHERE Zeitstempel BETWEEN '2022-01-05' AND '2022-01-07';').fetchall()
for i in ids:
    print (i)

Unfortunately, I get “SyntaxError: invalid syntax”

What am I doing wrong?

How Can I Display Images When Clicked?

I am trying to develop a card matching game. I watched a Youtube Tutorial about it. But the cards does not show up even if I write the exact code from the video. The aim is matching two same characters. The characters should show up when a portal is clicked. So what’s the problem here? Here is my JavaScript code:

document.addEventListener('DOMContentLoaded',()=>{

    const cardArray = [
        {   
            name: 'beth',
            img: 'images/beth.png'
        },  

        {   
            name: 'beth',
            img: 'images/beth.png'
        }, 

        {   
            name: 'jerry',
            img: 'images/jerry.png'
        },    

        {   
            name: 'jerry',
            img: 'images/jerry.png'
        }, 

        {   
            name: 'morty',
            img: 'images/morty.png'
        },    

        {   
            name: 'morty',
            img: 'images/morty.png'
        }, 

        {   
            name: 'mrpoopybutthole',
            img: 'images/mrpoopybutthole.png'
        }, 
    
        {   
            name: 'mrpoopybutthole',
            img: 'images/mrpoopybutthole.png'
        },  

        {   
            name: 'rick',
            img: 'images/rick.png'
        },    

        {   
            name: 'rick',
            img: 'images/rick.png'
        },

        {   
            name: 'summer',
            img: 'images/summer.png'
        }, 
        
        {   
            name: 'summer',
            img: 'images/summer.png'
        }  
    ]


cardArray.sort(()=> 0.5 - Math.random());

const grid = document.querySelector('.grid');
const resultDisplay = document.querySelector('#result');
var cardsChosen = [];
var cardChosenId = [];
var cardsWon = [];


function createBoard() {
    for(let i=0; i<cardArray.length; i++){
        var card = document.createElement('img');
        card.setAttribute('src','images/portal.png');
        card.setAttribute('data-id', i);
        card.addEventListener('click', flipCard);
        grid.appendChild(card);
    }
}

function checkForMatch(){
    var cards = document.querySelectorAll('img');
    const optionOneId = cardsChosenId[0];
    const optionTwoId = cardsChosenId[1];

    if (cardsChosen[0] === cardsChosen[1]) {
        alert('You found a match');
        cards[optionOneId].setAttribute('src', 'images/white.png');
        cards[optionTwoId].setAttribute('src', 'images/white.png');
        cardsWon.push(cardsChosen);
    }

   else {
       cards[optionOneId].setAttribute('src', 'images/portal.png');
       cards[optionTwoId].setAttribute('src', 'image/portal.png');
       alert('Sorry, try again');
   } 

   cardsChosen = [];
   cardChosenId= [];
   resultDisplay.textContent = cardsWon.length;

   if (cardsWon.length === cardArray.length/2){
        resultDisplay.textContent = 'Congratulations! You found them all!';
   }

}


function flipCard(){
    var cardId= this.getAttribute('data-id');
    cardsChosen.push(cardArray[cardId].name);
    cardsChosenId.push(cardId);
    this.setAttribute('src',cardArray[cardId].img);

    if(cardsChosen.length === 2){
        setTimeout(checkForMatch,500);
    }


}
createBoard();

});

Create a function that follows a moving text on a table

I found a function to move data between table cells but the functions never seem to stick to whatever tag is “attached” to the cell itself. I’m not sure if I was using ids wrong. I need help finding a way to “attach” a function to a tag that moves between cells.
Can you help me create a button to move a tag (unit 1) upwards and downwards through a table such that it stops at the end of the table?

Original code attached here

//Send to the "bottom"
function sendOS() {
  var node = document.getElementById("r1c1").lastChild;
  document.getElementById("r1c3").appendChild(node);
  /*
    var node = document.getElementById("r1c3").lastChild;
  document.getElementById("r1c2").appendChild(node);
  */
}

//Send to the "top"
function sendTop() {
  var node = document.getElementById("r1c2").lastChild;
  document.getElementById("r1c1").appendChild(node);
}
table,
th,
td {
  border: 1px solid black;
  width: 32px;
  height: 32px;
}
<table>
  <tr id="row1">
    <td id="r1c1">Unit1</th>
      <td id="r1c2">Unit2</th>
        <td id="r1c3">Unit3</th>
  </tr>
  <tr id="row2">
    <td id="r2c1">r1c2</td>
    <td id="r2c2">r2c2</td>
    <td id="r2c2">r2c3</td>
  </tr>
  <tr id="row3">
    <td id="r2c2">r3c1</td>
    <td id="r2c2">r3c2</td>
    <td id="r2c2">r3c3</td>
  </tr>
</table>
<!--Table ends -->
<!-------------------------------------------------------------->


<button onclick="sendOS()">move to the other side</button>
<button onclick="sendTop()">move to the right</button>

AJAX: Posts are sent empty

I am using AJAX for the first time and try to send data to my PHP controller with an XMLHttpRequest. Unfortunately, the data arrives empty there.

           request.onload = () => {
                let responseObject = null;

                try {
                    responseObject = JSON.parse(request.responseText);
                } catch (e) {
                    console.error('Could not parse JSON!');
                }

                if (responseObject) {
                    handleResponse(responseObject);
                }
            };

            const requestData = `title=${this._title.value}&reference=${this._reference.value}&area=${this._area.value}`;

            request.open('post', 'checknews');
            request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            request.send(requestData);

Whats wrong ?

p5.js: Why can’t I use my ‘brush’ while background() is called in the draw() function?

I’m creating a painting app using the p5.js editor, and I want to be able to customise both the background and draw using various brushes etc.

The problem is, when I include background(variable) into the draw() function, I can only change the background, but cannot draw.

When I remove it so that it is only included in the setup, I can draw once again, but cannot change the background colour.

Is there a way to include both, perhaps in different functions?

Any help would be greatly appreciated as I’ve been stuck on this for days!!

Here is my code:

let whiteB;
let redB;
let yellowB;
let blueB;
let blackB;
let greenB;
let pinkB;
let brownB;
let bucket;

let brushSize;

let rSlide, gSlide, bSlide;
let r, g, b;

let imgLego;
let imgPalette;
let fontHead;
let fontMid;
let fontSub;
let x;

let legohead;
let lucky;


function preload() {
  imgLego = loadImage("images/lego.png");
  imgBucket = loadImage("images/bucket.png");
  fontHead = loadFont("fonts/shizuru.ttf");
  fontMid = loadFont("fonts/concertOne.ttf");
  fontSub = loadFont("fonts/gloria.ttf");
  
}// close preload function

function setup() {
  
  background(255);
  createCanvas(1000, 600);
  noStroke();

  x = 10;
  
  // create the slider for the brush size
  brushSize = createSlider(1, 100, 20);

  // create the sliders for red, gree, blue values
  rSlide = createSlider(0, 255, 0);
  gSlide = createSlider(0, 255, 0);
  bSlide = createSlider(0, 255, 0);

  // position the sliders
  rSlide.position(x, x * 20);
  gSlide.position(x, x * 22);
  bSlide.position(x, x * 24);
  brushSize.position(x, x * 26);

  // variables to hold the colour (background)
  r = 255;
  g = 255;
  b = 255;
  
  // variables to hold the colour (random button)
  r1 = random(0,255);
  g1 = random(0,255);
  b1 = random(0,255);
  
  // color variables for fill bucket
  whiteB = color(255);
  redB = color(255,0,0);
  yellowB = color(246, 236, 54);
  blueB = color(0,0,255);
  blackB = color(0);
  greenB = color(0,170,35);
  pinkB = color(255,53,184);
  brownB = color(155,103,60);
  bucket = whiteB;

}

function draw() {
  
  background(bucket);
  noStroke();
  
  // yellow rectangle acting as margin
  fill(yellowB);
  rect(0, 0, 250, height)
  
  // poisition the text & value of slider
  textAlign(LEFT, TOP);
  fill(255);
  textFont(fontMid);
  textSize(15);
  text("red : " + rSlide.value(), x*2 + rSlide.width, x*20);
  text("green : " + gSlide.value(), x*2 + gSlide.width, x*22);
  text("blue : " + bSlide.value(), x*2 + bSlide.width, x*24);
  text("brush : " + brushSize.value(), x*2 + brushSize.width, x*26);

  // read the value of the slider and store it in a variable
  r = rSlide.value();
  g = gSlide.value();
  b = bSlide.value();
  
  // customise "background" text
  fill(0);
  textSize(20);
  text("BRUSH COLOR", 20, 175);
  
  // red "navbar"
  fill(redB)
  rect(0,0,1000,120,0,0,50,0);
  
  // customse "sketch" text
  fill(255)
  textFont(fontHead);
  textSize(40);
  text("SKETCH", 180, 10)
  
  // customse "random" text
  fill(0)
  textFont(fontSub);
  textSize(25);
  text("random", 850, 550);
  
  
  // images
  image(imgBucket, 930, 40, 40, 40);
  image(imgLego, 20, 15, 160, 90);
  
  //**lego block top right corner**//
  stroke(0);
  strokeWeight(3)
  // yellow block
  fill(246, 236, 54);
  rect(748,18,164,84,5)
  
  
  // paint buttons
  
  ellipseMode(CENTER);
  
  // white button
  fill(whiteB);
  ellipse(770,40,30);
  if (mouseX > 750 && mouseX < 790 && mouseY > 20 && mouseY < 60 && mouseIsPressed) { 
  bucket = whiteB;
  }
    
  // red button
  fill(redB);
  ellipse(810,40,30);
  if (mouseX > 790 && mouseX < 830 && mouseY > 20 && mouseY < 60 && mouseIsPressed) { 
  bucket = redB;
  }
    
  // yellow button
  fill(yellowB);
  ellipse(850,40,30);
  if (mouseX > 830 && mouseX < 870 && mouseY > 20 && mouseY < 60 && mouseIsPressed) { 
  bucket = yellowB;
  }
  
  // blue button
  fill(blueB);
  ellipse(890,40,30);
  if (mouseX > 870 && mouseX < 910 && mouseY > 20 && mouseY < 60 && mouseIsPressed) { 
  bucket = blueB;
  }
  
  // black button
  fill(blackB);
  ellipse(770,80,30);
  if (mouseX > 750 && mouseX < 790 && mouseY > 60 && mouseY < 100 && mouseIsPressed) { 
  bucket = blackB;
  }
  
  // green button
  fill(greenB);
  ellipse(810,80,30);
  if (mouseX > 790 && mouseX < 830 && mouseY > 60 && mouseY < 100 && mouseIsPressed) { 
  bucket = greenB;
  }
  
  // pink button
  fill(pinkB);
  ellipse(850,80,30);
  if (mouseX > 830 && mouseX < 870 && mouseY > 60 && mouseY < 100 && mouseIsPressed) { 
  bucket = pinkB;
  }
  
  // brown button
  fill(brownB);
  ellipse(890,80,30);
  if (mouseX > 870 && mouseX < 910 && mouseY > 60 && mouseY < 100 && mouseIsPressed) { 
  bucket = brownB;
  } 
  
} // close draw function


function mouseDragged() {
  stroke(r,g,b);
  strokeWeight(brushSize.value())
  line(mouseX, mouseY, pmouseX, pmouseY)
  
} // close mouseDragged function

Get nested button id in header

So I’m trying to reference my button (which is nested inside my header/nav), to make an event onclick, but I cant seem to get it to work. Tried nesting getElementByName with getelementbyid tried some queryselector and querySelectorAll been watching a lot of videos and tutorials don’t know if I’m just doing them wrong thanks.

Tried:

var x = document.getElementsByClassName('hdr');
var y= x.querySelector('hdrBtns');
z = y.getElementById('singUp');

Tried:

const brt = document.querySelectorAll('.hdr .hdrBtns');
const dac = brt.getElementById('signUp');

Code Underneath:

 <body>
        <header class="hdr">
            <div class="hLogo">
                <h1>
                    Test
                </h1>               
            </div>

            <nav class="hdrBtns">
                <button id="singUp">Sign Up</button>
                <button id="singIN">Sign In</button> 
                
            </nav>
        </header>
     <script src="./script.js"></script>
    </body>

Find JSON values return as strings [duplicate]

I am trying to read the JSON data to find how many instances each trait_type’s value appears for each nth edition and send the value to the HTML table as a string with the trait_type value’s ID. The filter function currently returns 0 for each value.

var data = [
  {
    edition: 1,
    attributes: [
      {
        trait_type: "hair",
        value: "mullet"
      },
      {
        trait_type: "hat",
        value: "cap"
      }
    ]
  }
];
var mullet = data.filter(function (d) {
    return d.value === "mullet";
  }).length,
  cap = data.filter(function (d) {
    return d.value === "cap";
  }).length;

document.getElementById("mullet").innerText = mullet;
document.getElementById("cap").innerText = cap;
<dl>
  <dt>Hair?</dt>
  <dd id="mullet"></dd>
  <dt>Hat?</dt>
  <dd id="cap"></dd>
</dl>

firebase functions, cant resolve module?

Im having an annoying problem which i’ve spent most of my day trying to solve without any luck – Also tried searching for a solution here and on Google, but without any luck, or at least all solution tried out didn’t work.

When running my function, the firebase function log is telling me:

Cannot find module 'mailgun.js'

I have no idea why it won’t resolve the module as it exist in the package.json file.

From the package.json:

"dependencies": {
    "cors": "^2.8.5",
    "firebase-admin": "^9.8.0",
    "firebase-functions": "^3.14.1",
    "form-data": "^4.0.0",
    "mailgun.js": "^4.1.4"
  },

I’ve have done a npm install inside the functions folder, and it deploys without problems, so the problem is when calling the function…

The code is:

import * as functions from "firebase-functions";
import Mailgun from "mailgun.js";
// eslint-disable-next-line @typescript-eslint/no-var-requires
const formData = require("form-data");

const domain = "https://app.mailgun.com/app/sending/domains/sandboxae7cd087b3854d25a6933f1fe489b5e3.mailgun.org";
const mgClient = new Mailgun(formData);

const mg = mgClient.client({
  key: "mykey",
  username: "api",
  public_key: "mypublickey",
});

export const sendWelcomeEmailToClient = functions.https.onCall(
    async (email: string) => {
      return mg.messages.create(domain, {
        from: "Task System",
        to: email,
        subject: "Testing",
        html: "Dette er en test",
      });
    }
);

Please note, i’ve also tried doing a require instead of import on mailgun.js like so, but didn’t work either:

const Mailgun = require("mailgun.js");