How to make a selection in a dropdown menu active with js (Chrome flags)

I’m trying to write code to the console on a page chrome://flags/ to automate the selection of the desired flag options. The problem is that I have code that selects the desired option from the dropdown menu

var parametr = "Enabled";
var index = [...document.querySelectorAll('select[aria-labelledby="temporary-unexpire-flags-m109_name"]')[0].querySelectorAll('option[jsvalues]')].findIndex(({textContent}) => textContent.includes(parametr));
console.log(index);
document.querySelectorAll('select[aria-labelledby="temporary-unexpire-flags-m109_name"]')[0].querySelectorAll('option[jsvalues]')[index].selected = 'selected'

But it is not active and when the page is refreshed, everything goes back. Can anything be done?

How to turn a string into hex colour code?

So I need to make a code that turns a string into hex colour code. For example turn the string “purple” into the hex code that matches purple, but if its a random thing such as “fjskf”, it should still turn it into a random colour.

I have tried this so far:

function convert(str: string){
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  let colour = '#';
  for (let i = 0; i < 3; i++) {
    const value = (hash >> (i * 8)) & 0xFF;
    colour += ('00' + value.toString(16)).substr(-2);
  }
  return colour;
};

But it doesnt work for every color like pink and green and blue. Thank you!

Generate openapi/swagger js client, without having to use npm or nodejs

