MongoInvalidArgumentError: Update document requires atomic operators during attempted upsert

I’m working with node and mongodb 5. I have a unique index added to the Parcel property of my collection. As I run the program while testing, I get:

MongoBulkWriteError: E11000 duplicate key error collection: mydata.pima2 index: Parcel_1 dup key: { Parcel: "AARON" }   

My code:

for (let j = 0; j < lastNameRecords.length; j++) {
        const ln = lastNameRecords[j].name;
        const recordsObj = { 'Parcel': ln, 'recordNum': 'TBD' };
        recordsArr.push(recordsObj);
    }

    console.log('number of records: ', recordsArr.length);
    try {
-->        const response = await collection.insertMany(recordsArr, { ordered: false });
        const updated = await collection.updateOne(result, { recordNum: 'ERD' });
    } catch (error) {
        console.log(error);
    }

Th error is occurring at the line with the arrow above. Obviously as I test, I am inserting multiple records , all of which have been previously inserted into the ‘pima2’ collection. I want to avoid causing an error or handle it so that I can move on to the next statement

Thinking that maybe the best approach here is an upsert, I have decided to change

const response = await collection.insertMany(recordsArr, { ordered: false });

I am confused about https://www.mongodb.com/docs/manual/reference/method/db.collection.updateMany/ . I’d tried

const response = await collection.updateMany({}, recordsArr, { upsert: true });

but now getting the error in the title. How do I fix this?

Is there any way to detect if a website is using any cookie consent tool?

Actually, I need to determine if a site is using a cookie consent tool for managing its cookies or not. I would like to check this via running a script on any site via puppeteer js and so, is there any way with which I could check if a site is indeed using any cookie consent tool? Also, is there any way to check it via cookies only?

I tried to find if there’s any cookie that might indicate that but so, far I couldn’t.

How to change Dom document methods to REACT JS

How to convert or replace the below code into a react component code :

var pages = document.getElementsByClassName('page');
  for(var i = 0; i < pages.length; i++)
    {
      var page = pages[i];
      if (i % 2 === 0)
        {
          page.style.zIndex = (pages.length - i);
        }
    }


I have tried using many different methods and codes but it didn't worked.

If anyone could please help with the code.

TypeError: forEach is not a function

I am trying to run a function that returns my article, but I keep getting:

TypeError: articles.forEach is not a function

What am I doing wrong?

Markup

<body>
   <div class="container">
    <h1 class="mb-4">Blog Articles</h1>
    <a href="/articles/new" class="btn btn-success">New Articles</a>

    <% articles.forEach(article => { %>
        <div class="card mt-4"> 
            <% article.title %>
        </div>
    <% }) %>
    </div>
</body>

Error

