Fill in missing data of maps in json html

I am trying to fill out missing values from my data so that my map will not have empty spaces. It looks a bit weird that the map has holes, as if the countries does not exist. Instead of a new colour, I would like the missing data to be filled with lines in maps.

To make it easier to understand.
Here is my map
mymap

Here is how I want the missing data to be filled with lines
whatIwant

Appreciate the help. I just started to learn how to code in HTML js CSS.

Below is the code in HTML:

<!DOCTYPE html>
<html>
<head>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
</head>
<body>
  <div id="vis"/>
  <script>
    const spec = {
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "title": "Average Years of Schooling around the World (2020)",
  "background": "#F1FAFE",
  "width": 800,
  "height": 400,
  "projection": {"type": "equalEarth"},
  "data": {
    "url": "https://raw.githubusercontent.com/Clairinechendra/FIT3179_HW9/main/ne_110m_admin_0_countries.json",
    "format": {"type": "topojson", "feature": "ne_110m_admin_0_countries"}
  },
  "transform": [
      {
        "lookup": "properties.NAME",
        "from": {
          "data": {
            "url": "https://raw.githubusercontent.com/Clairinechendra/FIT3179_HW9/main/2020_MeanYearsSchooling.csv"
          },
          "key": "Country",
          "fields": ["Years"]
        }
      }
    ],
    "mark": {"type": "geoshape"},
    "encoding": {
      "color": {
        "field": "Years",
        "type": "quantitative",
        "scale": {
          "type": "threshold",
          "domain":  [0, 2, 4, 6, 8, 10, 12],
          "range": ["#fff5f0", "#fee5d9", "#fcbba1", "#fc9272", "#fb6a4a", "#ef3b2c", "#cb181d", "#99000d"]
        }
      },
      "tooltip": [
        {"field": "properties.NAME", "type": "nominal", "title": "Country"},
        {"field": "Years", "type": "quantitative"}
      ]
    },
    "config": {}
  }
    vegaEmbed("#vis", spec, {mode: "vega-lite"}).then(console.log).catch(console.warn);
  </script>
</body>
</html>

This is the code in vegalite:

{
    "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
    "title": "Average Years of Schooling around the World (2020)",
    "background": "#F1FAFE",
    "width": 800,
    "height": 400,
    "projection": {"type": "equalEarth"},
    "data": {
      "url": "https://raw.githubusercontent.com/Clairinechendra/FIT3179_HW9/main/ne_110m_admin_0_countries.json",
      "format": {"type": "topojson", "feature": "ne_110m_admin_0_countries"}
    },
    "transform": [
      {
        "lookup": "properties.NAME",
        "from": {
          "data": {
            "url": "https://raw.githubusercontent.com/Clairinechendra/FIT3179_HW9/main/2020_MeanYearsSchooling.csv"
          },
          "key": "Country",
          "fields": ["Years"]
        }
      }
    ],
    "mark": {"type": "geoshape"},
    "encoding": {
      "color": {
        "field": "Years",
        "type": "quantitative",
        "scale": {
          "type": "threshold",
          "domain":  [0, 2, 4, 6, 8, 10, 12],
          "range": ["#fff5f0", "#fee5d9", "#fcbba1", "#fc9272", "#fb6a4a", "#ef3b2c", "#cb181d", "#99000d"]
        }
      },
      "tooltip": [
        {"field": "properties.NAME", "type": "nominal", "title": "Country"},
        {"field": "Years", "type": "quantitative"}
      ]
    },
    "config": {}
  }

“If the code is in an Astro component, move it to a tag outside of the frontmatter.”

I am trying to import JS for navigation into my Astro project. The error I get is “Browser APIs are not available on the server.

If the code is in a framework component, try to access these objects after rendering using lifecycle methods or use a client:only directive to make the component exclusively run on the client.

See https://docs.astro.build/en/guides/troubleshooting/#document-or-window-is-not-defined for more information.”

The script does use both window and document. However I am unsure how to import the script outside the frontmatter.

Thanks a lot.

I have tried importing the script and am using:


import ‘../js/menu.js’;

inside Header.astro.

However I cannot figure out how to import it outside of the frontmatter.

Thanks

How I can inject html link in the Dom by JS

