what is XXX encode method in javascript

there is a string like :

"2311222241164620127275337153163715226626430024"

when I log it in js console, its decoded form is:

'x99Rx94N&x10W½ßks9*¶´Àx14'

I’ve searched a lot but couldn’t find what encode/decode method is, in js its automatically converted. I need to converted this string in python

What domain driven design mean for Javascript applications on the client side?

What domain driven design mean for Javascript applications on the client side?

I want to build an application based on ddd architecture with javascript.

The framework I’ll use to implement the application is not important to me because I want to learn how to organize the code according to ddd architecture.

Let’s decide module is folder.

My application is have login, notifications, reports, crud operations, and shared stuff, and each of them have api-server logic, ui components, services and crud.

For example auth folder contains the following

 api               --> server logic
 domain            --> the domain itself. the bl: handle the data, use of http.
 feature-login     --> the page itself containers of ui elements. 
 feature-register  --> the page itself containers of ui elements.
 ui                --> ui elements for auth domain
 utils             --> utils functions for auth domain

same goes for notification folder:

 api               --> server logic
 domain            --> the domain itself. the bl: handle the data, use of http.
 feature-create    --> the page itself containers of ui elements. 
 feature-list      --> the page itself containers of ui elements.
 ui                --> ui elements for notification domain
 utils             --> utils functions for notification domain

And reports:

 api               --> server logic
 domain            --> the domain itself. the bl: handle the data, use of http.
 feature-dashboard    --> the page itself containers of ui elements. 
 feature-search      --> the page itself containers of ui elements.
 feature-edit      --> the page itself containers of ui elements.
 feature-view      --> the page itself containers of ui elements.
 ui                --> ui elements for report domain
 utils             --> utils functions for report domain

This is how I build my application.

So Where is my problem here?

According to ddd the domain is shouldn’t be share inside other domains. because it’s create decoupling.

But in the report domain I need to get the user from auth domain and need to display notification from notification domain.

This is makes decoupling between the domains.

So it’s lead me to realize maybe I don’t defined my domain correctly? my folder structure is matching the ddd principle? if no how I do I decide what is domain and what is not?

How to check if key exists on mongoose document?

I have a User Model and recently added some key to it. This means that existing users will not have this key initially and new users do. Now I have a route where I want to check if the particular key exists on the user object so that I can add it if it returns false.

This is my route currently:

router.post("/new-application", verifyUser, (req, res) => {
  const { application } = req.body;
  User.findById(req.userId)
    .then((user) => {
      if (user.hasOwnProperty("applications")) {
        console.log("has applications");
      } else {
        console.log("has not applications");
        user["applications"] = initialApplications;
      }
      user.save().then((updatedUser) => {
        // console.log(updatedUser);
      });
    })
    .catch((err) => {
      console.log("err fetching user: ", err);
      res.end();
    });
});

The problem is that if (user.hasOwnProperty("applications")) always returns false even after I added it to the user. I also tried if("applications" in user). That also does not work.

So how can I check if a key or field exists on a Mongoose object.

Creating a Family Tree Maker/Editor with React

This is a really open question, but I have no idea how to go about this idea and I’m quite stuck.

I wanted to create a family tree maker, where the user can freely add new members of his family, and it is displayed neatly in a family tree chart. I imagined creating a node component for each family member, and somehow linking all the node components into a comprehensible Family Tree Chart. But the truth is, I have no idea how to do this linking.

Are there any packages that can help me out with this? I initially thought about using react-sortable-tree, but I wouldn’t be able to implement spouses, only children.

When Header is added the Protected Route is not getting rendered

I am doing a simple application which has a protected route.

The code goes like:

function App() {


return (
    <>
      <Router>
        <Header />
        <Routes>
          <Route path="/" element={<Home />} />
          <Route
            path="/protected"
            element={
              <PrivateRoute>
                <ProtectedExample />
              </PrivateRoute>
            }
          />
          <Route path="/sign-in" element={<Login />} />
        </Routes>
      </Router>
    </>
  );
}