I have a swagger 2.0 api specification and I would like to generate an API client in javascript for it. The issue is, that the generator I am currently using (org.openapi.generator" version '6.4.0') also creates a node.js project.
Nodejs modules can’t be resolved by the browser (that’s expected) but I can’t host the javascript on a node server (I use springboot). I want to have a static version of the npm module openapi creates that can be included using standard ES6 syntax.

I tried to build the generated code and create a bundle using browserify but I have issues accessing the generated classes (everything is undefined).
But I doubt that this is the correct procedure, as using openapi in that way probably is a common thing to do.

In Cypress.Commands.add function use a param to mutate a cy.intercept function and return modified function from handler

I would love a recommendation on scaling my Cypress test harness. I have lots of fixtures and many of my fixtures are similar. So, for example, I might have a spec that has five tests testing five fixtures that are all identical except for one line. This is not scalable. They should be taking one fixture and using a parameter to dynamically update that one line.

I started trying to break out one fixture with a command that is similar to this:

Cypress.Commands.add('setDivisionsIds', (Array) => {
  cy.intercept(
    'GET',
    `**/${Cypress.env('API_BASE_URL')}/v2/divisions/*`,
    (req) => {
      req.reply({ division
      //   ids: Array,

where the last line of that code is the first line of a 400 line json response that is deeply nested.

When I call `cy.setDivisionsIds([‘1’, ‘2’]);

it does mutate the fixture and now I can write a test with a single ID or a test with more than 1 IDs and it will return that mutated intercept instead of calling two fixtures.

However, moving the 400 line fixture from my fixture folder to commands.ts is clogging up my commands.ts and isn’t scalable. I want to be able to find cypress commands easily in this file and keep fixtures separate. Some of these fixtures are also used by jest, which is why they’re in a /fixture file in my /src and not in /cypress.

I was thinking of creating something like a handler and saving it as a file called DivisionFixture.ts in my fixtures folder

However, I’m not sure how to create a function that returns the json object with my mutated parameter. ie. if I try to create a function in DivisionFixture.ts and export it like this

export function setDivision(Array) {
    return [
        external_ids: Array,
        ... rest of json 

All my json gets underlined with <key name> not found. Do I need to stringify this value and how would i do that in a function? Or do I need to create a whole class and export that? That could easily get very hairy with the size of my json files and the nesting (up to 10x).

Does anyone have a recommendation? Again steps are:

  1. Create a Cypress.command that sets a value from an intercept
  2. Reply in the intercept with the json body that is mutated with the value
  3. Do this with the help of an external file to keep the test harness scalable

I want to make a website where the user can access the courses and materials(pdfs) he/her has purchased using javascript. Is it possible? [closed]

I am not sure whether I should use javascript or react js for this purpose. I also am struggling to figure out how the user would purchase the courses. Please help me out and if possible please link a video which you think might be able to help out. Thank you so much!

I am still planning the user interface and design.

find query doesn’t working properly, find({ _id: { $lte: mongoose.Types.ObjectId(‘64205050fc177e94b6e4d82b’) }, }).limit(11);

the _id attributed doesn’t working, tried different attributes like createdAT , none of them working. at the end its acting like a empty object(no effect on query).

const chats = await ChatsModel.find({_id: { $lte: mongoose.Types.ObjectId(‘64205050fc177e94b6e4d82b’) },}).limit(11);

/ problem here at _id which results empty array

i want to retrieve the messages from chat less than the id or createdat(cursor based pagination), query in the find method doesn’t working. here is code.

expecting messaged before/after the id / createdat

also tried:-

=> const chats = await ChatsModel.find({createdAt: { $lte: ‘timestamps’ },}).limit(11);

also tried
=> const chats = await ChatsModel.find({ _id: { $lte/gte/gt/lt: ‘64205050fc177e94b6e4d82b’ }, }).limit(11);

React component does not detect any css file while importing

I’m trying to import css into my react component but when i write ‘./’ it does not show me any css files. If i import by writing the correct path, css does not work.

component:

import React from 'react';
import './'
function square(props) {
console.log(props)
 return (
  <div onClick={props.onClick} className='Square'>
       <h4>{props.value}</h4>
  </div>
   )
 export default square

MongooseError: Model.findById() no longer accepts a callback

i’ve encountered a problem : Can anyone help, thanking you in advance !

MONGOOSE VERSION: "mongoose": "^7.0.3"

MongooseError: Model.findById() no longer accepts a callback at Function.findById (C:UsersNOOBDesktopmern-projectnode_mod at module.exports.userInfo (C:UsersNOOBDesktopmern-projectco at Layer.handle [as handle_request] (C:UsersNOOBDesktopmern-projectnode_modulesexpresslibrouterlayer.js:95:5) at next (C:UsersNOOBDesktopmern-projectnode_modulesexpresslibrouterroute.js:144:13) at Route.dispatch (C:UsersNOOBDesktopmern-projectnode_modulesexpresslibrouterroute.js:114:3) at Layer.handle [as handle_request] (C:UsersNOOBDesktopmern-projectnode_modulesexpresslibrouterlayer.js:95:5) at C:UsersNOOBDesktopmern-projectnode_modulesexpresslibrouterindex.js:284:15 at param (C:UsersNOOBDesktopmern-projectnode_modulesexpresslibrouterindex.js:365:14) at param (C:UsersNOOBDesktopmern-projectnode_modulesexpressmern-projectnode_modulesexpresslibroutejs:376:1rindex.js:376:14) ïDesktopmern-projectno at Function.process_params (C:UsersNOOBDesktopmern-projectnode_moduleslibrouexpresslibrouterindex.js:421:3)

const UserModel = require("../models/user.model");
const ObjectID = require("mongoose").Types.ObjectId;

module.exports.getAllUsers = async (req, res) => {
  const users = await UserModel.find().select("-password");
  res.status(200).json(users);
};

module.exports.userInfo = (req, res) => {
  if (!ObjectID.isValid(req.params.id))
    return res.status(400).send("ID unknown : " + req.params.id);

  UserModel.findById(req.params.id, (err, docs) => {
    if (!err) res.send(docs);
    else console.log("ID unknown : " + err);
  }).select("-password");
};

module.exports.updateUser = async (req, res) => {
  if (!ObjectID.isValid(req.params.id))
    return res.status(400).send("ID unknown : " + req.params.id);

  try {
    await UserModel.findOneAndUpdate(
      { _id: req.params.id },
      {
        $set: {
          bio: req.body.bio,
        },
      },
      { new: true, upsert: true, setDefaultsOnInsert: true },
      (err, docs) => {
        if (!err) return res.send(docs);
        if (err) return res.status(500).send({ message: err });
      }
    );
  } catch (err) {
    return res.status(500).json({ message: err });
  }
};

module.exports.deleteUser = async (req, res) => {
  if (!ObjectID.isValid(req.params.id))
    return res.status(400).send("ID unknown : " + req.params.id);

  try {
    await UserModel.remove({ _id: req.params.id }).exec();
    res.status(200).json({ message: "Successfully deleted. " });
  } catch (err) {
    return res.status(500).json({ message: err });
  }
};

module.exports.follow = async (req, res) => {
  if (
    !ObjectID.isValid(req.params.id) ||
    !ObjectID.isValid(req.body.idToFollow)
  )
    return res.status(400).send("ID unknown : " + req.params.id);

  try {
    // add to the follower list
    await UserModel.findByIdAndUpdate(
      req.params.id,
      { $addToSet: { following: req.body.idToFollow } },
      { new: true, upsert: true },
      (err, docs) => {
        if (!err) res.status(201).json(docs);
        else return res.status(400).jsos(err);
      }
    );
    // add to following list
    await UserModel.findByIdAndUpdate(
      req.body.idToFollow,
      { $addToSet: { followers: req.params.id } },
      { new: true, upsert: true },
      (err, docs) => {
        // if (!err) res.status(201).json(docs);
        if (err) return res.status(400).jsos(err);
      }
    );
  } catch (err) {
    return res.status(500).json({ message: err });
  }
};

module.exports.unfollow = async (req, res) => {
  if (
    !ObjectID.isValid(req.params.id) ||
    !ObjectID.isValid(req.body.idToUnfollow)
  )
    return res.status(400).send("ID unknown : " + req.params.id);

  try {
    await UserModel.findByIdAndUpdate(
      req.params.id,
      { $pull: { following: req.body.idToUnfollow } },
      { new: true, upsert: true },
      (err, docs) => {
        if (!err) res.status(201).json(docs);
        else return res.status(400).jsos(err);
      }
    );
    // remove to following list
    await UserModel.findByIdAndUpdate(
      req.body.idToUnfollow,
      { $pull: { followers: req.params.id } },
      { new: true, upsert: true },
      (err, docs) => {
        // if (!err) res.status(201).json(docs);
        if (err) return res.status(400).jsos(err);
      }
    );
  } catch (err) {
    return res.status(500).json({ message: err });
  }
};

I am having connection error with post api in MERN, api is giving correct output at backend but inverse at frontend

Hi I am learning MERN and trying to resolve issue regarding the api connection for a login page.
handeLoginSubmit() runs on submitting the login form having try n catch..

Entering the wrong credentials or the right only the try block runs
from the backend it is giving error but at front end it shows sucessful upon both right/ wrong credentails

>front-end(react code)

async function handeLoginSubmit(e) {
        e.preventDefault();
        try {
            await axios.post('/login', { email, password });
            alert('Login Successfull')
            // console.log('No - error');
        } catch (e) {
            // console.log('error');
            alert('Login Failed!')
        }
    }

----------------------------------------------

> backend code for express server with post request 


app.post('/login', async (req, res) => {
    const { email, password } = req.body;
    const userDoc = await User.findOne({ email });
    console.log(userDoc);
    if (userDoc) {
        const passOk = bcrypt.compareSync(password, userDoc.password)
        if (passOk) {
            res.json('passok')
        } else {
            res.status(422).json('wrong crediantials')
        }
        console.log(' user found');
    } else {
        res.json('not found!!')
        console.log('not found!!')
    }
})

chrome headless print-to-pdf add param for the index file

I’m trying to get a chrome headless script working where I convert a local html file to a pdf file. But within the HTML file I would like to pass some parameters to use in my html file. Unfortunately this seems easier said than done as I can’t find much information on this.

This command line works correctly

google-chrome --headless=new --no-sandbox --disable-gpu --print-to-pdf=file2.pdf file2.html 

And this is my file2.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
    </head>

    <body >

            <div class="page" id="page-0">
                <div id="content-0">
                    <div id="prm"></div>
                </div>
            </div>

    </body>

    <script>
        const queryString = window.location.search;

        const urlParams = new URLSearchParams(queryString);
        const product = urlParams.get('product')

        document.getElementById("prm").innerHTML = product
    </script>

</html>

The script within file2.html works properly, I tested this myself locally. The problem I run into is that chrome headless changes the url every time.

For Example:

google-chrome --headless=new --no-sandbox --disable-gpu --print-to-pdf=file2.pdf file2.html?product=test

Becomes: file2.html/?product=test (So not found because of “/” after .html)

google-chrome --headless=new --no-sandbox --disable-gpu --print-to-pdf=file2.pdf file2.html#product=test

Becomes: file2.html/#product=test (So not found because of “/” after .html)

In addition, I also found an extra parameter argument that I could use according to the documentation and that was “extra-search-query-params”.

So I tried the following command:

google-chrome --headless=new --no-sandbox --disable-gpu --print-to-pdf=file2.pdf file2.html --extra-search-query-params="product=test"

But no luck either.

I can use the complete url with domain name and then it does work. Only the html page will eventually be used from the backend and not from a public url address.

Does anyone know how I can pass a parameter to my local index html page from the command line?

Thank you in advance.

What to use in place of Redirect for React Router 6 when making custom protected routes

I have some older React Router 5 code I am upgrading to use React Router 6 and have run into a problem with using a custom route that is used to do protected routes in conjunction with authentication.

First I have the routes in App.js

function App() {
  return (
    <Container>
      <Row>
        <Col className="text-center">
          <h1>React Authentication Tutorial</h1>

          <section id="navigation">
            <a href="/">Home</a>
            <a href="/free">Free Component</a>
            <a href="/auth">Auth Component</a>
          </section>
        </Col>
      </Row>

      {/* create routes here */}
      <Routes>
        <Route exact path="/" component={Account} />
        <Route exact path="/free" component={FreeComponent} />
        <ProtectedRoutes path="/auth" component={AuthComponent} />
      </Routes>
    </Container>
  );
}

In my ProtectedRoutes.js file as per the React Router 6 instructions I removed the Redirect and replaced with Navigate as you can see below. Basically this function as you can see moves the component the user tries to access into the function and then surmises if it is allowed and then just redirects them if they have a JWT token…but I am not doing something correctly because I get this error:

Error: [ProtectedRoutes] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment> at invariant
import React from "react";
import { Route, Navigate } from "react-router-dom";
import Cookies from "universal-cookie";
const cookies = new Cookies();

// receives component and any other props represented by ...rest
export default function ProtectedRoutes({ component: Component, ...rest }) {
  return (

    // this route takes other routes assigned to it from the App.js and return the same route if condition is met
    <Route
      {...rest}
      render={(props) => {
        // get cookie from browser if logged in
        const token = cookies.get("TOKEN");

        // returns route if there is a valid token set in the cookie
        if (token) {
          return <Component {...props} />;
        } else {
          // returns the user to the landing page if there is no valid token set
          return (
            <Navigate
              replace to={{
                pathname: "/",
                state: {
                  // sets the location a user was about to access before being redirected to login
                  from: props.location,
                },
              }}
            />
          );
        }
      }}
    />
  );
}

For reference, here is the older React Router 5 code for the protected Route. Of course App.js was using Switch as well, but I spiffed that up to use Route and Routes so that is working good. Just a bit stuck on how to handle the redirect code using React Router 6 in my nifty ProtectedRoutes.js helped function.

import React from "react";
import { Route, Redirect } from "react-router-dom";
import Cookies from "universal-cookie";
const cookies = new Cookies();

// receives component and any other props represented by ...rest
export default function ProtectedRoutes({ component: Component, ...rest }) {
  return (

    // this route takes other routes assigned to it from the App.js and return the same route if condition is met
    <Route
      {...rest}
      render={(props) => {
        // get cookie from browser if logged in
        const token = cookies.get("TOKEN");

        // returns route if there is a valid token set in the cookie
        if (token) {
          return <Component {...props} />;
        } else {
          // returns the user to the landing page if there is no valid token set
          return (
            <Redirect
              to={{
                pathname: "/",
                state: {
                  // sets the location a user was about to access before being redirected to login
                  from: props.location,
                },
              }}
            />
          );
        }
      }}
    />
  );
}

how can i translate every page to another language by clicking button on main page

i have multipage angular application with a lot of components. all them are stored in app.module.ts as modules. how can i translate every page to another language by clicking button on main page. Ive tried with translationservice and pipes but didnt work, I might did something wrong 🙁 First time building app on angular so i am beginner at it(
Thats my app.module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { MainPageModule } from './main-page/main-page.module';
import { RegPageModule } from './reg-page/reg-page.module';
import { TaskPopupModule } from './task-popup/task-popup.module';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { LoginModule } from './login/login.module';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import {HttpClientModule, HTTP_INTERCEPTORS} from '@angular/common/http';
import { TokenInterceptorService } from './service/token-interceptor.service';
import { BoardpageModule } from './boardpage/boardpage.module';
import { MatDialogModule } from '@angular/material/dialog';
import { CreateBoardModule } from './create-board/create-board.module';
import { BoardModule } from './board/board.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    FontAwesomeModule,
    MainPageModule,
    RegPageModule,
    TaskPopupModule,
    MatSnackBarModule,
    LoginModule,
    BoardpageModule,
    MatDialogModule,
    CreateBoardModule,
    BoardModule
  ],
  providers: [{provide:HTTP_INTERCEPTORS, useClass:TokenInterceptorService, multi:true}],
  bootstrap: [AppComponent]
})
export class AppModule { }

Thats my app.component.html

<body>
  <router-outlet></router-outlet>
</body>

thats the what the whole thing looks like

How to set Object to data in React

I want to set object to data in React.

I know how to do in jquery but not in React.

How to do it?

Jquery example.

<button id="set" onClick="set()">set</button>
<button id="restore" onClick="restore()">restore</button>
set = () => {
  $('#set').data('date', dayjs());  
}

restore = () => {
  alert($('#set').data('date').format('YYYY-MM-DD hh:mm:ss'));
}

If I click ‘set’ button, current date object of dayjs set to the object #set.
If I click ‘restore’ button, get dayjs object from #set and alert it.

data(‘date’) is not string. dayjs object. so, i can format directly.

You can check with:
https://codepen.io/sforest1975/pen/qBMgxeR

I can find how to use data in string, but not in object, in React.

How do I display it on one page? [closed]

I can’t show all the items on one page, how do I collect them on the same page?

<div data-include="views/nav></div>

<section data-include "views/page-content/content-left"></section>
<section data-include="views/page-content/content-middle"></section>
<section data-include "views/page-content/content-right"></section>

I didn’t find a solution to try it

Keep prisma studio from production

I use prisma for our database and worry that prisma studio could be a security issue for production. Reading through the docs they don’t seem to mention this nor do they show a way to disable it. Do you all have any suggestions on disabling prisma studio for production? I feel like the best solution would be to separate prisma studio from prisma and put prisma studio as a dev dependency, but it does not appear that is possible.