Lerna / Nx / Turborepo or other monorepo systems for non-js apps (php)

I have repository with /frontend (JS/Vue) and /backend (PHP) and docker-compose.yml for development. But now I need to add another JS frontend that will be sharing some components, libs etc. I do not want to repeat code, so I found that I can use many tools for this like lerna, nx, turborepo and more for managing monorepo with shared packages.

Problem is that all tutorials and example repos I found are based on 100% JS repos, like React on front + Nest on back etc.

So question – using for ex. nx makes sense on repos with multiple languages, just to leverage it on JS packages? If yes, how directory structure should look like? Or maybe there are better monorepo tools that are designed for multiple languages, not just JS?

Calculate the No. of possible ways two chess pieces can be placed [closed]

This was one of the questions asked in a mock test. If any one has seen this problem somewhere else or know the solution, please help me out.

A famous chess grandmaster was analyzing one of his games in his head and… he suddenly forgot the positions of two important pieces.

However, he is sure about some facts:

  • the location of the first piece on the board is (x1; y1) and xl1 <=
    x1 <= xr1, yl1 <= y1 <= yr1.
  • the location of the second piece on the board is (x2; y2) and xl2
    <= x2 <= xr2, yl2 <= y2 <= yr2.
  • the chessboard cells corresponding to the pieces are of the same
    color.

In other words, he doesn’t remember the exact positions of the pieces, however, for every piece, he is sure about the part of the board where it can be. Part of the board here is just a rectangular submatrix described by 4 coordinates.

Note: obviously, two pieces can’t be in the same location.

Now the grandmaster is wondering, how many placements of this two pieces are possible if he remembers everything correctly?

Input Format:

  • The first line contains an integer, x1, denoting the minimum possible
    row of the first piece.
  • The next line contains an integer xr1, denoting the maximum possible
    row of the first piece
  • The next line contains an integer, yl1, denoting the minimum possible
    column of first piece
  • The next line contains an integer yr1, denoting the maximum possible
    column of the first piece.
  • The next line contains an integer, xl2, denoting the minimum possible
    row of the second piece.
  • The next line contains an integer, xr2, denoting the maximum possible
    row of the second piece.
  • The next line contains an integer, y12, denoting the minimum or
    possible the second piece.
  • The next line contains an integer, yr2, denoting the maximum possible
    column of the second piece.

Sample Input:
Image with sample input and output

Thanks

I have been trying in the past few days to solve this problem and i can’t

Whenever I add an addEventListener, or a toggle in javascript, I get ”can’t read **** of null” or ”can’t read of undefined”. I tried many different ways to solve it, deleting the javascript file and recreating it, putting everything inside an “addEventListener(‘DOMContentLoaded, …’), moving the javascript code in html file. Nothing works, I don’t know why. I tried all the ways that they say on the internet that work.

enter image description here

(In what manner should I) feed Excel file into MySQL?

Disclaimer, this not looking for HOW (yet), but asking which method is safer and/or more efficient. This is possibly subjective.

I can see 2 processes when reading an excel file and feeding it into a MySQL database. Either:

  1. Convert whole file into one Insert statement
  2. Insert one row at a time

I thought about #1, and can see it working, but I also have a step after this: I need to normalize (separate into multiple connected tables) the content.

If I insert one row at a time, I can weave the normalization within the insertion as a stored procedure.

If I insert as a giant sql file, I just need to clean up afterwards cells of the same values and columns.

While my tables aren’t millions of rows, I still am just one person, so any way to make it easier for me would be appreciated.

So, which sounds better? Clean up a giant file? or Loop the file’s rows one at a time?

Is it fine to use the same mkcert certificate for both your frontend and backend?

I’m developing a webapp that uses vite on the frontend for my local testing environment and also a separate API backend.

I used mkcert to generate a local dev certificate and am using that one for the backend.

My question is, for my frontend dev environment I also can use a certificate, as shown here in the vite config:

server: {
  https: {
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('cert.pem'),
  },
  proxy: {
    '/v1': {
      target: 'https://127.0.0.1:8080'
    }
  }
}

My question is: can I use this same generated certificate (key.pem and cert.pem) for my backend and frontend servers? It seems to work okay, but I’m not sure of the implications for this.

I generated my mkcert certificate using the following command:

mkcert localhost 127.0.0.1 ::1 192.168.1.96

Toggle image source with vanilla javascript function

I am trying to swap an SVG logo image on click using Javascript. My script looks like this:

document.querySelector('.logo').addEventListener('click', function() {
    document.querySelector('#logo-switch').src='logo-B.svg';
    document.querySelector('#logo-switch').src='logo-A.svg';
    })

The function works on the first click (when the third line of code is removed):
document.querySelector('#logo-switch').src='logo-A.svg';

However, I would like for it to switch back to the original src each time the logo is clicked — this should function as a toggle.