I had some module in the html,But the link doesn’t work now, so I need to make injection into Dom HTML by JS.
(Example)

<a class=”link” href=”ABC.com”

And put the script before the end of body html.Script will makes changing into the html, JavaScript will search class and clear href and add(toggle) it, it’s possible to do it without {id} of a, search by class ? Thank you friends.

To inject Dom href link , and change it for my link to other resource.

How To create a Role Based Access System On A Web Application Using Tokens in Node.JS?

So Basically what I want to achieve here is to allow logged in users to access pages that their role/access level allows them to while preventing those with a lesser or different roles from accessing the higher access pages (EX. obviously I don’t want students to be messing around with the library’s database and thus this privilege/access to the webpage with that function is reserved for teachers and above) Additionally I also don’t want users that aren’t logged in from accessing anything other than the sign up and login page.

So far I have some basic infrastructure here on the backend which writes the users access level on their token upon logging in:

const express = require('express');
const router = express.Router();
const mysql = require('mysql');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken'); // Import jsonwebtoken for token generation

const connection = require('../database/connector');
const config = require('../Misc/Config');

router.use(bodyParser.json());

// Define the login route
router.post('/login', (req, res) => {
    const { username, password } = req.body;

    // Check if the username and password are provided
    if (!username || !password) {
        res.status(400).json({ error: 'Username and password are required.' });
        return;
    }

    // Query the database to find the user by username
    const sql = 'SELECT * FROM accounts.loginfo WHERE username = ?';
    connection.query(sql, [username], async (error, results) => {
        if (error) {
            console.error(error);
            res.status(500).json({ error: 'An error occurred during login.' });
        } else {
            // Check if the user exists
            if (results.length === 0) {
                res.status(401).json({ error: 'Invalid username or password.' });
            } else {
                // Verify the password
                const user = results[0];
                const passwordMatch = await bcrypt.compare(password, user.password);

                if (!passwordMatch) {
                    res.status(401).json({ error: 'Invalid username or password.' });
                } else {
                    // User is authenticated; create a JWT token and send it back to the client
                    const token = generateAuthToken(user);

                    // Include the user's access level in the response
                    res.status(200).json({ token, access: user.access });
                }
            }
        }
    });
});


// Function to generate a JWT token
function generateAuthToken(user) {
    // Generate a JWT token with user data and a secret key
    const token = jwt.sign({ userId: user.id, username: user.username }, config.secretKey, { expiresIn: '1h' });
    return token;
}

module.exports = router;

Here is the corresponding log in front end:

// Wait for the DOM to load
if (document.readyState == 'loading') {
    document.addEventListener('DOMContentLoaded', ready);
} else {
    ready();
}

function ready() {
    const loginpassword = document.getElementById('loginpassword');
    const togglePasswordButton = document.getElementById('ShowPass');

    togglePasswordButton.addEventListener('click', function () {
        if (loginpassword.type === 'password') {
            loginpassword.type = 'text';
        } else {
            loginpassword.type = 'password';
            togglePasswordButton.textContent = 'Show Password';
        }
    });

    // Add event listener to the Login button
    const loginButton = document.getElementById('Login');

    loginButton.addEventListener('click', () => {
        const username = document.getElementById('loginuser').value;
        const password = document.getElementById('loginpassword').value;

        // Validate user input
        if (!username || !password) {
            alert('Please enter your username and password.');
            return;
        }

        // Create an object with login data
        const loginData = {
            username,
            password,
        };

        // Send a POST request to the backend login route
        fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(loginData),
        })
            .then((response) => response.json())
            .then((data) => {
                if (data.error) {
                    // Display an error alert if login fails
                    alert('Login failed. Please check your username and password.');
                } else {
                    // Store the token securely in localStorage
                    localStorage.setItem('authToken', data.token);
                    
                    // Determine where to redirect based on user's access
                    if (data.access === 'teacher') {
                        window.location.href = '../Teacher-Pages/T-Home.html'; // Teacher dashboard URL
                    } else if (data.access === 'student') {
                        window.location.href = '../Student-Pages/S-Home.html'; // Student dashboard URL
                    } else {
                        alert('Invalid user access.'); // Handle other access types as needed
                    }
                }
            })
            .catch((error) => {
                console.error(error); // Log the error for debugging
                alert('An error occurred during the login process.');
            });
    });
}

