Error in styling when using function to determine flex React Native

Im trying to create 2 dropdown menus where depending on which are clicked would reduce a third view’s flex number to accommodate the other 2 expanded views. Im using two useState variables to keep track of the 2 different dropdown menus, and calculate the flex as shown:

const [isFirstExpanded, setIsFirstExpanded] = useState(false)
const [isSecondExpanded, setIsSecondExpanded] = useState(false)

const calculateFlex = () => {
    if (isFirstExpanded && isSecondExpanded) {
        return 0; // This means both dropdowns are expanded, and should hide the third view
    } else if (isFirstExpanded || isSecondExpanded) {
        return 2; // Only one of the dropdowns are open, so half the size of the third view
    } else {
        return 4; // None of the dropdowns are open, so show the full view
    }
}
<View style={{flex: 1}}>
    <View style={{flex: calculateFlex, backgroundColor: "red"}}/> // View to be grown or shrunk depending on below views

    <TouchableOpacity style={{flex: 1}} onPress={setIsFirstExpanded(!isFirstExpanded)}/>
    <View style={isFirstExpanded ? styles.expandView : styles.hideView}/> // The dropdown that is hidden by default

    <TouchableOpacity style={{flex: 1}} onPress={setIsSecondExpanded(!isSecondExpanded)}/>
    <View style={isSecondExpanded ? styles.expandView : styles.hideView}/> // The dropdown that is hidden by default
</View>

This code leaves out some innocuous things, if needed I can copy/paste them. My problem occurs when the first view to be grown or shrunk doesn’t seem to follow the calculate flex function. Not sure why, or if there is a better way to calculate this.

Can’t run react-native app on iOS 5 error: duplicate symbols for architecture x86_64

Log output:

duplicate symbol ‘_bridgeRef’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtil.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlob.o)
duplicate symbol ‘_fsQueue’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtil.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlob.o)
duplicate symbol ‘_commonTaskQueue’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtil.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlob.o)
duplicate symbol ‘_fileStreams’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtilFS.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlobFS.o)
duplicate symbol ‘_expirationTable’ in:
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/react-native-blob-util/libreact-native-blob-util.a(ReactNativeBlobUtilNetwork.o)
/Users/sistemas/Library/Developer/Xcode/DerivedData/AppRino-dpmstbwiuaxsmaaznuvxrkhqxixf/Build/Products/Debug-iphonesimulator/rn-fetch-blob/librn-fetch-blob.a(RNFetchBlobNetwork.o)
ld: 5 duplicate symbols for architecture x86_64

Can someone help me write a simple script for my google sheet based on a monthly time basis or teach me how to?

https://docs.google.com/spreadsheets/d/10wT1xopLKYn8kptHByDGav-fDBkhehq2HcRwkLhaJr0/edit?usp=sharing

I need a simple script to be written where the January Row will be locked at the 1st of Febuary and so on till December where it will lock the next year January the 1st.

I did this cause not every month has a 31st but every month has a 1st.

Its a rather simple and intuitive script but, I don’t have the knowledge to write the script. If someone can write it or teach me the abc’s to writing it so that I can understand the script, I would appreciate it.

I shared a doc link to my google sheet so you have an idea of what I am looking for and envisioning.

  • I want cells B12:F12 to lock on the first of Febuary. (Yellow cells) The greyed out cells are locked no matter what so that does not have to be changed.
  • The comment section or (cells in white) can be unlocked indefinetely and doesn’t need to be changed.

Summary: In my google sheet I need the (yellow cells) locked on a monthly basis based on the first of every month. January’s cells B12:F12 locked on Febuary 1st, Febuary’s cells B13:F13 locked on March 1st and so on till December where it locks on January 1st of next year.

Thank You for reading this and your time.

Vue – Advanced Cropper (Uncaught TypeError: this.$refs.cropper.getResult is not a function)

I have a crop function for Vue Advanced Cropper like this:

            crop() {
            const { canvas } = this.$refs.cropper.getResult();
            if (canvas) {
                const form = new FormData();
                canvas.toBlob(blob => {
                    form.append('files[]', blob);
                    // Perhaps you should add the setting appropriate file format here
                }, 'image/jpeg');

                this.formData = form;

            }

        },