Private Route is :

import { Navigate } from "react-router-dom";
import { useAuthStatus } from "../hooks/useAuthStatus";
import Spinner from "./Spinner";

const PrivateRoute = ({ children }) => {
  const { loggedIn, checkingStatus } = useAuthStatus();

  if (checkingStatus) {
    return <Spinner />;
  }
  return loggedIn ? children : <Navigate to="/sign-in" />;
};

export default PrivateRoute;

Protected Route

import React from "react";

const ProtectedExample = () => {
  return <div>ProtectedExample</div>;
};

export default ProtectedExample;

Header.js

import React from "react";
import { Container, Nav, Navbar } from "react-bootstrap";
import { Link } from "react-router-dom";

const Header = () => {
  return (
    <Navbar bg="light" variant="light" fixed="top">
      <Container>
        <Navbar.Brand>
          <Link to="/">Vivans</Link>
        </Navbar.Brand>
        <Nav className="me-auto">
          <Link to="/sign-in" className="me-4">
            Login
          </Link>
          <Link to="/protected">ProtectedRoute</Link>
        </Nav>
      </Container>
    </Navbar>
  );
};

export default Header;

When i remove the header component in App.js

The output is :
enter image description here

But when i add header component in App.js

The output is :
enter image description here
It doesn’t return ProtectedExample as expected to be .

Why?

How to convert js code of click to clipboard button into jquery

I want to convert my peice of code into jquery and also i want to add setTimeout function but not able to set that in a code. please help me.

Below is my html code

<blockquote>
  <p id="myInput">Lines of code Here</p>
<button id="btn1">Copy</button>
 </blockquote>

Js code

<script>
  function copyFunction() {
  const copyText = document.getElementById("myInput").textContent;
  const textArea = document.createElement('textarea');
  textArea.textContent = copyText;
  document.body.append(textArea);
  textArea.select();
  document.execCommand("copy");
  btn1.innerText = "copied";
    textArea.remove();
}
document.getElementById('btn1').addEventListener('click', copyFunction);
  </script>

I want 1 line o/p for 2 search conditions. One line o/p for search w/o company name is working fine but search with specific name is not working

<?php

    include 'config.php';

    if(!empty($_GET['companyname']) && !empty($_GET['designation']))
    {
        $name = !empty($_GET['companyname']) ? strtolower(trim($_GET['companyname'])) : '';
        $designation = !empty($_GET['designation']) ? strtolower(trim($_GET['designation'])) : '';
        $conditions = " LOWER(companyname) ='$name'";
        if(!empty($name)) {
            $conditions .= " AND LOWER(companyname) ='$name' ";
        }

        $sqlSalary = "SELECT companyname,designation  max(annualctc) as MaxSalary, min(annualctc) as MinSalary , AVG(annualctc) as avgSalary FROM `salery_calculator` WHERE $conditions group by companyname";
        $resultSalary = mysqli_query($conn, $sqlSalary);
        $row_count = mysqli_num_rows( $resultSalary );
        if($row_count > 0){
            $html = "<table class='table table-bordered'><thead><tr><th>Company Name</th><th>Designation</th><th> Max Salary</th><th>Middle Salary</th><th>Min Salary</th></tr></thead><tbody>";
            while ($p_row = mysqli_fetch_array($resultSalary)) {
                $html .= "<tr><td>" . ucwords($name) . "</td><td> " . ucwords($designation) . "</td><td> " . $p_row['MaxSalary'] . "</td><td>" . round($p_row['avgSalary']) . "</td><td>" . $p_row['MinSalary'] . "</td></tr>";
            }
            $html .="</tbody></table>";
            $errorcode = 200;
        } else{
            $html = "<p>No record found on search criteria</p>";
            $errorcode = 105;
        }
    }

    else{
        $html = "<p>Required field missing</p>";
        $errorcode = 105;
    }
    if(empty($_GET['companyname']) && !empty($_GET['designation'])){

        $designation = !empty($_GET['designation']) ? strtolower(trim($_GET['designation'])) : '';
        $conditions = " LOWER(designation) ='$designation'";
        if(empty($name) && !empty($designation)) {
            $conditions .= " AND LOWER(designation) ='$designation' ";
        }

        $sqlSalary = "SELECT designation, max(annualctc) as MaxSalary, min(annualctc) as MinSalary , AVG(annualctc) as avgSalary FROM `salery_calculator` WHERE $conditions group by designation and companyname";
        $resultSalary = mysqli_query($conn, $sqlSalary);
        $row_count = mysqli_num_rows( $resultSalary );
        if($row_count > 0){
            $html = "<table class='table table-bordered'><thead><tr><th>Designation</th><th> Max Salary</th><th>Average Salary</th><th>Min Salary</th></tr></thead><tbody>";
            while ($p_row = mysqli_fetch_array($resultSalary)) {
                $html .= "<tr><td> " . ucwords($designation) . "</td><td> " . $p_row['MaxSalary'] . "</td><td>" . round($p_row['avgSalary']) . "</td><td>" . $p_row['MinSalary'] . "</td></tr>";
        }    $html .="</tbody></table>";
            $errorcode = 200;
        } 
        else{
            $html = "<p>No record found on search criteria</p>";
            $errorcode = 105;
        }
    }

    else
    {
        $html = "<p>Required field missing</p>";
        $errorcode = 105;
    }






    echo json_encode(array('error_code'=>$errorcode, 'message'=>$html));