Both of these JS does work and i have tested and logged if a token i create when a user logs in, and it does. but i am at a loss how to proceed with the Role Based Access System, i am fairly new to full stack web dev so any help would be appreciated.

Here is my app.js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser');

// Import the signup and login routes
const signupRoute = require('./routes/signup');
const loginRoute = require('./routes/login'); // Import your login route
const logoutRoute = require('./routes/logout')

// Serve static files from the 'public' directory
app.use(express.static('public'));

// Middleware to parse incoming JSON data
app.use(bodyParser.json());

// Use the signup and login routes with their respective prefixes
app.use('/api', signupRoute);
app.use('/api', loginRoute); // Add the login route
app.use('/api', logoutRoute);

// Start the server
const port = process.env.PORT || 3002;
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

Data on navbar only appears after refreshing

Im using vuex for my logIn, but it isnt loading after the callback, and i need to refresh the page

My App.vue

axios.get(process.env.VUE_APP_API_URL + '/api/', config).then((res) => {
    this.$cookies.set('user', res.data);
    Vue.set(this.$store.state, 'user', res.data)
}).catch(function (error) {
    if (error.response) console.log(error.response.data);
});

My store.js

export default new Vuex.Store({
  state: {
    user: {
      id,
      avatar,
      name,
      tag,
      discriminator,
      email
    },
  }
})

My index.vue

<script>
export default {
    name: 'Navbar',
    computed: {
        user () {
            return this.$store.state.user;
        }
    },
}
</script>

Expected:

  1. Before login: Login button;
  2. After login: My username.

What happens:

  1. Before login: Login button;
  2. After login: Login button;
  3. After refresh: My username.

Helps to Challenge

Challengeenter image description here

Implement a javascript app that can calculate the total length of iron bars required to create a gate. The gate will have an alternating design of empty rows and rows filled with circles (please note the design starts with an empty row from top). Design should be symmetrical. If a symmetrical design cannot be generated for given inputs, the programme should identify and show a message to the user.

Note:
Bar will have a thickness of 10cm;
Take this value into account when doing calculations.
Minimise the waste of bars as much as possible.

Inputs:
width and height of gate (in cm)

Max height percentage of each row (ex. If the gate height is 100cm and the max row height is 10%, then each
row can be a max 10cm in height).

Return type should be a string.
calculateTotalBarLengthReq(500, 500, 20, ironBarThickness) should return “Total bar length requirement = 7021.59cm.”

calculateTotalBarLengthReq(100, 100, 20, ironBarThickness) should return “Total bar length requirement = 1308.32cm.”

The answer should be valid for any given input.

update to the bellow code

function calculateTotalBarLengthReq(gateWidth, gateHeight, rowHeightPercentage, barThickness) {
return false;
}
const ironBarThickness = 10;
calculateTotalBarLengthReq(500, 500, 20, ironBarThickness);

Then i input correct code#

function calculateTotalBarLengthReq(gateWidth, gateHeight, rowHeightPercentage, barThickness) {
// Calculate the length of vertical bars (columns)
const verticalBarLength = gateHeight * 2;

// Calculate the size of each row
const rowSize = gateHeight * rowHeightPercentage * 0.01;

// Calculate the number of horizontal bars (rows)
const numOfHorizontalBars = (gateHeight / rowSize) + 1;

// Calculate the length of horizontal bars
const horizontalBarLength = (gateWidth - barThickness * 2) * numOfHorizontalBars;

// Calculate the gap between rows
const rowGap = (gateHeight - numOfHorizontalBars * barThickness) / (numOfHorizontalBars - 1);

// Calculate the number of circles in a row
const numOfCirclesInRow = gateWidth / rowGap; //this may not natural number (float value)
// const numOfCirclesInRow = Math.floor(gateWidth / rowGap); // this will give natural number (integer value)

// Calculate the number of alternate rows with circles
const numOfRowsWithCircles = Math.floor((numOfHorizontalBars - 1) / 2);

// Calculate the total number of circles
const totalNumOfCircles = numOfCirclesInRow * numOfRowsWithCircles;

// Calculate the radius of each circle
const radius = rowGap / 2;

// Calculate the circumference of each circleyour text
const circumference = 2 * radius * Math.PI;

// Calculate the total length of iron bars required
const totalBarLength = verticalBarLength + horizontalBarLength + circumference * totalNumOfCircles;

return Total bar length requirement = ${totalBarLength.toFixed(2)}cm;
}