Is this done with an if statement? Or how is this achieved?

Many thanks

inserting elements from an array to a div’s innerHTML using forEach()

I m basically trying to first clear the form div by saying form.innerHTML = ''. Then when i try to insert one by one the elements from an array back to the form div using forEach() on the array, it just sets the innerHTML to the last element from that array.
Here’s my javascript code :

 form.innerHTML = '';

    userCorrectAnswers.forEach(e => {
        let cA = e.innerHTML;
        form.innerHTML = cA;
    })

Need to know how can i add all the elements from that array to the innerHTML of the form.

Passing variable to other pages in react

I have to make global variable to be taken for all pages in the reactJs application. It is named as ‘city’ where it changes every time I am using useState of reactJs. The city is only changed in Mainpage of the react site.
When I change the city in Mainpage and direct it to other pages then the changed value of the city is not taken. It remains the default that I declared at app.js. I checked it by printing the city in the console in app.js and it changes every time when I change it in MainPage which is correct, but when I direct it to other pages the default value of the city i.e, ‘Select city’ is taken.
I use the functional component. The image of the declaration of the variable and routing is given in the image.
Mainpage is changing the city in app.js but it is not forwarded to other pages. The default value is taken for it.
I want that whenever the value of the city is changed in the MainPage the effect will show in the app.js, which is working, and also to the other pages when I go to them just like, ‘https://www.nobroker.in/home-services’, them. But the changes are not reflected to other pages.
I am using tag to redirect the window to other pages.

The code of app.js is:

function App() {

const [city, setCity] =useState(“Select City”)

const handleData = (data) => {
setCity(data)
}
console.log(city);

return (

  {/* home page  */}
  <Route exact path='/home-services' element={<HouseDeckHomeServicesMainPage city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/' element={<HouseDeckHomeServicesMainPage city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home' element={<HouseDeckHomeServicesMainPage city={city} setCity={setCity} handleData={handleData} />} />

  {/* footer pages  */}
  <Route exact path='/home-services/terms-and-conditions' element={<HouseDeckHomeServicesTC/>} />
  <Route exact path='/home-services/privacy-policy' element={<HouseDeckHomeServicesPrivacy/>} />
  <Route exact path='/home-services/return-exchange-and-refund' element={<HouseDeckHomeServicesPrivacy/>} />
  <Route exact path='/home-services/faqs' element={<HouseDeckHomeServicesFAQpage />} />

  {/* services pages  */}
  <Route exact path='/home-services/painting' element={<HouseDeckHomeServicesPainting city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/cleaning' element={<HouseDeckHomeServicesCleaning city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/home-sanitization' element={<HouseDeckHomeServicesSanitization city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/ac-repair' element={<HouseDeckHomeServicesACRepair city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/electrician' element={<HouseDeckHomeServicesElectrician city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/carpentary' element={<HouseDeckHomeServicesCarpentary city={city} setCity={setCity} handleData={handleData} />} />
  <Route exact path='/home-services/plumbing' element={<HouseDeckHomeServicesPlumbing city={city} setCity={setCity} handleData={handleData} />} />

  {/* 404 page  */}
  <Route exact path='*' element={<HouseDeckHomeServicesNotFound city={city} />} />
</Routes>
</BrowserRouter>

);
}

enter code here

please help.

how to use variables conditionally in styled components

I am trying to conditionally change the UI of my component in styled components, but I found myself repeating myself a lot.
this is what is happening right now:

color: ${props => (props.isProductPage ? color('white') : 'reset')};
background-color: ${props =>
  props.isProductPage ? color('primary', 'main') : 'reset'};
font-size: ${props => (props.isProductPage ? '1.4rem' : 'reset')};
font-weight: ${props => (props.isProductPage ? '400' : 'reset')};

but I want to have all these in a variable and import that variable conditionally, but I could not find out what am I doing wrong. This is what I am looking for.

const ProductPageAddToCard = `
color: ${color('primary')};
background: ${color('primary', 'main')};
font-size: ${textSize('medium')};
font-weight: ${textWeight('medium')}
`;

export const StyledAddToCardWrapper = Styled.div`
 button {
  ${props => (props.isProductPage ? ProductPageAddToCard : '')}
 }
`

Thanks in advance

FlatList conditional rendering if {user === owner || gues}

In my Applikation I render a Expo FlatList to show created Events.

List Preview

If the user has created or joined this event, he should be able to see the images. If not, they should be hidden.

I would now store the creator and the guests in the database and would have to compare this with the currentUser from the Firebase Auth beforehand.

However, I face the problem that I can’t tell the FlatList which items should be rendered and which shouldn’t.

Does anyone knows a solution for conditional render a FlatList?

Fullcode

import React, { Component } from 'react';
import { FlatList, Box,  } from "native-base";
import { StyleSheet } from 'react-native'
import EventCard from "./EventCard.js";
import { collection, getDocs } from 'firebase/firestore';
import { firestore, auth } from '../firebase.js'
import { getStorage } from "firebase/storage"

export default class Events extends Component {

    constructor(props) {
        super(props);
        this.currentUser = auth.currentUser
        this.navigation = this.props.navigation
        this.storage = getStorage()
        this.querySnapshot = getDocs(collection(firestore, 'events'));
        this.state = {
            isLoading: true,
            fetch: false,
            eventData: {
                adress: '',
                hosts: '',
                description: '',
                eventtitle: '',
                invitecode: '',
                key: '',
                timestamp: '',
                owner: '',
            }
        }
    }

    componentDidMount() {
        this.loadEventsFromFirebase()

    }

    //  reload on pull down
    onRefresh() {
        this.setState({
            fetch: true
        });
        this.loadEventsFromFirebase()
    }

    loadEventsFromFirebase() {
        let data = []
        this.querySnapshot.then(querySnapshot => {
            querySnapshot.docs.map(doc => {
                data.push(doc.data())
            })
            this.setState({
                eventData: data,
                fetch: false,
            });
        });

    }

    render() {

        return (
            <Box style={styles.container} _dark={{ bg: "blueGray.900" }} _light={{ bg: "blueGray.50" }}>
                <FlatList
                    showsVerticalScrollIndicator={false}
                    onRefresh={() => this.onRefresh()}
                    refreshing={this.state.fetch}
                    data={this.state.eventData}
                    keyExtractor={item => item.key}
                    renderItem={({ item }) => (<EventCard key={Date.now()} eventData={item} />
                    )}
                />
            </Box>
        )
    }
}

const styles = StyleSheet.create({
    container: {
        alignSelf: 'stretch',
        alignItems: 'center'
    },
})

Calculating max and avg values from two arrays

I am trying to use two arrays to calculate max value and average values to create key/value object.
Here are the two arrays

const products = ["car", "car", "motorcycle", "motorcycle"] // key
const prices =[2000, 1500, 800, 900] // value

desire outcome - 
{"car" : {max: 2000, average: 1750}, 
"motorcycle":{max: 900, average: 850} }

It will be great if ES6 iterators like reduce/map and etc can be used for solution.

Thank you for help!

Recent grad revisiting a 2021 plain JS app project. Issues running front end server with Webpack [closed]

I graduated a couple weeks ago with a Certificate in Full Stack Development. Post graduation, we’re instructed to revisit and revise older projects. One of which, I accidentally deleted package.json files as well as all node.js files. Don’t ask me how. Ashamed to say if a recruiter asked me to demonstrate booting up a vanilla JS server app, I’d be in trouble. If he/she asked me about file source control with Github, I’d be in deep trouble as well. Most commits have disappeared. Unfortunately, these topics were briefly mentioned within the course curriculum and now I’m having to go back and research. I suppose Ive been so accustomed to react and rails setup that I forgot how to start up a plain server without either frameworks. With each Youtube tutorial and package.json configuration, I grow more confused as to how to get things back up and running. To be more specific, it seems my updated webpack configurations do not permit me to render code to the browser from localhost8080. The console error says GET http://localhost:8080/ 404 (Not Found) I do not know where to begin to resolve this issue. Still lost after hours of tutorial videos. Any help is gladly appreciated.
Git Repository: https://github.com/jasonronalddavis/ManyProjectsFrontend
Terminal error log:

ERROR in ./src/style.css (./node_modules/css-loader/dist/cjs.js??ruleSet[1].rules[1].use[1]!./src/style.css)
Module build failed (from ./node_modules/css-loader/dist/cjs.js):
ValidationError: Invalid options object. CSS Loader has been initialized using an options object that does not match the API schema.
 - options has an unknown property 'minimize'. These properties are valid:
   object { url?, import?, modules?, sourceMap?, importLoaders?, esModule?, exportType? }
    at validate (/Users/jasondavis/Flatiron/code/ManyProjectsFrontEnd/node_modules/schema-utils/dist/validate.js:105:11)
    at Object.getOptions (/Users/jasondavis/Flatiron/code/ManyProjectsFrontEnd/node_modules/webpack/lib/NormalModule.js:585:19)
    at Object.loader (/Users/jasondavis/Flatiron/code/ManyProjectsFrontEnd/node_modules/css-loader/dist/index.js:31:27)
 @ ./src/style.css 8:6-127 22:17-24 26:7-21 58:25-39 59:36-47 59:50-64 63:6-73:7 64:54-65 64:68-82 70:42-53 70:56-70 72:21-28 83:0-97 83:0-97 84:22-29 84:33-47 84:50-64 61:4-74:5

webpack 5.70.0 compiled with 1 error in 17776 ms