TypeError: C:UserstitanOneDriveDocumentsGitHubMarkdown Blogviewsindex.ejs:15
    13|     <a href="/articles/new" class="btn btn-success">New Articles</a>

    14| 

 >> 15|     <% articles.forEach(article => { %>

    16|         <div class="card mt-4"> 

    17|             <% article.title %>

    18|         </div>


articles.forEach is not a function

Fetching data from API and Displaying response data into a Data grid

I am trying to fetch data from an API. I am getting data in the following format.

data: 
[
{type: 'PropertyDamage', id: '100', attributes: {identification_number: '3931', damage_date: '2021-04-29', report_date: '2021-06-26'}},
{type: 'PropertyDamage', id: '101', attributes: {identification_number: '3839', damage_date: '2021-01-21', report_date: '2021-08-25'}},
{type: 'PropertyDamage', id: '102', attributes: {identification_number: '3735', damage_date: '2021-04-25', report_date: '2021-10-29'}}
]

Below I have implemented the Data grid and tried to import data from API into this data grid.

const columns = [ { field: 'id', headerName: "ID" }, { field: "type", headerName: "TYPE" }];
const Dashboard = () => {
  const theme = useTheme();
  const colors = tokens(theme.palette.mode);
  const [propertydamages, setPropertyDamages] = useState([]);

  useEffect(() => 
    {
        const url = "URL";
            fetch(url, {
            method: "GET",
            withCredentials: true,
            headers: {
                'X-API-Key': 'API Key'
            }
            })
            .then((response) => response.json())
            .then((json) => {
              setPropertyDamages(json)
            } )
            .catch(function(error) {
                console.log(error);
            }, []);
    })

  return (
    <Box m="20px">
      {/* Data Grid */}
        <DataGrid 
            rows = {propertydamages}
            columns = {columns}
        />
    </Box>
  );
};

This is the error poping up into my console log. Nothing is appearing in the data grid(frontend side) Help needed. Thank you in advance.

I tried changing the data into different formats but it was not working.

Is there a way to use Flask instead of PHP on this code?

I’m working on a Drag and Drop function using Javascript as user side and PHP as backend. I would like to use Flask instead of PHP?

Javascript

function ui_add_log(message, color)
{
  var d = new Date();

  var dateString = (('0' + d.getHours())).slice(-2) + ':' +
    (('0' + d.getMinutes())).slice(-2) + ':' +
    (('0' + d.getSeconds())).slice(-2);

  color = (typeof color === 'undefined' ? 'muted' : color);

  var template = $('#debug-template').text();
  template = template.replace('%%date%%', dateString);
  template = template.replace('%%message%%', message);
  template = template.replace('%%color%%', color);
  
  $('#debug').find('li.empty').fadeOut(); // remove the 'no messages yet'
  $('#debug').prepend(template);
}

// Creates a new file and add it to our list
function ui_multi_add_file(id, file)
{
  var template = $('#files-template').text();
  template = template.replace('%%filename%%', file.name);

  template = $(template);
  template.prop('id', 'uploaderFile' + id);
  template.data('file-id', id);

  $('#files').find('li.empty').fadeOut(); // remove the 'no files yet'
  $('#files').prepend(template);
}

// Changes the status messages on our list
function ui_multi_update_file_status(id, status, message)
{
  $('#uploaderFile' + id).find('span').html(message).prop('class', 'status text-' + status);
}

// Updates a file progress, depending on the parameters it may animate it or change the color.
function ui_multi_update_file_progress(id, percent, color, active)
{
  color = (typeof color === 'undefined' ? false : color);
  active = (typeof active === 'undefined' ? true : active);

  var bar = $('#uploaderFile' + id).find('div.progress-bar');

  bar.width(percent + '%').attr('aria-valuenow', percent);
  bar.toggleClass('progress-bar-striped progress-bar-animated', active);

  if (percent === 0){
    bar.html('');
  } else {
    bar.html(percent + '%');
  }

  if (color !== false){
    bar.removeClass('bg-success bg-info bg-warning bg-danger');
    bar.addClass('bg-' + color);
  }
}



$(function(){
  /*
   * UI functions ui_* can be located in: demo-ui.js
   */
  $('#drag-and-drop-zone').dmUploader({ //
    url: '../backend/upload.php',
    maxFileSize: 3000000, // 3 Megs 
    onDragEnter: function(){
      // Happens when dragging something over the DnD area
      this.addClass('active');
    },
    onDragLeave: function(){
      // Happens when dragging something OUT of the DnD area
      this.removeClass('active');
    },
    onInit: function(){
      // Plugin is ready to use
      ui_add_log('Penguin initialized :)', 'info');
    },
    onComplete: function(){
      // All files in the queue are processed (success or error)
      ui_add_log('All pending tranfers finished');
    },
    onNewFile: function(id, file){
      // When a new file is added using the file selector or the DnD area
      ui_add_log('New file added #' + id);
      ui_multi_add_file(id, file);
    },
    onBeforeUpload: function(id){
      // about tho start uploading a file
      ui_add_log('Starting the upload of #' + id);
      ui_multi_update_file_status(id, 'uploading', 'Uploading...');
      ui_multi_update_file_progress(id, 0, '', true);
    },
    onUploadCanceled: function(id) {
      // Happens when a file is directly canceled by the user.
      ui_multi_update_file_status(id, 'warning', 'Canceled by User');
      ui_multi_update_file_progress(id, 0, 'warning', false);
    },
    onUploadProgress: function(id, percent){
      // Updating file progress
      ui_multi_update_file_progress(id, percent);
    },
    onUploadSuccess: function(id, data){
      // A file was successfully uploaded
      ui_add_log('Server Response for file #' + id + ': ' + JSON.stringify(data));
      ui_add_log('Upload of file #' + id + ' COMPLETED', 'success');
      ui_multi_update_file_status(id, 'success', 'Upload Complete');
      ui_multi_update_file_progress(id, 100, 'success', false);
    },
    onUploadError: function(id, xhr, status, message){
      ui_multi_update_file_status(id, 'danger', message);
      ui_multi_update_file_progress(id, 0, 'danger', false);  
    },
    onFallbackMode: function(){
      // When the browser doesn't support this plugin :(
      ui_add_log('Plugin cant be used here, running Fallback callback', 'danger');
    },
    onFileSizeError: function(file){
      ui_add_log('File '' + file.name + '' cannot be added: size excess limit', 'danger');
    }
  });
});


PHP

<?php

header('Content-type:application/json;charset=utf-8');

try {
    if (
        !isset($_FILES['file']['error']) ||
        is_array($_FILES['file']['error'])
    ) {
        throw new RuntimeException('Invalid parameters.');
    }

    switch ($_FILES['file']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
        default:
            throw new RuntimeException('Unknown errors.');
    }

    $filepath = sprintf('files/%s_%s', uniqid(), $_FILES['file']['name']);

    if (!move_uploaded_file(
        $_FILES['file']['tmp_name'],
        $filepath
    )) {
        throw new RuntimeException('Failed to move uploaded file.');
    }

    // All good, send the response
    echo json_encode([
        'status' => 'ok',
        'path' => $filepath
    ]);

} catch (RuntimeException $e) {
    // Something went wrong, send the err message as JSON
    http_response_code(400);

    echo json_encode([
        'status' => 'error',
        'message' => $e->getMessage()
    ]);
}


HTML

         <main role="main" class="container">
            <div class="row">
               <div class="col-md-6 col-sm-12">

                  <!-- Our markup, the important part here! -->
                  <div id="drag-and-drop-zone" class="dm-uploader p-5">
                     <h3 class="mb-5 mt-5 text-muted">Drag &amp; drop files here</h3>
                     <div class="btn btn-primary btn-block mb-5">
                        <span>Open the file Browser</span>
                        <input type="file" title='Click to add Files' />
                     </div>
                  </div><!-- /uploader -->

               </div>
               <div class="col-md-6 col-sm-12">
                  <div class="card h-100">
                     <div class="card-header">
                        File List
                     </div>

                     <ul class="list-unstyled p-2 d-flex flex-column col"
                        id="files">
                        <li class="text-muted text-center empty">No files
                           uploaded.</li>
                     </ul>
                  </div>
               </div>
            </div><!-- /file list -->

            <div class="row">
               <div class="col-12">
                  <div class="card h-100">
                     <div class="card-header">
                        Debug Messages
                     </div>

                     <ul class="list-group list-group-flush" id="debug">
                        <li class="list-group-item text-muted empty">Loading
                           plugin....</li>
                     </ul>
                  </div>
               </div>
            </div> <!-- /debug -->

         </main> <!-- /container -->


I’ve tried these links:

  1. https://www.jitsejan.com/python-and-javascript-in-flask
  2. https://flask.palletsprojects.com/en/2.2.x/patterns/javascript/
  3. https://towardsdatascience.com/talking-to-python-from-javascript-flask-and-the-fetch-api-e0ef3573c451

How do I check in javascript if my html checkbox is checked in html

I’m currently working on a library project, where you have a form where you put different information about a book, and also you have to check a checkbox if you have read the book. Well, the thing that I want to do is, if the checkbox is checked, I want the text content that is gonna be displayed in the html to be Read or if the checbox ain’t checked the text content to be Not read. Thanks in advance, and sorry if this question bothers anyone

function intakeFormData(){
    let Title = document.getElementById("Title").value;
    let Author = document.getElementById("Author").value;
    let Pages = document.getElementById("Pages").value;
    let Read = document.getElementById("Read").value;
    if(Read === true){
        Read.textContent = "Read";
       
    }else{
        Read.textContent = "Not read";
    }
    

change size of drawing marker relative to the speed of the cursor – Javascript

I have made a marker that draws when the mouse click is held down. I now want to change the size of this marker relative to the speed of the cursor. My code is as follows :

class App {
  constructor(event, x) {
    this.container = this.createContainer();
    this.canvas = this.createCanvas();
    this.ctx = this.canvas.getContext("2d");
    this.addEventListeners();
    this.isDrawing = this.letDrawing();
      }

  createContainer = () => {
    const container = document.createElement("div");
    container.className = "app-container";
    document.body.appendChild(container);
    return container;
  };

  createCanvas = () => {
    const canvas = document.createElement("canvas");
    canvas.className = "app-canvas";
    this.container.appendChild(canvas);
    canvas.width = this.container.getBoundingClientRect().width;
    canvas.height = this.container.getBoundingClientRect().height;
    return canvas;
  };

  addEventListeners = () => {
    this.canvas.addEventListener("mousemove", this.onMouseMove);
    this.canvas.addEventListener("mousedown", this.onMouseDown);
    document.addEventListener("mouseup", this.onMouseUp);
  };

  letDrawing = () => {
    this.isDrawing = false;
  };

  onMouseDown = () => {
    this.isDrawing = true;
  };

  onMouseMove = (event) => {
    if (this.isDrawing === true) {
      this.drawBall(event.x, event.y);
  
    }
  };

  onMouseUp = () => {
    this.isDrawing = false;
  };

  drawBall = (x, y) => {
    this.ctx.beginPath();
    this.ctx.arc(x, y, 0, Math.PI * 2);
    this.ctx.fillStyle = "#6f0ecf";
    this.ctx.fill();
    this.ctx.closePath();
  };
}
export { App };

I was thinking of using previous position of X and Y, and doing something like below… Can I use deltaX in this scenario?
Any help on how to do this would be much appreciated!!


  onMouseMove = (event) => {
    if (this.isDrawing === true) {
      this.drawBall(event.x, event.y);
      this.previousX = this.currentX;
      this.currentX = event.x;
      distance = this.currentX - this.previousX;
   
    }
  };
  onMouseMoveSpeed = () => {
    const size = speed * 10 + 10;
  };

  onMouseUp = () => {
    this.isDrawing = false;
  };

  drawBall = (x, y, size) => {
    this.ctx.beginPath();
    this.ctx.arc(x, y, size, 0, Math.PI * 2);
    this.ctx.fillStyle = "#6f0ecf";
    this.ctx.fill();
    this.ctx.closePath();
  };

My image cannot upload on cloudinary with restApi in node.js?

I have a restApi of registerUser which creates the user but the issue is that when I target my Api my avatar image cannot upload to the cloudinary so when its not upload to the cloudinary so no public_id and secure_url generate so beacause of this my backend generates an error

:typeerror::cannot convert the undefined or null to object.

I cant find any solution
here is my my Rest Api

const catchAsyncError = require("../middleware/catchAsyncError");
const ErrorHandler = require("../utils/errorhandler");
//const ErrorHandler = require("../middleware/error.js");
const User=require("../models/userModel");
const sendToken=require("../utils/Jwttoken");
const sendEmail=require("../utils/sendEmail")
const crypto=require('crypto')
const cloudinary=require("cloudinary").v2;


exports.registerUser = catchAsyncError(async (req, res, next) => {
  console.log("B1");
  console.log(req.body.avatar);
  let myCloud
   myCloud = await cloudinary.uploader.upload(req.body.avatar, {
    folder: avatars,
    width: 150,
    crop: "scale",
   
  });
  
  /*let myCloud= []; 
 let PID; 
 let PURL; 
   if(req.body.avatar.length > 100){ 
  
     myCloud = await cloudinary.v2.uploader.upload(req.body.avatar,{ 
       folder:"avatars", 
       width:750, 
       crop:"scale", 
     }) 
   } 
   if(req.body.avatar.length > 100){ 
     PID = myCloud.public_id; 
     PURL = myCloud.secure_url; 
   } 
   else{ 
     PID  = "HelloGuys" 
     PURL  = req.body.avatar; 
   }*/
  console.log("B2");
  const { name, email, password } = req.body;
  
  console.log(name);
  console.log(email);
  console.log(password);
 

  const user = await User.create({
    name,
    email,
    password,
    avatar:{
      public_id:myCloud.public_id,
      url:myCloud.secure_url
  }
   
  });
  console.log("B3");
  sendToken(user, 201, res);
});

Cleaner way to handle Navigation in Typescript in React Native

Anyone here who knows a cleaner way then ´{ navigation }:{navigation: NativeStackNavigationProp}` in Typescript in a React Native cli project? I already tried many different things from stackoverflow but they didn’t work.

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import {createNativeStackNavigator, NativeStackNavigationProp} from '@react-navigation/native-stack';
import {Button, Text} from "react-native";

const Stack = createNativeStackNavigator();

export const App = () => {
    return (
        <MyStack/>
    );
};

const MyStack = () => {
    return (
        <NavigationContainer>
            <Stack.Navigator>
                <Stack.Screen
                    name="Home"
                    component={HomeScreen}
                    options={{ title: 'Welcome' }}
                />
                <Stack.Screen name="Profile" component={ProfileScreen} />
            </Stack.Navigator>
        </NavigationContainer>
    );
};

const HomeScreen = ({ navigation }:{navigation: NativeStackNavigationProp<any>}) => {
    return (
        <Button
            title="Go to Jane's profile"
            onPress={() =>
                navigation.navigate('Profile', { name: 'Jane' })
            }
        />
    );
};
const ProfileScreen = ({ navigation, route }:{navigation: NativeStackNavigationProp<any>, route: any}) => {
    return <Text>This is {route.params.name}'s profile!</Text>;
};

Knex.js and NodeJS – Dynamic Endpoints for Select, Insert, Delete, Update

Currently moving a web application over to using Knex to help with issues to do with SQL injection.

Knex has helped us to stop the issue of running different and new queries however we have a point of concern. Currently we have 4 endpoints which look like so:

router.all('/deleteTable', checkAuth, (req, res) => {
if (checkTableWhitelist(req.body.table) === true) {
knexMarsDb(req.body.table)
  .where(req.body.where)
  .del()
  .then((result) => {
    console.log(result);
    res.json({ success: true, message: 'deleted' });
  })
  .catch((error) => {
    res.json({ success: false, message: 'failure' });
    console.log(error);
  });
} else {
res.send(401, 'You are not authorised for this request');
console.log('Table not in whitelist');
}
});

What I understand is that it can be a threat to have this as it means people can delete whatever and how many rows and etc they want to.

Is there a way to make this safer (we have lots of queries running) or is it smarter to just move everything to a hard coded individual endpoint basis?

Thank you