How to update modal information without reopening the modal in react native?

I have a modal which opens when a product is clicked and details of that product are displayed in modal there is also a you might also like section of products which have the same view as product now I want that when a you might like product is clicked the modal should update the information without opening a modal above existing modal. How can I do that?

const cartProducts = useSelector(state => state.cart.cartProducts);
const dispatch = useDispatch();
const [MyProducts,setProducts] = useState([]);
const prodCode = product.ItemCode;
const {user} = useSelector(state=>state.auth);

async function fetchProducts(){
 //console.log(prodCode);
 await axios({
               method:'GET',
               url:`${BASE_URL}/items/${prodCode}`,
               headers:{
                   'Authorization': AUTH_KEY,
               }
           })
           .then((response)=>{  
             setIsLoading(false);
             const status = response.data[0]['status'];
             //console.log(status);
             if(status=='success'){
               const items = response.data[0]['body']['related'];
               if(items){
                 //console.log(items);
                 setProducts(items);
               }
               //console.log(Products);
               }
               if(status=='error'){
                 MyToast(status);
               }
           }).catch((error)=>{
             setIsLoading(false);
               MyToast('Error: '+error.message);
               //console.log('Error is: ',error.message);
           });
}

useEffect(()=>{
 if(MyProducts.length === 0 && visible){
 fetchProducts();
 }
},[MyProducts]);

return (
 <Modal
   animationType="slide"
   transparent={true}
   visible={visible}>
   <View style={styles.centeredView}>
     <View style={styles.modalView}>
       <View style={styles.modalClose}>
         <TouchableOpacity style={styles.button} onPress={() => { handlePinClick()}}>
           <IconPin name={isPin ? 'pushpin' : 'pushpino'} size={responsiveWidth(6)} color={Colors.primary} />
         </TouchableOpacity>
         <TouchableOpacity style={styles.button} onPress={() => { handleFavoriteClick() }}>
           <IconFavorite style={{ padding: responsiveWidth(1.5) }} name={'ios-heart'} size={responsiveWidth(8)} color={isFavorite ? 'red' : Colors.grey} />
         </TouchableOpacity>
         <IconClose style={[styles.button, { padding: responsiveWidth(1.5) }]} name='cross' size={responsiveWidth(8.5)} color={Colors.black} onPress={() => onClose()} />
       </View>
       <ScrollView style={{ paddingBottom: responsiveHeight(7) }}>
         <Image style={styles.modalImage} source={{ uri: isFromAll ? product.feature_image : product['item_details'].feature_image }} />
         <Text style={styles.modalProdName}>{isFromAll ? product.ItemName : product['item_details'].ItemName}</Text>
         <ExpandableComponent product={product} isFromAll={isFromAll}/>
           {MyProducts.length !== 0 && 
           <View style={{ paddingVertical: responsiveHeight(1) }}>
           <Text style={styles.youMightText}>You might also Like</Text>
           {isLoading ?
             <View style={{height:responsiveHeight(28),flexWrap:'wrap' }}>
                 {widthList.map((item, index) => <ShimmerItem key={index} item={item} />)}
             </View> :
             <FlatList
               horizontal
               data={MyProducts}
               renderItem={({ item }) => <Product key={item.key} product={item} isFromAll={true}/>}
               ListEmptyComponent={()=><EmptyComponent height={30} text={'No Product!'}/>}
             />
             }
             </View>
             }
       </ScrollView>
       <View style={styles.bottomView}>
         {cartProducts && <BottomSheetScreen itemsCount={cartProducts.length} />}
       </View>
     </View>
   </View>
 </Modal>
)
}


How to decode base64 text to binary file?

I am converting binary file’s buffer to base64 text before storing to mongodb. I am using multer to get image alongside with with other field. I am sending those data in FormData and the back end is