My HTML:

    <div v-if="cropView">
    <h1>Step 2: Crop images</h1>
    <div class="upload-example__cropper-wrapper">
        <div v-for="image in this.images" :key="image">
            <cropper ref="cropper" class="upload-example__cropper"
                     check-orientation :src="image.src"/>
            <button v-if="image.src" class="upload-example__button" @click="crop">Crop</button>
            <!--<div class="upload-example__reset-button" title="Reset Image" @click="reset()"></div>-->
            <div class="upload-example__file-type" v-if="image.type">
                {{ image.type }}
            </div>
        </div>
    </div>
</div>

I have included the import for Cropper:

    import {Cropper} from 'vue-advanced-cropper'

Version from package.json:

"vue-advanced-cropper": "^2.8.1"

Everything works until I get to the crop function where it says the following:
Uncaught TypeError: this.$refs.cropper.getResult is not a function

My first thought was, that it may have something to due with looping through multiple images, however it does not work with juse one either. I have tried combining the part from disc and upload to server from here:
https://norserium.github.io/vue-advanced-cropper/guides/recipes.html#upload-image-to-a-server

NVDA / focus / accessibility Issues

We are building custom dropdown components with a hierarchical selection of checkboxes. Each hierarchy is shown/hidden using standard bootstrap 3 accordion code which handles screen readers very well (this is a Drupal site so bootstrap 3 is the version supported).

We have code controlling the up/down/home/end keys which completely fails to trigger when NVDA is running. Clicking the down arrow is supposed to take you to the next visible checkbox. The home key takes you to the first. The end key takes you to the last.

All this works fine when NVDA is not running. When running, the home/end keys do nothing. The up/down arrow act like tab/shift-tab so they don’t go to the next checkbox; they go to the next tabable element.

This is happening in all browsers.

Does anyone know how to fix this?

Fiddle:
https://jsfiddle.net/1pya0bm3/1/

    $(document).ready(function(){
        $('.region_of_delivery_checkbox').keyup(function(e){
            var code = (e.keyCode ? e.keyCode : e.which);
            var tabables = $(".region_of_delivery_checkbox:visible");
            var index = tabables.index(this);
            console.log(`checkbox and tabables.length = ${tabables.length} and tabables.index(this) is: ${tabables.index(this)}`);
            if(code == 40) {
                console.log("40");
                tabables.eq(index + 1).focus();
                console.log(`tabables.eq(index + 1) is: ${index}`);
            } else if(code == 38) {
                console.log("38");
                tabables.eq(index - 1).focus();
            } else if(code == 35) {
                console.log("35");
                tabables.eq(tabables.length - 1).focus();
            } else if(code == 36) {
                console.log("36");
                tabables.eq(0).focus();
            }
        });
    });

What is an “Object” in a JavaScript NodeJS code?

I saw the following code:

const User = require('../model/User');
const jwt = require('jsonwebtoken');

const handleRefreshToken = async (req, res) => {
    const cookies = req.cookies;
    if (!cookies?.jwt) return res.sendStatus(401);
    const refreshToken = cookies.jwt;

    const foundUser = await User.findOne({ refreshToken }).exec();
    if (!foundUser) return res.sendStatus(403); //Forbidden 
    // evaluate jwt 
    jwt.verify(
        refreshToken,
        process.env.REFRESH_TOKEN_SECRET,
        (err, decoded) => {
            if (err || foundUser.username !== decoded.username) return res.sendStatus(403);
            const roles = Object.values(foundUser.roles);
            const accessToken = jwt.sign(
                {
                    "UserInfo": {
                        "username": decoded.username,
                        "roles": roles
                    }
                },
                process.env.ACCESS_TOKEN_SECRET,
                { expiresIn: '10s' }
            );
            res.json({ roles, accessToken })
        }
    );
}

module.exports = { handleRefreshToken }

And I can not understand what is the Object in this line of code:

const roles = Object.values(foundUser.roles);

I mean is it instance of a class? What class? Where did it instantiated?

