jsonwebtoken in Pentaho PDI

I am trying to run this code in Modified JavaScript value step from PENTAHO to generate a token which will be used to access information by API. I am new with JS and also pentaho so idk why it keeps me shooting the error: syntax error (script#16). Furthermore, if i let just the code until const request, it says ReferenceError: “require” is not defined. (script#2). So, i think even the jsonwebtoken library is not being called.

Everything is fine if you run this code outside pentaho, i did it in Vs Code and i got the token, but when i put in the step from pentaho, it does not run.

const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
const request = require('request');

// settings
const basePath = 'https://identityhomolog.acesso.io';

// entry point
const options = {
  serviceAccount: pemfile,
  tenant: x-tenant
};

requestAnAccessToken(createServiceAccountToken(options), (err, accessToken) => {
  const payload = jwt.decode(accessToken.access_token);
  console.log('Access Token:', accessToken.access_token);
  console.log('expires_in:', accessToken.expires_in);
});

// functions
function createServiceAccountToken({ tenant, serviceAccount, account = '' }) {
  // Reads the service account private key
  const privateKey = serviceAccount;

  // Prepare the request
  const payload = {
    iss: '[email protected]',
    aud: 'https://identity.acesso.io',
    scope: '*',
    exp: Math.floor(Date.now() / 1000) + 3600,
    iat: Math.floor(Date.now() / 1000),
  };
  // Service account is requesting an access token for another user?
  if (account) {
    payload.sub = account;
  }

  // Create JWS
  return jwt.sign(payload, privateKey, { algorithm: 'RS256' });
}

function requestAnAccessToken(serviceToken, callback) {
  // Prepare the request
  const options = {
    method: 'POST',
    url: 'https://identity.acesso.io/oauth2/token',
    headers: { 'content-type': content-type },
    form: {
      grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
      assertion: serviceToken,
    },
  };
  console.log('Requesting Access Token with self created token: ', serviceToken);

  // Ask identity and authorization server for an access token
  request(options, (error, response, body) => {
    if (error) {
      callback(new Error(error));
    }

    body = JSON.parse(body);

    if (body.error) {
      callback(new Error(`${body.error}: ${body.error_description}`));
    }

    callback(null, body);
  });
}

Flatten an array in most efficient manner

I would like to do something like this but in a more large scale and efficient way.
Assume I have the array of objects to be flattened.

Convert:

{
  name: 'john doe',
  address: { apartment: 1550, streetno: 167, streetname: 'Victoria', a... }
  b...
}

to this –

{
  name: 'john doe',
  apartment: 1550,
  streetno: 167,
  streetname: 'Victoria'
  a...
  b...
}

Using js methods.

Uploading images directly to html site [closed]

I’m trying to develop a gallery site where I can display images I upload. I was able to make a site with the gallery but could not come across a way to create a way to upload images from my local directory, and save the img as a in html.
are there any recommended ways/library to do so? how would I be able to do this without using backend.

MUI 5 and react 18. How to mask the entered date with (*) asterisk symbol in mui datepicker

In my application, there is an option for capturing date of birth of user. Once user entered date or selected from calendar, I want to show number as asterisk.

Package version:

“@mui/material”: “^5.6.2”,
“@mui/lab”: “^5.0.0-alpha.71”,
“date-fns”: “^2.24.0”,
“react”: “^18.0.0”,

Example:

If user enter DOB 05/11/1990(mm/dd/yyyy), then need to show like * * / * */ 1990.

Actual
enter image description here

Expected:
enter image description here
Code:
enter image description here

Can Constructor functions inherit an interface in Typescript?

I have a JS constructor function written in Typescript and i access this constructor function from other code like this

const ls = new LocalStorage<ICountryHolidayData>()
let strdVal = ls.getItem(constants.localStorageKey).storedValue

Though the code works fine but i do not get any intellisense..neither for ls.getItem nor for the storedValue property.

I think its because constructor functions can’t inherit interface like classes do in typescript?
Otherwise can some help me understand how to do this, so that i can get intellisense for both values.


export interface ILocalStorgaeReturnValue<Type>{
  storedValue: Type,
  date: Date
}

export interface ILocalStorage<Type extends {}>{

setItem(key:string,value:Type):void;
getItem(key:string):ILocalStorgaeReturnValue<Type>;
removeItem(key:string ):void;
//clear();
}



export function  LocalStorage<Type>(){  
  
  if( !window.localStorage)
      throw new Error(`Browser does not support local storage`)
 
 this.setItem = (key:string, val:Type ) =>{
   
  if(!key || !val )
    throw new Error(`key or value can not be null `)

    const completeObj = {
      storedValue: {
      ...val
      },
      date:new Date()
    }
    window.localStorage.setItem(key ,JSON.stringify(completeObj))
 },
 
 this.getItem = (key:string):ILocalStorgaeReturnValue<Type> =>{
   
 
  if(!key  )
    throw new Error(`[key can not be null `)

    
  const val= JSON.parse(window.localStorage.getItem(key))

  if(!val || Object.keys(val).length<2)
    return null 
  else 
    return <ILocalStorgaeReturnValue<Type>> {
      ...val
    }     
    
 },

 this.removeItem = (key:string) =>{
   
  if(!key  )
    throw new Error(`Key is empty`)

   window.localStorage.removeItem(key)
 }

}

Test CKEditor change

I’m using a CKEditor component from ckeditor4-react in my application. I’d like to create a jest test that will use react-testing-library to write some stuff inside this CKEditor component.

At the moment, my component contains code like:

const handleChange = (event: any) => {
    setBody(event.editor.getData());
};

<CKEditor
  onChange={handleChange}
  data-testid="ckeditor-textfield"
/>

This works fine when testing manually.

Within my Jest test, I’ve got the following:

const editorText = screen.getByTestId('ckeditor-textfield');
fireEvent.change(editorText, { target: { value: 'Email body text' } });

However, this doesn’t work and I get an error:

TestingLibraryElementError: Unable to find an element by:
[data-testid=”ckeditor-textfield”]

If I try a different way to get the editor text fiend by doing:

const editorText = document.getElementsByClassName('cke_editable')[0];

I get the following error:

Unable to fire a “change” event – please provide a DOM element.

How can I test the input field for a CKEditor component?

How to implement dropdown menu Vanilla JS CSS

I have been attempting to put together a drop down menu which slides down rather than “just appears” upon the click event. I tried to apply a transition to the drop down menu with no success. Help would be appreciated. I would like come to a solution with both css and javascript.

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width">
    <!-- <meta http-equiv="content-type" content="text/html; charset=UTF-8" /> -->
    <script
  src="https://code.jquery.com/jquery-3.6.0.js"
  integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
  crossorigin="anonymous"></script>
    <script src="https://kit.fontawesome.com/36947df53d.js" crossorigin="anonymous"></script>
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>
  <div class="logo">
    <p id="logo">Logo</p>
    <button id="btn"><i class="fa-solid fa-bars"></i></button>
  </div>
   <nav class="nav">
     <ul class ="dropmenu" id="dropdown">
       <li><a href="contact.html" class="link">Link 1</a></li>
       <li><a href="#" class="link">Link 2</a></li>
       <li><a href="#" class="link" id="last">Link 3</a></li>
     </ul>
   </nav>
   <div class = input>
   <!-- <input type="checkbox" id="myCheckbox"> -->
  </div>
    <script src="script.js"></script>
  </body>
</html>

CSS
Applied a transition to the #dropdown but with no success


body {
    height: 100vh;
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

.logo {
    display: block;
    text-align: left;
    background: #f8f9f9;
    height: 10vh;
}

.logo #logo {
    display: inline;
    line-height: 10vh;
    font-size: 1.6em;
    margin-left: 0.5em;
    color: #438ED9;
    
}

button#btn {
    display: inline;
    float: right;
    margin-right: 2em;
    margin-top: 0;
    margin-bottom: 0;
    border: none;
    background-color: #f8f9f9;
    padding: 0;
}