app.post('/image', multer().single('image'), (req, res) => {
    const image = Buffer.from(req.file.buffer).toString('base64')
    database.collection('images').insertOne({image})
}

Now, how do I decode this base64 text to binary image?

I tried this in the front end after getting the json from the back end

URL.createObjectURL(new Blob([window.atob(data.image)]))

But I think the binary file is corrupted.

Is it possible to make a pixelated bitmap font in node-canvas?

I’ve been recently working on a Node.js project that uses node-canvas module.

Although I have a problem. I want to completely disable the font smoothing (like you can do in Paint.net, Photoshop, Adobe Animate, etc), so that the font is pixelated and crisp.

Here’s the picture of the text with the same font and size. The top one is rendered by node-canvas, while the bottom one is how I want it to look like (i.e. unsmoothed, crispy).

hi there

Does anyone know if it’s possible or not?

watch method of fs module in node.js logs the output twice

fs.watch is unstable and not consistent and sometimes reports events twice. I tried other packages out there but still the same thing. I tried the ‘chokidar’ package not to get the double logs, but it doesn’t report all the events if they happen extremely fast, for example doing a thousand writes to a file.

Can someone explain what is happening behind the scenes with C++ APIs and OS while calling the watch method in node.js?

import { log } from "console";
import { watch } from "fs/promises";
(async () => {
  const watcher = watch("./somefile.txt");
  for await (const event of watcher) {
      log(event);
  }
})();

NestJS TypeORM createQueryBuilder SELECT query

I am trying ‘SELECT USER_CODE FROM USERS’ query by TypeORM in nestJS.
My databse is MySQL and this database has ‘users’ table.
the columns are ‘USER_CODE’, ‘USER_EMAIL’, ‘USER_PASSWORD’, ‘USER_PHONE’.
I’ve seen TypeORM official documents several times, but I don’t understand them well.

//service.ts
import { InjectRepository } from '@nestjs/typeorm';
import { Injectable } from '@nestjs/common';
import { Users } from './entity/users.entity';
import { Repository } from 'typeorm';
import { UsersSignupDto } from './dto/users.signup.dto';
import { generateCode } from 'src/common/utils/code.generator';

@Injectable()
export class UsersService {
  constructor(
    @InjectRepository(Users) private userRepository: Repository<Users>,
  ) {}

  async signup(body: UsersSignupDto) {
    const user = await this.userRepository
      .createQueryBuilder()
      .select('users.user_code')
      .from(users,'users')
      .where('users.user_code = :id', { id: '74EQQK' })
      .getOne();
    console.log(user);
   
}

the code returns ‘null’ but I checked that table’s rows are not empty.

but when i tried

const user = await this.userRepository
      .createQueryBuilder()
      .where('users.user_code = :id', { id: '74EQQK' })
      .getOne();
      console.log(user);

It works.. but this qurey gets all informations from table.
I just want to get ‘user_code’ column. How to make it works? or Can someone link me the references information?

Can not start server file of Git Cloned MERN-Stack Backend folder [duplicate]

I cloned the MERN-STACK backend folder from Github. It is our group project. So That backend is working well when it starts by person who created that. But When I tried to run it showed the following error.

node index.js
(node:81836) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/masterlwa/Desktop/new/ITP_Project__GYMLY/backend/src/index.js:1
import "dotenv/config";
^^^^^^
SyntaxError: Cannot use import statement outside a module
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1195:20)
    at Module._compile (node:internal/modules/cjs/loader:1239:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
    at Module.load (node:internal/modules/cjs/loader:1133:32)
    at Module._load (node:internal/modules/cjs/loader:972:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
    at node:internal/main/run_main_module:23:47

I installed node modules to that file and tried to run it using node index.js command (index is a server file). But I show the following error. How to fix it?

Sharing vCard using Web-Share API: Permission Denied

I have the following code to share vCard on my android device.

        <Button
          variant={buttonColorHandler()}
          onClick={handleAddToContact}
        >
          Add to Contact
        </Button>

And handler

const handleAddToContact = async () => {
    console.log('Add to contact');
    console.log(navigator.canShare);
    const res = await fetch('/vcard.vcf');
    const data = await res.blob();
    const file = new File([data], 'vcard.vcf', { type: 'text/vcard' });
    const shareData = {
      files: [file],
      title: 'vCard',
    };

    console.log(shareData);
    console.log(navigator.canShare(shareData)); // getting true here


    navigator
      .share(shareData)
      .then(() => {
        console.log('Data was shared successfully');
      })
      .catch(err => {
        console.log(err);
      });
  };

When I’m running the following code and after clicking on Button I’m getting following exception

DOMException: Permission denied

JavaScript in Qualtrics: Referencing the displayed order of choices

For a question, I have 4 choices (alpha, beta, gamma, delta) displayed in random order through choice randomization. I want the displayed order of these choices to be captured in embedded data fields, to be used later in the survey.
For example, if the choices were displayed

beta
gamma
alpha
delta

I want embedded data fields pos_beta = 1, pos_gamma = 2, pos_alpha=3 and pos_delta=4.

If they were displayed

gamma
alpha
beta
delta

I want embedded data fields pos_gamma = 1, pos_alpha = 2, etc

Easiest way to implement this? (Also, could the answer be generic enough to capture if the choices had random text around the keywords – “blah blah gamma blah blah” etc?)

Thanks in advance!

(I looked at other questions on this site but could not find anything that addresses this).

How to have select/input be an explicit width when inline with a label, but on smaller screens break onto a new line and fill the width?

I have this desktop and mobile broken layout at the moment.

Desktop

Mobile

Code

The code looks like this basically:

button {
  padding: 8px;
}

*, *:after, *:before, *::placeholder {
    padding: 0px;
    margin: 0px;
    border: none;
    color: inherit;
    font-size: inherit;
    font-weight: inherit;
    text-transform: inherit;
    -webkit-font-smoothing: antialiased;
    box-sizing: border-box;
    -webkit-text-size-adjust: none;
    position: relative;
    min-height: 0px;
}

.Container {
    background: #F4F4F4;
    box-shadow: rgba(50,50,93,0.25) 0px 13px 27px -5px, rgba(0,0,0,0.3) 0px 8px 16px -8px;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-flex-direction: column;
    -ms-flex-direction: column;
    flex-direction: column;
    gap: 16px;
    height: calc(100vh - 60px);
    max-width: 720px;
    overflow-y: auto;
    padding-bottom: 16px;
    padding-top: 16px;
    position: fixed;
    top: 60px;
    width: 100%;
    z-index: 1001;
}

.Field1 {
    -webkit-align-items: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    background: #DEDEDE;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    gap: 16px;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    -ms-flex-pack: justify;
    justify-content: space-between;
    padding: 16px;
}

.Label1 {
    font-size: 18px;
    font-weight: bold;
}

input[type="number"] {
    background: #FFFFFF;
    border-radius: 4px;
    box-shadow: rgba(100,100,111,0.2) 0px 7px 29px 0px;
    min-width: 160px;
    padding: 16px;
}

.Field2 {
    -webkit-align-items: center;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    background: #DEDEDE;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-flex-wrap: wrap;
    -ms-flex-wrap: wrap;
    flex-wrap: wrap;
    gap: 16px;
    -webkit-box-pack: justify;
    -webkit-justify-content: space-between;
    -ms-flex-pack: justify;
    justify-content: space-between;
    padding: 16px;
}

.Label2 {
    -webkit-box-flex: 1;
    -webkit-flex-grow: 1;
    -ms-flex-positive: 1;
    flex-grow: 1;
    font-size: 18px;
    font-weight: bold;
    text-align: left;
    white-space: nowrap;
}

.Select {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    background: #FFFFFF;
    background-image: url(data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%22292.4%22%20height%3D%22292.4%22%3E%3Cpath%20fill%3D%22%23282828%22%20d%3D%22M287%2069.4a17.6%2017.6%200%200%200-13-5.4H18.4c-5%200-9.3%201.8-12.9%205.4A17.6%2017.6%200%200%200%200%2082.2c0%205%201.8%209.3%205.4%2012.9l128%20127.9c3.6%203.6%207.8%205.4%2012.8%205.4s9.2-1.8%2012.8-5.4L287%2095c3.5-3.5%205.4-7.8%205.4-12.8%200-5-1.9-9.2-5.5-12.8z%22%2F%3E%3C%2Fsvg%3E);
    background-position: right 16px top 50%,0 0;
    background-repeat: no-repeat;
    background-size: 16px auto;
    border-radius: 4px;
    box-shadow: rgba(100,100,111,0.2) 0px 7px 29px 0px;
    display: block;
    -webkit-flex-basis: 160px;
    -ms-flex-preferred-size: 160px;
    flex-basis: 160px;
    -webkit-box-flex: 1;
    -webkit-flex-grow: 1;
    -ms-flex-positive: 1;
    flex-grow: 1;
    padding: 16px;
}

.mobile {
  width: 320px !important;
}
<button onClick="document.querySelector('.Container').classList.toggle('mobile')">Toggle mobile</button>

<div class="Container">
  <div class="Field Field1">
    <div class="Label Label1">Width</div>
    <input
      type="number"
      value="100"
    />
  </div>
  <div class="Field Field1">
    <div class="Label Label1">Height</div>
    <input
      type="number"
      value="100"
    />
  </div>
  <div class="Field Field2">
    <div class="Label Label2">Fit</div>
    <select class="Select">
      <option value="">None</option>
      <option value="contain">Contain</option>
      <option value="cover">Cover</option>
      <option value="fill">Fill</option>
      <option value="inside">Inside</option>
      <option value="outside">Outside</option>
    </select>
  </div>
</div>

Question

How do I get it so these constraints are all met?

  1. The max width on the select and input is 160px, only when the screen is wide (desktop), and the label and input/select can fit on the same line.
  2. Otherwise, the select box (and input) drop down to the next row and fill the width (I did this currently with flex-wrap and tried to do it with a combo of flex-basis and flex-grow (I only focused on the select so far), but it isn’t leading down the correct road.
  3. The inputs/labels are within 16px of padding of the parent Field container.

The inputs/selects should fill the width on mobile and be underneath the layout, otherwise they should be 160px wide and on the same line. How can it be done using only CSS. A little JS can be used too if necessary, but hoping I don’t just have to get in there and write a complex bit of code measuring element rectangles and parents and children and such, that would be overkill I think.

For development purposes only Google Key map API

I’m using google map on server HTTPS, when I run on web Https, it displays message: ‘For development purposes only’

enter image description here

This is information i have configured on console

enter image description here

I tested on Stagging Dev environment it still success, but i run on web HTTPs it seem still cannot run

How to fix the problem ?

Paypal transactions not going through with standard-integration

Im trying to implement purchasing with paypal
https://github.com/paypal-examples/docs-examples/tree/main/standard-integration

I set up a paypal business account and entered my client-id and secret into the env variable and into the Index.html (I assume its supposed the be the same client ID in both, correct?)

I followed the instructions, except I didn’t log in with my sandbox ID, instead I just sent money with CC

Create an application
Rename .env.example to .env and update CLIENT_ID and APP_SECRET
Replace test in public/index.html with your app's client-id
Run npm install
Run npm start
Open http://localhost:8888
Click "PayPal" and log in with one of your Sandbox test accounts

I have a couple issues:

  1. I followed the instructions npm install and npm start
    I tried sending the default amount to myself, but I dont see anything in the account, eventhough all of the transaction steps were completed in the paypal popup, I entered my CC info and etc. Am I missing something? Is the backend automatically started if I follow those instructions, or maybe it’s not starting the backend?

  2. I cant seem to change the payment value from the front end,
    I did a search and found value: "100" in paypal-api.js, and set it there to $1,
    I want to set the price using an external shopping cart, how can I set the value from Index.html?

  3. What does the sandbox account actually do? I don’t see any instructions on how to use it, I have a username and password for it, does it send money from myself to myself?

Thanks,

Inner HTML not working in this case with a tic-tac-toe ai

Look, I have this for a tic-tac-toe ai:

function checkForThreats() {
  for (let i = 0; i <= 7; i++) {
    var cell = winningConditions[i].indexOf("");
      let index = gameState[cell];
      document.querySelector(`[data-cell-index="${index}"]`).innerHTML = "O";
  }
}

and it gives me an error that I can’t set properties of null, I’m confused on how this would work.

I tried to change and mess with the string interpolation yet it still gave errors.

JavaScript for loop inside a function not work

I’m new to JavaScript.

I want to add a loop inside a function ,so it can loop different ids.

Code:

 function toggleCheckboxArea(onlyHide = false) {
        var checkboxes = document.getElementById("myOptions1");
        var displayValue = checkboxes.style.display;
      
        if (displayValue != "block") {
          if (onlyHide == false) {
            checkboxes.style.display = "block";
          }
        } else {
          checkboxes.style.display = "none";
        }
      }

This function only used one of my ids ,document.getElementById(“myOptions1”); I modified this code ,to let it can loop through 2 ids :

  function toggleCheckboxArea(onlyHide = false) {
    var checkboxes = document.querySelectorAll('#myOptions1,#myOptions2');
    checkboxes.forEach(function(checkboxe){
        var displayValue = checkboxe.style.display;
        if (displayValue != "block") {
          if (onlyHide == false) {
            checkboxe.style.display = "block";
          }
        } else {
          checkboxe.style.display = "none";
        }
    })
  }

However after modifying ,the code not work ,I have no idea where is the bug. Any friend can help ?

React native Bluetooth keyboard support

I have a react native app and I am trying to see how can I support a Bluetooth keyboard for iPads. Right now, what is doing is acting like is typing something but nothing appears on the text input. I am assuming is because react native doesn’t support right off the bat?