const ironBarThickness = 10;
console.log(calculateTotalBarLengthReq(500, 500, 20, ironBarThickness));
console.log(calculateTotalBarLengthReq(100, 100, 20, ironBarThickness));

after input code programme said incorect plese helps me what i do get the correct answer

How to remove whitespace of a substring

I am working on a functional programming exercise and I was asked to replace all whitespaces in the string with an hyphen. If I have a string like This is a title, the output should be this-is-a-title.

Now, all cases as described before work but I have an edge case string like this: Peter Is Coming. I would like to strip out the whitespace that is before the Coming so that my final output is peter-is-coming which would be the equivalent output for when I have an initial string of Peter is Coming with no redundant whitespace. I was able to do that of before Peter with ease using the trim method. How do I go about this edge case’s?

Note: One of the constraints is that there shouldn’t be the use of the replace method.

Thanks.

My code:

function urlSlug(title) {

  const url = title.trim().toLowerCase();
  console.log(url);

  const splitURL = url.split("");
  // console.log(splitURL);

  const urlArr = [];

  const filtered = splitURL.filter(val => {
    if (/s/.test(val)) {
      
      urlArr.push("-");
    }
    
    else {
      urlArr.push(val);
    }
  });

  return console.log(urlArr.join(""));

}

urlSlug("A Mind Needs Books Like A Sword Needs A Whetstone"); // a-mind-needs-books-like-a-sword-needs-a-whetstone
urlSlug("Hold The Door"); // hold-the-door 
urlSlug(" Peter is  Coming"); // peter-is--coming 

// The last output is what I get but not what I want to achieve.

Navigate javascript form via Python Request

I am trying to scrap data from a webpage that shows a limited amount of data, and requires the user to click a button to navigate to the next set of records. The webpage achieves that by sending GET requests to itself.

I tried to write a code in Python that would send a GET request to the page hoping to get the next set of results, and write a for loop to retrieve subsequent results, but I am always getting the initial sets (apparently the website is ignoring my params)

This is the website I am targeting:
https://portaltransparencia.procempa.com.br/portalTransparencia/despesaLancamentoPesquisa.do?viaMenu=true&entidade=PROCEMPA

This is my code:

url = "https://portaltransparencia.procempa.com.br/portalTransparencia/despesaLancamentoPesquisa.do?viaMenu=true&entidade=PROCEMPA"

r_params = {
    "perform": "view",
    "actionForward": "success",
    "validate": True,
    "pesquisar": True,
    "defaultSearch.pageSize":23,
    "defaultSearch.currentPage": 2
    }
page = requests.get(url, params=r_params)

I expected that this generated a response with data from the 2nd page, but it is responding that from the first page.

Nextjs13 does not recognize auth route and give 404 error

I am working on a project that is based on NextJs v13 and uses Strapi v4 as the backend. I have a separate layout for the site, login, and dashboard. I worked on the login section and used NextAuth for authentication. But when I submit the login form, it does not recognize the authentication route and redirects to the http://localhost:3000/api/auth/error route.
The error
GET http://localhost:3000/api/auth/error 404 (Not Found)

This is my project folder structure.

enter image description here

This is the submission code.

 const onSubmit = async (e) => {
    e.preventDefault();
    const result = await signIn('credentials', {
      redirect: false,
      email: e.target.email.value,
      password: e.target.password.value,
    });
    if (result.ok) {
      router.replace('/');
      return;
    }
    alert('Credential is not valid');
  };

This is the […nextauth].j code:

import NextAuth from 'next-auth';
import CredentialsProvider from 'next-auth/providers/credentials';
import { signIn } from '../../../../services/auth';