Istanbul scripts are not running

No coverage information was collected, exit without writing coverage information
D:JobProjectsToDoListToDosListnode_modules.bintape.CMD:1
@ECHO off
^

SyntaxError: Invalid or unexpected token
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1032:15)
at Module._compile (node:internal/modules/cjs/loader:1067:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
at Object.Module._extensions. [as .js] (D:JobProjectsToDoListToDosListnode_modulesistanbullibhook.js:109:37)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at runFn (D:JobProjectsToDoListToDosListnode_modulesistanbullibcommandcommonrun-with-cover.js:122:16)
at D:JobProjectsToDoListToDosListnode_modulesistanbullibcommandcommonrun-with-cover.js:251:17

@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0

IF EXIST “%dp0%node.exe” (
SET “_prog=%dp0%node.exe”
) ELSE (
SET “_prog=node”
SET PATHEXT=%PATHEXT:;.JS;=;%
)

endLocal & goto #undefined# 2>NUL || title %COMSPEC% & “%_prog%” “%dp0%..tapebintape” %*

could not render component in react

When I use history.push () method, from signup to log in, goes to a particular API/URLenter code here but does not render the login component.

import React, { useState } from "react";
import "./UserRegister.css";
import { Link } from "react-router-dom";
import ing from "../assets/ing.png";
import { message } from "antd";
import { createBrowserHistory } from "history";
const UserRegister = () => {
  const history = createBrowserHistory();
  const [role, setRole] = useState("");
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [mobile, setMobile] = useState("");
  const [password, setPassword] = useState("");
  const [confirmpassword, setConfrimpassword] = useState("");

  console.log({
    role,
    username,
    email,
    mobile,
    password,
    confirmpassword,
  });
  const fetchRegister = () => {
    fetch("/api/user/userregister", {
      method: "post",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        role,
        username,
        email,
        mobile,
        password,
        confirmpassword,
      }),
    })
      .then((res) => res.json())
      .then((data) => {
        console.log(data);
        if (data.error) {
          message.error(data.error);
        } else {
          history.push("/login");
        }
      });
  };

  return (
    <div className="body_body">
      <div className="signup-container">
        <div className="welcome-img">
          <img src={ing} alt="welcome image" height="350px" width="450px" />
        </div>

        <div class="form-container">
          <h2>Create your Account Today ! </h2>

          <p class="title">Sign Up</p>

          <div class="signup-form">
            <div class="form-item selector">
              <span class="item-indicator"></span>
              <label className="select_label" for="role">
                Choose your role
              </label>
              <select
                id="role"
                className="role_select"
                value={role}
                onChange={(e) => setRole(e.target.value)}
              >
                <option value="Student">Student</option>
                <option value="Company">Company</option>
                <option value="Mentor">Mentor</option>
              </select>
            </div>
            <div class="form-item fullname">
              <input
                type="text"
                placeholder="Please enter your username "
                value={username}
                onChange={(e) => setUsername(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>
            <div class="form-item email">
              <input
                type="text"
                placeholder="Enter your email"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>

            <div class="form-item confirm-password">
              <input
                type="text"
                placeholder=" Enter Mobile No"
                name="mobile"
                value={mobile}
                onChange={(e) => setMobile(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>
            <div class="form-item password">
              <input
                type="password"
                placeholder="Enter Password"
                name="password"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>

            <div class="form-item confirm-password">
              <input
                type="password"
                name="Confirmpassword"
                placeholder="Enter Confirm Password"
                value={confirmpassword}
                onChange={(e) => setConfrimpassword(e.target.value)}
              />
              <span class="item-indicator"></span>
            </div>

            <p class="login">
              Already have an account?
              <Link to="login">Login</Link>
            </p>
            <div class="actions">
              <button type="submit" onClick={() => fetchRegister()}>
                Sign Up
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

export default UserRegister;

enter code here

Javascript – Program function in time

I need to write a code in javascript that works 24/7 and constantly detects if today is (for example) Wednesday at 10.00pm, and executes every Wednesday at 10pm (calls a function inside the script) Can you help me with that? I’m still learning JS

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?