nav {
    display: block;
    background-color: #438ED9;
    width: 100vw;
    /**/
}

nav ul#dropdown {
    display: none;
    list-style-type: none;
    margin: 0; 
    padding-left: 0;
    box-shadow: none; 
    overflow-y: hidden;
    max-height: 21vh; /* approximate max height */

    transition-property: all;
    transition-duration: .5s
}


nav ul li {
    text-align: center; 
    
}



.link {
    display: block;
    color: white;
    font-size: 1.5em;
    background-color: #438ED9;
    text-decoration: none;
    width: 100vw;
    height: 7vh;
    line-height: 7vh;
    border-bottom: 2px solid black;
    text-align: center;
    
}

 #last {
    border-bottom: none;
}

.link:hover {
    background-color: blue;
}

.link:active {
    background-color: blue;
}

.visible {
    display: block !important;
}

.fa-bars:before, .fa-navicon:before {
    content: "f0c9";
    font-size: 20px;
    line-height: 10vh;
}

.fa-solid .fa-bars:hover {
    color: red;
}
.fa-solid:active, .fa-bars:active {
    color: grey;
}

@media only screen and (min-width: 480px) { 
    
    .fa-bars:before, .fa-navicon:before {
        font-size: 30px;
    }

    /* #dropdown {
        display: block;
    } */

}
  
  @media only screen and (min-width: 600px) {

    .fa-bars:before, .fa-navicon:before {
        font-size: 30px;
    }

    nav ul {
        display: block;
        text-align: center;
        float: right;
        margin-right: 30px;
    }
    nav ul li {
        display: inline;
        text-align: center;
        padding: 0 10px;

    }
    #btn i {
        display: none;
    }

    nav {
        height: 7vh;
    }

    .link {
        display: inline;
        color: white;
        font-size: 1.2em;
        border-bottom: none;

    }
    .link:hover {
        background-color: #438ED9;
    }
    
    .link:active {
        background-color: #438ED9;
    }

    
}