export default NextAuth({
  providers: [
    CredentialsProvider({
      name: 'Sign in with Email',
      credentials: {
        email: { label: 'Email', type: 'text' },
        password: { label: 'Password', type: 'password' },
      },
      async authorize(credentials, req) {
        
        if (credentials == null) return null;
       
        try {
          const { user, jwt } = await signIn({
            email: credentials.email,
            password: credentials.password,
          });
          return { ...user, jwt };
        } catch (error) {
          // Sign In Fail
          return null;
        }
      },
    }),
  ],
  callbacks: {
    session: async ({ session, token }) => {
      session.id = token.id;
      session.jwt = token.jwt;
      return Promise.resolve(session);
    },
    jwt: async ({ token, user }) => {
      const isSignIn = user ? true : false;
      if (isSignIn) {
        token.id = user.id;
        token.jwt = user.jwt;
      }
      return Promise.resolve(token);
    },
  },
});

And this the auth.js code:

import axios from 'axios';

const strapiUrl = process.env.NEXT_PUBLIC_STRAPI_API_URL;

export async function signIn({ email, password }) {
  const res = await axios.post(`${strapiUrl}/api/auth/local`, {
    identifier: email,
    password,
  });
  return res.data;
}

I searched alot to solve this problem but unfotunately I could not find any solution for this.

Code completion for HTML DOM in JavaScript string literals in IntelliJ / PHPStorm

I am using a custom framework that shortens document.getElementById like so:

function $$(elementId){ return document.getElementById(elementId); }
    
$$("someDOMid").style.color = "#336699";