?>

Firebase storage delete image by downloadURL V9

I’m trying to delete an image from Firebase storage in React Native by downloadURL. Also i’m using web V9.
Writing down most essential chuncks of code:

import {
  deleteObject,
  getStorage,
  ref
} from "firebase/storage";

...
// DownloadURL
const photo = "https://firebasestorage.googleapis.com.... ";

const storage = getStorage();
...
const storageRef = ref(storage, photo);
deleteObject(storageRef)
  .then(() => {
    console.log("File deleted successfully");
  })
  .catch((error) => {
    console.log(error.message);
  });

My code is inspired from here and I got this error:

[Unhandled promise rejection: FirebaseError: Firebase Storage: The
operation ‘deleteObject’ cannot be performed on a root reference,
create a non-root reference using child, such as .child(‘file.png’).
(storage/invalid-root-operation)]
I’m little confused.

why is react native maps not working after build in expo

I have created a react native application with expo clii. In there I am using react-native-maps.With expo app It was very worked. But after building the standalone app and when I try to open it it did not navigate to that component.It mean when I click on the location tab it restart the app.This is my that component code.

iframe receives message from parent window but console.log returns [object MessageEvent]

I’m sending messages from the parent window to the iframe, but when I log the message inside the iframe, it returns [object MessageEvent].

I’ve tried to parse it with JSON.parse and it produces a parse error, but when I try JSON.stringify it prints the string representation of the message correctly.

Can I access the object without doing JSON.strinfigy?

From the Parent window, I’m not sending JSON string. I’m sending an object.

Below is my code in parent window

frame.contentWindow.postMessage({
  action: 'start', 
  config: {onlyWithImages}
}, '*')

and inside the iframe I’ve this code