JS

document.querySelector("body").addEventListener("click", function(event){  
    let dropd = document.querySelector('#dropdown');
    if (!event.target.parentNode.matches('#btn')) {    
      dropd.classList.remove("visible");
    } else {
      dropd.classList.toggle("visible");
    }
  });

Most efficient way to make multiple AJAX calls

I have an ASP.NET Core page where I need to display several charts using morris.js. This package renders the characts using client-side JavaScript.

Rather than building all the data for all the charts before the page is served, I’m thinking the page would feel more responsive if I serve the page and then use AJAX to get the data for each chart. But I’m a little unsure how well the JavaScript engine handles concurrency.

Is it okay to simply code one AJAX call after the other? Or would it be better to wait until each AJAX call finished before calling the next? I’d love to hear anyone’s thoughts who has some knowledge in this area.

Javascript recursion related question about push() and unshift() methods working opposite

function countup(n) {
  if (n < 1) {
    return [];
  } else {
    const countArray = countup(n - 1);
    countArray.push(n);
    return countArray;
  }
}
console.log(countup(5));

After running the above code it returns an array [1, 2, 3, 4, 5] But push() adds new values at the end of an array so when value of n was 5 it should push 5 to the end of the array and when value of n got 4 it should push 4 at the end of the array like [5,4]. So why not it is returning [5,4,3,2,1] ? It is hard to understand what is happening in this code probably because of this recursion. Isn’t unshift() (which add new values to start of the array) should return [1,2,3,4,5] and push() [5,4,3,2,1] why opposite is happening?

I only want a div to display on screen depending on a boolean value

I only want a particular div to display if showHideClassName is set to the value of true. I have this code in my React application so that a div will either display or not depending on the status of showHideClassName:

render() {
    ...
    const showHideClassName = showPrompt ? 'show-div' : 'display-none';
        return (
            <div className={showHideClassName}>
                ...
            </div>
        );
}

The div is always visible though. Is there any way I can get this to work as I desire?

Selinium click on tag with data-id python

I am a computer science student and this is my first post on stackoverflow, I am trying to write a code that automatically logins into my college website and helps with booking a court for my sports.

I am trying to write a line that clicks on a tag with data-id, but can’t seem to find a way…

Here is a screenshot of the tag that website contains…