I am using JetBrains IntelliJ PHPStorm (although this would apply to WebStorm as well I would presume.

I note that in the IDE, code completion for HTML DOM ids shows up for document.getElementId and also JQuery’s $(“#someId”) function.

How do I get PHPStorm to recognize my framework’s wrapper as the same as the native call, and thus get those very handy DOM code completions?

React form inputs not clickable

I’m having problems with clicking my form inputs… I can only click the first one ate the top, the rest… it like they are disabled or something (But the second one is clickable if I decrease the width of my browser which is really weird)… this is my code.

import {useState} from 'react';


const Modal = ({open, close, submitForm}) => {

    const [task, setTask] = useState('');
    const [cat, setCat] = useState('');
    const [deadline, setDeadline] = useState('');

    const handleSub = (e) => {
        e.preventDefault();
        
        submitForm({'task': task, 'cat': cat, 'ddln': deadline});

        setTask('');
        setCat('');
        setDeadline('');
    }
    if(!open){
        return (

            <div className="myOverlay">
                <div className="myModal">
                    <strong onClick={close}>X</strong><br />
                    <form method="post" onSubmit={handleSub} >
                      <div className="form-group">
                        <label htmlFor="exampleInputEmail1">Task</label>
                        <input type="text" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter task" name="task" value={task} onChange={(e) =>setTask(e.target.value)}/>
                      </div><br />
                      <div className="form-group">
                          <select className="form-control" defaultValue={cat} id="inlineFormCustomSelectPref" name="cat" onChange={(e) =>setCat(e.target.value)}>
                            <option>Task category</option>
                            <option value="Tech">Tech</option>
                            <option value="Marketing">Marketing</option>
                            <option value="Financial">Financial</option>
                            <option value="Admin">Admin</option>
                          </select>
                      </div>
                      <br />
                      <div className="form-group">
                        <label htmlFor="exampleInputPassword1">Deadline</label>
                        <input type="date" className="form-control" id="exampleInputPassword1" placeholder="Deadline" name="ddln" value={deadline} onChange={(e) =>setDeadline(e.target.value)}/>
                      </div>
                      <div className="form-check">
                        <input type="checkbox" className="form-check-input" id="exampleCheck1" />
                        <label className="form-check-label" htmlFor="exampleCheck1">Make Task Active</label>
                      </div> <br />
                      <input type="submit" className="btn btn-dark" value="Submit"/>
                    </form>
                </div>
            </div>

        );
    }
}

export default Modal

That is my form controller and it is a modal.

import { Outlet } from 'react-router-dom';
import { useState } from 'react';
import Sidebar from './Sidebar';
import Modal from './Modal';

import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';


const Root = () => {
  const [ modal, setModal ] = useState(true);

  const [ page, setPage ] = useState('home');

  const addFormHandle = async (formData) => {

          const res = await fetch('http://127.0.0.1:8000/api/tasks/add', {

              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify(formData),

          })

          if (res.ok) {
            //throw new Error('Network response was not ok');

            toast.success('Task added successfully', {
              position: "top-right",
              autoClose: 5000,
              hideProgressBar: false,
              closeOnClick: true,
              pauseOnHover: true,
              draggable: true,
              progress: undefined,
              theme: "dark",
            });
          }
          else
          {
            toast.error('Task failed to add please check network connection!!!', {
            position: "top-right",
            autoClose: 5000,
            hideProgressBar: false,
            closeOnClick: true,
            pauseOnHover: true,
            draggable: true,
            progress: undefined,
            theme: "dark",
            });
          }
          setModal(true);
      //console.log(formData);
      
  }

      
  return(

    <div className='row'>

      <div className="col-md-2">
        <Sidebar page={setPage}  />

      </div>

          <div className="col-md-10">
            <main className="main-sec container">
                <Outlet />
            </main>

            <Modal open={modal} close={()=>setModal(true)} submitForm={addFormHandle} />
      
          </div>

          <div className="myContainer">
              <button className="btn btn-dark fixed-button" onClick={()=>setModal(false)}>Add Task</button>
          </div>

          
      </div>
    )
}

export default Root;

This is my root controller… I used react-toastify on it (the problem kind of started the same time I added it… but was kind of on and off until it was just on… it was weird I event thought my pc was crashing so I restarted it but the problem remained).

import { createBrowserRouter, createRoutesFromElements, Route, Outlet, RouterProvider} from 'react-router-dom';
import { useState } from 'react';
import Sidebar from './Components/Sidebar';
import Cards from './Components/Main/Cards';
import Table from './Components/Main/Table';
import Modal from './Components/Modal';
import Deadlines from './Components/Deadlines';
import Home from './Components/Home';
import Tasks from './Components/Tasks';
import Inoives from './Components/Inoives';
import Root from './Components/Root';
import DataLoada from './DataLoada.js';
import { ToastContainer } from 'react-toastify';

function App() {

  const router = createBrowserRouter(
      
      createRoutesFromElements(
          <Route path="/" element={<Root />}>
              <Route index element={<Home />} />
              <Route path="/deadlines" element={<Deadlines />} />
              <Route path="/tasks" element={<Tasks />} loader={DataLoada} />
              <Route path="/invoices" element={<Inoives />} />
          </Route>
      )

  )

  return (
    <>
      <RouterProvider router={router} />
      <ToastContainer />
    </>
  );
}

export default App;

This is my App.js file… I added the toast container here.

I tried looking at the backend. I thought maybe the problem was it… I don’t think it was.

about forwardRef , I can’t understand the second use case

Case I, I can accept those code as the picture shows, we define the ref in parent component and pass it to child component

enter image description here

enter image description here

Case II,the component Input was defined as following ,

import * as React from 'react'

import { cn } from '@/lib/utils'

export interface InputProps
  extends React.InputHTMLAttributes<HTMLInputElement> {}

const Input = React.forwardRef<HTMLInputElement, InputProps>(
  ({ className, type, ...props }, ref) => {
    return (
      <input
        type={type}
        className={cn(
          'flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',
          className
        )}
        ref={ref}
        {...props}
      />
    )
  }
)
Input.displayName = 'Input'

export { Input }

this was used in another file chat.js, the episoid as follwing

import { Input } from './ui/input'

<Input
        value={previewTokenInput}
        placeholder="OpenAI API key"
        onChange={e => setPreviewTokenInput(e.target.value)}
/>

something confused me , the parent didn’t define Ref variable, and use directly . Is this a new approach of using forwardRef ?

the codes are from https://github.com/vercel-labs/ai-chatbot,

  • /component/chat.tsx
  • /component/ui/input.tsx

cdkDrag free drag and drop not working inside cdkDropList using Angular, Angular material drag and drop

I tried to drag and drop an item using cdkDrag (free drag and drop anywhere) and it’s working without cdkDropList. I can able to swap item between two container(Available Services <=> Dropbox Container). But free drag and drop feature inside Dropbox Container not working when tried with cdkDropList as parent container using Angular, Angular material drag and drop.

Expected result:
User can able to drag and drop item anywhere inside cdkDropList Dropbox Container.

Stackblitz Link

https://stackblitz-starters-djbrtx.stackblitz.io/

I tried with following code flow

Html Template

<div class="container">
    <section class="service-container">
        <div class="row" cdkDropListGroup>
            <div class="col-2 available-service text-center">
              <h4 class="pt-3">Available Services</h4>
          
              <div
                cdkDropList
                [cdkDropListData]="todo"
                class="service-list"
                (cdkDropListDropped)="drop($event)">
                <div class="service-box" *ngFor="let item of todo; let i = index" 
                cdkDrag
                >
                    {{item}}
                </div>
              </div>
            </div>
          
            <div class="col">
              <h2>Workspace</h2>
              <div class="service-boundary"
              cdkDropList
              [cdkDropListData]="done"
              (cdkDropListDropped)="drop($event)"
              >
                <div *ngFor="let item of done; let i = index" class="service-box" 
                  cdkDrag
                  >
                    <strong>
                      {{item}}
                    </strong>
                    </div>
              </div>
            </div>
        </div>
    </section>
</div>
  

ts file

import { ChangeDetectorRef, Component } from '@angular/core';
import {
  CdkDragDrop,
  moveItemInArray,
  transferArrayItem,
} from '@angular/cdk/drag-drop';
import { BehaviorSubject } from 'rxjs';

@Component({
  selector: 'app-workflow-dashboard',
  templateUrl: './workflow-dashboard.component.html',
  styleUrls: ['./workflow-dashboard.component.scss']
})
export class WorkflowDashboardComponent {
  todo:any = ['One', 'Two', 'Three'];

  done: any = ['Four'];
  constructor(private changeDetectionRef: ChangeDetectorRef) {}

  drop(event: CdkDragDrop<any[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(
        event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex,
        );
        
    }
  }


}

SCSS

.service-container {
    border: solid 1px #ccc;
    margin-bottom: 25px;
    .available-service {
      border: solid 1px #ccc;
      margin: 15px 0 15px 25px;
    }
  }

  .service-list {
    min-height: 90%;
    background: white;
    border-radius: 4px;
    overflow: hidden;
    display: block;
    position: relative;
    
  }
  .service-box { 
    margin: 7px 7px;
    width: 150px; 
    height: 50px;
    border: solid 1px #ccc;
    color: rgba(0, 0, 0, 0.87);
    cursor: move;
    display: inline-flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    background: #fff;
    border-radius: 4px;
    margin-right: 25px;
    position: relative;
    z-index: 1;
    box-sizing: border-box;
    transition: box-shadow 200ms cubic-bezier(0, 0, 0.2, 1);
    box-shadow: 0 3px 1px -2px rgba(0, 0, 0, 0.2),
                0 2px 2px 0 rgba(0, 0, 0, 0.14),
                0 1px 5px 0 rgba(0, 0, 0, 0.12);
    
    
                &:active {
                  box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
                  0 8px 10px 1px rgba(0, 0, 0, 0.14),
                  0 3px 14px 2px rgba(0, 0, 0, 0.12);
                }
  }
  .cdk-drag-preview {
    box-sizing: border-box;
    border-radius: 4px;
    box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
                0 8px 10px 1px rgba(0, 0, 0, 0.14),
                0 3px 14px 2px rgba(0, 0, 0, 0.12);
  }
  
  .cdk-drag-placeholder {
    opacity: 0;
  }
  
  .cdk-drag-animating {
    transition: transform 250ms cubic-bezier(0, 0, 0.2, 1);
  }

  .service-boundary {
    height: 100%;
  }

pm2 -i flag runs app instances in fork mode rather than cluster mode

I am using pm2 version 5.3.0

I want to run several instances of my application in cluster mode using CLI.

I use the command

pm2 start node -n my-app -i 2 -- build

But when I provide -i flag, it starts a number of instances in fork mode, not in cluster mode.

In their documentation they say using -i flag with start runs the app in cluster mode. This contradicts another part of the documentation where they mention adding a config file as they say by default pm2 will start the processes in fork mode (which what happens) and I need to set exec_mode field to run the app in cluster mode.

So, is there a way to use the pm2 start command from cli AND specify the execution mode as cluster mode? I can’t seem to find any flag to set that.