window.addEventListener('message', e => {
  let data = e.data
  console.log(data) //[object MessageEvent]
}

how to cancel pop up audio in javascript

hello I’m new to code and javascript I’m creating a clock with timer. the countdown is done well with an alarm and a pop up when the timer reaches zero. only I can’t turn off the alarm when I close the pop up it opens in a loop. i need help please

let departInput = document.querySelector('#times');
let subButton = document.querySelector('#sub')


subButton.addEventListener('click', event => {
  let temps = (departInput.value)*60;
  var timerElement = document.getElementById("MyTimerDisplay")
  setInterval(() => {
  let minutes = parseInt(temps / 60, 10)
  let secondes = parseInt(temps % 60, 10)

  minutes = minutes < 10 ? "0" + minutes : minutes
  secondes = secondes < 10 ? "0" + secondes : secondes

  timerElement.innerText = `${minutes}:${secondes}`
  temps = temps <= 0 ? 0 : temps - 1
  if(minutes == 0 && secondes == 0){
    var snd = new Audio('clock.mp3');
    snd.play();
    alert("cest l'heure")

    }
  }, 1000)

});
  

Making and connecting hexagons on a rectangle grid

I am creating a pathfinding application and I want to connect every hexgon(H) to its adjacent hexagons. The grid is a rectangle but it is populated with hexagons. The issue is the code right now to connect these hexagons is lengthy and extremely finicky. An example of what i am trying to achieve is:
enter image description here

The issue is that the connections between say one hexagon and its neighbours (range from 2-6 depending on their placement in the grid) is not working properly. An example of the code i am using right now to connect a hexagon with 6 neighbours is:

        currentState.graph().addEdge(i, i + 1, 1);
        currentState.graph().addEdge(i, i - HexBoard.rows + 1, 1);
        currentState.graph().addEdge(i, i - HexBoard.rows, 1);
        currentState.graph().addEdge(i, i + HexBoard.rows +1, 1);
        currentState.graph().addEdge(i, i + HexBoard.rows , 1);

The graph is essetialy the grid, addEdge adds a connection from src ->dest with cost(c) in order. Is there any algorithm or way to make my code less bulky ? (right now it is polluted with if-else clauses)?
The site which inspired me :https://clementmihailescu.github.io/Pathfinding-Visualizer/#

Reemplazar el value de un input carácter por carácter con lo que ingresa el usuario

Espero que puedan ayudarme.
Intento reemplazar el formato predefinido de un input que tengo por el valor que el usuario ingresa. La idea es que reemplace la cadena carácter por carácter empezando siempre desde el inicio pero no lo he logrado hacer.
Este es mi input:

<div class="col-md-4">
                                <label for="inputName5" class="form-label">Téléphone</label>
                                <input type="text" class="form-control" id="tel" value="xxxxxxxx" pattern="[0-9]{8}" minlength="8" maxlength="8">
                            </div>

Lo que intenté hacer con JavaScript es el siguiente:

<script>
    var input = document.querySelector('input');
    var log = document.getElementById('tel');

 for (var i=0; i<log.length; i++){
     log.addEventListener('input', updateValue);
    function updateValue(e) {
        log[i].textContent.replace(e.target.value);
    }}
</script>

pero no me funcionó. ¿Alguien de buena fe que me pueda apoyar? Gracias de antemano.

A code to Find the Area of a circle in Java

I’m to write a code in Java for the area of a circle. This is how it should be;
First instruction should ask the inputter if it has the radius or the diameter of the circle …
Then, it continues to calculate the area based on the radius or diameter either.
I’m just a beginner at the tertiary level please help me out …

How do I get mongoose to await the creation of documents before disconnecting

I can’t seem to find an answer anywhere as to what I’m doing wrong here. I just want to wait for my for-loop to finish seeding my database before disconnecting

database.js

import mongoose from 'mongoose';

mongoose.connect(process.env.MONGO_URL || 'mongodb://localhost/db', { useNewUrlParser: true, useUnifiedTopology: true });

const exampleSchema = new mongoose.Schema({
    name: String,
    img: String,
});

const Example = mongoose.model('Example', exampleSchema);

export default Example;

seed.js

import axios from 'axios';
import mongoose from 'mongoose';
import Example from './database.js';

const seedExample = async () => {
    const { data } = await axios.get(api placeholder);

  for (let i = 0; i < data.length; i++) {
    await Example.create({
      name: data[i].name,
      img: data[i].img,
    }, (err, example) => {
      if (err) return err
    })
  }
};

await seedExample();
mongoose.disconnect()

If I set a timeout then disconnect the documents are created but otherwise, it just closes before the function even completes. I’ve tried putting the disconnect at the end of the for loop as well.

Go easy on me I’m a noob, any advice all around very welcome. Thanks!