screenshot1 of question

And here is some lines i have tried that didn’t work…

driver.find_element_by_xpath(‘/html/body/section/div/div[3]/div[2]/div/div/div[3]/button’).click()

driver.FindElement(By.CssSelector(“[data-text=’Shift 3′]”)).click()

Hoping anyone could help…

Loading when fetching firestore data

I want to set a loading state whenever the page is fetching the firestore data .
I am using this :
const [isLoading, setIsLoading] = React.useState(true)

const fetchGames=async()=>{
    let promises = []
    const dataDB = await db.collection('event')
    const eventsFromDb = []
    const DB =await db.collection('event').get()
    DB.docs.forEach((item,index)=>{
      const promise = dataDB
      eventsFromDb[index]= item.data()
      promises.push(promise);
     })
     setEvents(eventsFromDb)
     Promise.all(promises)
     .then(setIsLoading(false));
    }
useEffect(()=>
    {
      fetchGames()
      if(!isLoading)
      {
        console.log("HEY")
      }

    }, [])

I cannot get the HEY in my console , how to fix this ?

When i set a width the child element disappear

I have a div called a-text-box. And i want to display an arrow after a section. I have 4 sections. Section = 2 words. But when i set a width for my a-text-box, the arrow disappears.I dont really know how to fix that. The arrow it’s supposed to be displayed after ‘Jonathan’.

JSX:

  return (
    <Transitions>
      <div className={styles.about}>
        <h1>Who am I?</h1>
        <div className={styles["a-container"]}>
          <Undraw1 class={styles.svg} />
          <div className={styles["a-text__box"]}>
            <Element text="Name" text2="Jonathan" />
            <BsFillArrowRightCircleFill className={styles.arrow} />
            <Element text="Age" text2="18" />
            <Element text="Nationality" text2="Brazilian" />
            <Element text="Experience" text2="Junior" />
          </div>
        </div>
        <Btn name="Details" class={styles.btn} />
      </div>
    </Transitions>
  );

CSS:

@media (max-width: 992px) {
  .a-container {
    width:90%;
    .svg{
      transform:scale(0.8);
    }
    .a-text__box {
     width:40%;
      display: flex;
      background-color: var(--primary-color);
      border-radius: 27px;
      align-items: center;
      overflow: scroll;

      div {
        margin-inline: 20%;
        align-items:center;
        font-size: 2rem;
        display: flex;
        flex-direction: column;

        .arrowRight {
          display: none;
        }
        .space {
          display: none;
        }
      }

      .arrow {
        display: block;
      }
    }
  }
}

How to get details of logged in user in React

I’m new to React and I’m trying to make a route to keep the user logged in after registering, so that I can use their user details to populate fields in the homepage. I first tried doing this the way I used to before I started learning react, by saving the data in res.locals, but this doesn’t seem to work in react. Now I’m trying to do it with local storage. First, I send a post request when the user submits a form:

    onSubmit(e) {
        e.preventDefault();

        const newUser = {
            userName: this.state.userName,
            userEmail: this.state.userEmail,
            userPassword: this.state.userPassword,       
        }
        console.log(newUser);

        axios.post('http://localhost:5000/user/signup', newUser)
            .then(res => localStorage.setItem("CurrentTeacher", (res.data));                     
            console.log(localStorage.getItem("CurrentUser"));
        }

The post request works fine and the user is added to my DB with no issues, but localStorage.getitem line always returns undefined. Below is my post request in my userRoute.js file (I’m using Passport to register my user):

router.route('/signup').post(async (req, res) => {
    const username = req.body.userName;
    const userEmail = req.body.userEmail;
    const password = req.body.userPassword;
    try{
       const newUser = new User({userEmail,username});
  
       const registeredUser = await User.register(newUser,password);
       req.login(registeredUser,err=>{ 
          if(err) console.log(err);      
          console.log("NEW USER: " + req.user)     
       })
    } catch(e){
        console.log(e.message)
    }
  });

I’ve tried several different things, like adding JSON.stringify to my res.data. Infact, it doesn’t even look like my .then code is firing because when I run a simple console.log with .then, I get nothing.