How to handle empty cell values in @tanstack/react-table?

I am trying to find an optimal way to handle the empty cell values.
I have following column definition in which all the fields are optional except the name field:

const columnHelper = createColumnHelper<{
    name: string; 
    contact_person?: string; 
    phone_no?: string
}>();

export const countryColumns = () => [
    columnHelper.display({
        header: "S.N.",
        cell: ({ row }) => row.index + 1,
    }),
    columnHelper.accessor("name", {
        header: "Name",
    }),
    columnHelper.accessor("contact_person", {
        header: "Contact Person",
    }),
    columnHelper.accessor("phone_no", {
        header: "Phone Number",
    }),
    columnHelper.display({
        id: "actions",
        header: "Actions",
        cell: ({ row }) => (
      // Buttons
    ),
  }),
];

Here, contact_person and phone_no are optional fields. So, there might be cases where the contact_person and phone_no will be empty in the table. How do I handle it?

export const countryColumns = () => [
    columnHelper.display({
        header: "S.N.",
        cell: ({ row }) => row.index + 1,
    }),
    columnHelper.accessor("name", {
        header: "Name",
    }),
    columnHelper.accessor("contact_person", {
        header: "Contact Person",
        cell: info => info.getValue() ?? "---";
    }),
    columnHelper.accessor("phone_no", {
        header: "Phone Number",
        cell: info => info.getValue() ?? "---";
    }),
    columnHelper.display({
        id: "actions",
        header: "Actions",
        cell: ({ row }) => (
          // Buttons
        ),
    }),
];

Here, I need to check the condition in every optional field. Is this what I should do or there is another workaround?

Also, in the main table component, I tried doing something like this:

{row.getVisibleCells().map(cell => {
    return (
        <Td key={cell.id} pl={6}>
            {cell.getValue() ? flexRender(
            cell.column.columnDef.cell,
            cell.getContext(),
        ) : "---"}
        </Td>
  );
})}

However, this renders “—” in S.N. and “Actions” field too which are display columns. This only seems to work on accessor columns.

Javascript WebSocket: Receiving messages from discord

So. I have a app that communicates with Javascript with a WebView2 Object, in C# WinForms. However, Most of the handling messages is done in javascript/html of course, so i setup a websocket, and it somewhat works? My and ONLY my messages content(s) are being shown, like, if i send a message, then it’ll log it in the console, with the profile picture and all. But if someone else sends a message, then it’ll log the profile picture and name, but not the message content? And then the websocket closes. My token is valid as well.

var ws = new WebSocket("wss://gateway.discord.gg/?v=9&encoding=json");
var interval = 0;

payload = {
    op: 2
    , d: {
        token: ""
        , intents: 512
        , properties: {
            $os: "linux", // this works fine
            $browser: "chrome"
            , $device: "chrome"
        , }
    , }
, };

ws.addEventListener("open", function open(x) {
    ws.send(JSON.stringify(payload));
});

ws.addEventListener("message", function incoming(data) {
    var x = data.data;
    var payload = JSON.parse(x);
    
    const {
        t
        , event
        , op
        , d
    } = payload;
    
    switch (op) {
    case 10:
        const {
            heartbeat_interval
        } = d;
        setInterval(() => {
            ws.send(JSON.stringify({
                op: 2
                , d: null
            }));
        }, heartbeat_interval);
        
        break;
    }
    
    switch (t) {
        // yes targetChannelId is CORRECT.
    case "MESSAGE_CREATE":
        if (d.channel_id === targetChannelId) {
            var final = {
                author: d.author.username
                , content: d.content
                , image: `${d.author.avatar ? `https://cdn.discordapp.com/avatars/${d.author.id}/${d.author.avatar}.png` : 'N/A'}`
            }
            
            appendMessageWithFrame(final); // call
            console.log(d); 
            // this is where i'm confused. d.content is blank when someone else types? but when i type its not blank??
            console.log(`${d.author.username}: ${d.content}, Avatar URL: ${d.author.avatar ? `https://cdn.discordapp.com/avatars/${d.author.id}/${d.author.avatar}.png` : 'N/A'}`);
        }
        break;
    }
});

Tried double-checking my token, it was obviously correct, checked targetChannelId, ALSO correct, checked the d array, still, correct, until someone else types, then d.content is empty and the websocket breaks.

Stripe connect checkout session won’t work with connected account on direct charges PHP

I’m having a lot of trouble in getting my stripe checkout sessions working. Previously before making the payment a direct charge to the connected account and taking a fee, everything was working fine. Now with the updated code, everything functions as expected expect for the url when returning.
Which provides a 500 error, due to the checkout session not being recognized I assume.
The current code for creating a checkout session is below.

try {

            // Calculate the amount in Stripe's smallest unit
            $stripeAmount = $this->calculateStripeAmount($request['amounts'][$configItem['currency']]);

            // Calculate the 10% fee
            $feeAmount = $this->calculateFeeAmount($request['amounts'][$configItem['currency']]);

                

            $session = StripeCheckoutSession::create([
                'payment_method_types' => $paymentMethodTypes,
                'customer_email' => $request['payer_email'],
                'client_reference_id' => $request['order_id'],
                'line_items' => [[
                    'price_data' => [
                        'currency' => $configItem['currency'],
                        'unit_amount' => $this->calculateStripeAmount($request['amounts'][$configItem['currency']]),
                        'product_data' => [
                            'name' => $request['item_name'],
                            'description' => $request['description'],
                        ]
                    ],
                    'quantity' => 1,
                ]],
                'mode' => 'payment',


                'success_url' => getAppUrl($configItem['callbackUrl']) . '?stripe_session_id={CHECKOUT_SESSION_ID}' . '&paymentOption=stripe&orderId=' . $request['order_id'],
                'cancel_url' => getAppUrl($configItem['callbackUrl']) . '?stripe_session_id={CHECKOUT_SESSION_ID}' . '&paymentOption=stripe&orderId=' . $request['order_id'],
                'payment_intent_data' => [
                    'application_fee_amount' => $feeAmount,
                        ],
        

                
                 ], ['stripe_account' => $request['stripe_connect_account_id']],
             );
                    
            

              return $session;
        } catch (Exception $e) {
            //if payment failed set failed message
             $errorMessage = [
                'message' => 'failed',
                'errorMessage' => $e->getMessage(),
                'trace' => $e->getTraceAsString() // This will help in debugging
            ];
            return (array) $errorMessage;
        }
    }

 
        /**
         * Retrieve Stripe data by session Id
         *
         * @param string $sessionId
         *
         * request to Stripe checkout
         *---------------------------------------------------------------- */
        public function retrieveStripeData($sessionId)
        {
            try {
                $sessionData = StripeCheckoutSession::retrieve($sessionId);

                if (empty($sessionData)) {
                    throw new Exception("Session data does not exist.");
                }

                $paymentIntentData = StripePaymentIntent::retrieve($sessionData->payment_intent);

                return $paymentIntentData;
            } catch (StripeErrorInvalidRequest $err) {
                //set error message if payment failed
                $errorMessage['errorMessage'] = $err->getMessage();

                //return error message array
                return (array) $errorMessage;
            } catch (StripeErrorCard $err) {
                //set error message if payment failed
                $errorMessage['errorMessage'] = $err->getMessage();

                //return error message array
                return (array) $errorMessage;
            }
        }

Here is the front end in another file, ignore the public key not using the variable as that is on purpose and needs to be removed.

if(payWidth == 'stripe'){
            $(".payment_method_box").css("pointer-events", "auto");
            $(".loaderWrapper").remove();
            //config data For Stripe
            var configData = <?php echo json_encode($PublicConfigs); ?> ,
            configItem = configData['payments']['gateway_configuration']['stripe'],
                userDetails = <?php echo json_encode($DataUserDetails); ?> ,
            stripePublishKey = '';
            //check stripe test or production mode
            if (configItem['testMode'] === 'true') {
                stripePublishKey = '<?php echo $stripePaymentTestPublicKey;?>';
            } else {
                stripePublishKey = '<?php echo $stripePaymentLivePublicKey;?>';
            }
            /*if (configItem['testMode']) {
                stripePublishKey = configItem['stripeTestingPublishKey'];
            } else {
                stripePublishKey = configItem['stripeLivePublishKey'];
            }*/
            userDetails['paymentOption'] = payWidth;
            userDetails['f'] = 'processProduct';
            userDetails['creditPlan'] = planID;
            // Stripe script for send ajax request to server side start
            $.ajax({
                type: 'post', //form method
                context: this,
                url: siteurl + 'requests/request.php', // post data url
                dataType: "JSON",
                data: userDetails, // form serialize data
                error: function(err) {
                    var error = err.responseText
                    string = '';
                    alert(err.responseText);
                },
                success: function(response) {
                    //alert(response.id);
                    var stripe = Stripe('pk_test_51NfvLOJKlCTqPFwWMLFchWWnSWqy8v1JECWnjMSUxaUfomcl1ru5gSpxh3u395GPwDy23oVMK7tFpfAYuhkOkZwl009owSqTbq', {
                        stripeAccount: ('<?php echo $stripeConnectAccountId;?>')
                    });
                    //alert(stripe);
                    stripe.redirectToCheckout({
                        sessionId: response.id,
                    }).then(function(result) {
                        var string = '';
                        alert(result.error.message);
                    });
                }
            });
        }

Aswell as the error provided by stripe logs below. enter image description here

I’m very new to js and php, which may show in the code. I’m aware this is a lot to ask, but if anyone could provide guidance on where the issue may be arising from it would be greatly appreciated.

One idea I’ve had is that the customer might be getting created under the platform, while the checkout session is under the connected account. I’ve attempted to create a customer and use the same line with stripe_account but the result was the same.

How to make a custom element that appends each character in a ?

I’m attempting to implement this functionality for a typing website so that every character that is entered will be enclosed in a span. However, I was unable to figure out how to make a custom text-editable <div> instead of a <textarea>.

Here is how the output should look.

<div className="typableCustomDiv">
    <span>H</span>
    <span>E</span>
    <span>L</span>
    <span>L</span>
    <span>O</span>
</div>

The reason why I want to enclose them in a span to imitate a <textarea> is for the following reasons:

  1. Incorrect characters will have a strikethrough and be colored red.
  2. Green will be used to highlight the correct characters.
  3. Create a transition such that each character you type should appear gradually, with an ease of 0.25 seconds from opacity 0 to 1.
  4. etc.

setTimeout usage causing solution to fail

I have been recently practicing DSA in JS and here is the solution to one of my problems related to limiting the time to store a key in cache. Below is the code and the solution of it. My output differs from the expected one (ignore the first null, I have not added its console log in code below), please help me understand what can be the issue.

function TimeLimitedCache(){
    this.cache = {};
    
    this.set = function (key, value, duration) {
        let timer;
        let result = false;
        if(key in this.cache){
            clearTimeout(timer);
            result = true;
        }
        this.cache[key] = value;
        timer = setTimeout(()=> delete this.cache[key],duration);
        return result;
    }

    this.get = function(key){
        return this.cache[key] ? this.cache[key] : -1;
    }

    this.count = function(){
        return Object.keys(this.cache).length;
    }
    
}

const start = new Date().getSeconds();
const tesr = new TimeLimitedCache();

setTimeout(()=>console.log(tesr.set(1,42,50)),start)
setTimeout(()=>console.log(tesr.set(1,50,100)),start+40)
setTimeout(()=>console.log(tesr.get(1)),start+50)
setTimeout(()=>console.log(tesr.get(1)),start+120)
setTimeout(()=>console.log(tesr.get(1)),start+200)
setTimeout(()=>console.log(tesr.count(1)),start+250)

enter image description here

How to import *.so binary in React Native for Android

The manufacturer gave me an audio codec binary ‘libasc_decoder.so’. From what I’ve read, binary can just be included in ‘main/jniLibs’, and it’ll be automatically compiled with the project. Then I just have to call System.loadLibrary("asc_decoder"). I built apk and analyzed apk, and I see the binary file in lib folder. However, when I call the native method init(), I get error ‘implementation not found’.

I also see suggestions to just name it ‘libs’ instead of ‘jniLibs’, and add sourceSet in ‘app/build.gradle’

sourceSets {
  main {
    jniLibs.srcDirs = ['./src/main/libs']
    jni.srcDirs = []
  }
}

In both cases, when I run ‘Analyze APK…’ in android studio. I can see the binary was successfully compiled. but when below code doesn’t load any binary method at all

public class ASCDecoder {
  static {
    System.loadLibrary("asc_decoder");
  }

  public final static int ASC_I = 1;
  public final static int ASC_II = 2;
  public final static int ASC_III = 3;
  public final static int ASC_IV = 4;
  public final static int ASC_V = 5;
  public final static int ASC_VI = 6;
  public final static int ASC_VII = 7;

  public native short init(short codec);
  public native int readHead(short[] bytes);
  public native short[] decode(short[] bytes, short len, short codec);
  public native static void destroy();
}

Module not found: Error: Can’t resolve ‘./src/main.js’ in ‘C:UsersCarolina_MuñozDesktopvue-internships4u-main’

Do you know how to fix this error?. I have tried different things like deleting my package.json and creating a new one and a series of npm commands but nothing seems to work. I would like to attach a copy of my current package.json, main.js and directory:

package.json

{
  "name": "internships4u",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint",
    "start": "webpack-dev-server --open --config webpack.config.js"
  },
  "dependencies": {
    "core-js": "^3.8.3",
    "firebase": "^10.6.0",
    "vue": "^3.2.13",
    "vue-router": "^4.0.3"
  },
  "devDependencies": {
    "@babel/core": "^7.23.6",
    "@babel/eslint-parser": "^7.23.3",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-router": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^7.32.0",
    "eslint-plugin-vue": "^8.7.1",
    "sass": "^1.32.7",
    "sass-loader": "^12.0.0",
    "vue-loader": "^15.11.1",
    "vue-template-compiler": "^2.7.15"
  }
}

main.json

import { createApp } from 'vue'
import App from './App.vue'
import router from './router'


createApp(App).use(router).mount('#app')

[enter image description here](https://i.stack.imgur.com/Ap4a2.png)

I have tried the following npm commands among others:

npm install
npm install -g npm@latest
npm cache clean -f
npm install --save-dev eslint babel-eslint @babel/core @babel/eslint-parser eslint-plugin-vue

How to send datapicker value from API in React?

I have created simple react Datepicker application. I get date from API stored useState() function const [datebirth, setDateBirth] = useState(''); after I changed date will send request another API. I want to update API. I will provide my code.

my handleChangeInput:

const handleChangeInput = (e) => {
    const { name, value } = e.target;
    setDatas((prevState) => ({
      ...prevState,
      [name]: value,
    }));
  };

Datepicker Stored Date useState:

const [datebirth, setDateBirth] = useState('');

Get Date From API this format yyyy-MM-dd:

useEffect(() => {
    fetchData();
  }, [decryptedAccessToken]);

  const fetchData = async () => {
    try {
      const response = await axios.get(
        "https://rwood.znapay.in:5000/allcontactsbyID/" + id,
        {
          headers: { Authorization: `Bearer ${decryptedAccessToken}` },
        }
      );
      const data = response.data[0].contact_details;
       
      var d_o_b=response.data[0].contact_details.birthdate;
      console.log(dataLength); 
      setDatas(data);
      const dob = parse(d_o_b, 'yyyy-MM-dd', new Date());
      const dobresult = format(dob, 'yyyy-MM-dd'); 
      setDateBirth(dobresult)
      setTimeout(() => {
        $("#quotes").DataTable();
        $("#history").DataTable();
      }, 10);
    } catch (error) {
      console.error(error);
    }
  };
  

Update API:

  const handleSaveEdit = (e) => {
        e.preventDefault();  
        
        const responseData={
          "saluation":datas.saluation,
          "first_name":datas.first_name,
          "last_name":datas.last_name, 
          "birthdate":datebirth,
          "title":datas.title,
          "account_name":datas.account_name,
          "reports_to":datas.reports_to,
          "contact_email":datas.contact_email,
          "contact_mobile":datas.contact_mobile,
          "contact_owner":datas.contact_owner,
          "department":datas.department,
          "lead_source":datas.lead_source,
          "mail_street":datas.mail_street,
          "mail_postal_code":datas.mail_postal_code,
          "mail_city":datas.mail_city,
          "mail_state":datas.mail_state,
          "mail_country":datas.mail_country
          
        };
        
        fetch(`https://rwood.znapay.in:5000/contact/update/${id}`, {  
          method: 'PUT',
          body: JSON.stringify(responseData),
          headers: { Authorization: `Bearer ${decryptedAccessToken}`,
                  'Content-Type': 'application/json' },
             
        })
          .then((response) => response.json())
          .then((updatedData) => {
            console.log(updatedData) 
            console.log(JSON.stringify(responseData))
            if(updatedData.msg==='contact updated successfully'){
             
              // fetchData();
          }
           
            setData(updatedData);
            setIsEditMode(false);
          })
          .catch((error) => console.error(error));
      };

My form:

<>
          
            <p className='edit-btn'>
     <button className='btn btn-primary' onClick={handleSaveEdit}>Save</button>
     <button className="btn btn-primary" onClick={handleCancelEdit}>Cancel</button>
     
     
     </p>
     <Row className="mb-3">
     
     <div className='col-md-12'>
     <h4 className='heading'>Contact Information</h4>
     </div>
     
     <Form.Group
     as={Col}
     md="6"
     id='' 
     >
     <FloatingLabel controlId="floatingSelect" className='dropDown' label="Salutation">
     <Form.Select aria-label="Floating label select example"
     name="saluation" 
     placeholder="Salutation"
     defaultValue={datas.saluation || ""}
     onChange={handleChangeInput}
     >
     <option value='' disabled>--None--</option>
     <option value="Mr">Mr</option>
     <option value="Ms">Ms</option> 
     <option value="Mrs">Mrs</option> 
     <option value="Dr">Dr</option> 
     <option value="Prof">Prof</option> 
     </Form.Select> 
     </FloatingLabel>
     </Form.Group>
     <Form.Group
     as={Col}
     md="6"
     
     >
     <FloatingLabel
     controlId="floatingInput"
     label="First Name"
     className="mb-3"
     >
     <Form.Control
     type="text"
     placeholder="First Name"
     name="first_name"
     defaultValue={datas.contact_full_name || ""}
     onChange={handleChangeInput}/> 
     </FloatingLabel>
     
     </Form.Group>
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Last Name"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Last Name" 
     name="last_name"
     defaultValue={datas.last_name || ""}
     onChange={handleChangeInput}/>
     
     </FloatingLabel>
     </Form.Group>
     
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Birth Date"
     className="mb-3 datepick"
     
     
     >
     <DatePicker
     selected={startDate1}
     onChange={(date) => setStartDate1(date)}
     customInput={<CustomInput />}
     dayClassName={() => "example-datepicker-day-class"}
     popperClassName="example-datepicker-class"
     todayButton="TODAY"
     dateFormat='yyyy-MM-dd'
     
     placeholderText='Birth Date'
     />
     </FloatingLabel>
     </Form.Group>
     
     
     
     <Form.Group as={Col} md="6">
     
     <FloatingLabel controlId="floatingSelect" 
     className='dropDown' label="Account name">
     <Form.Select aria-label="Floating label select example"
     name="account_name"
     id='account_name' 
     placeholder="Account name" 
     defaultValue={datas.account_name || ""}
     onChange={handleChangeInput}
     
     > 
     <option value='' >Select</option>
     {
     accountNames.map((x)=>{
     return(
     <option value={x.account_name}>{x.account_name}</option>
     )
     })
     }
     </Form.Select> 
     </FloatingLabel>
     </Form.Group> 
     
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Reports to"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Reports to" 
     name="reports_to"
     defaultValue={datas.reports_to || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     
     
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Contact Owner"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Contact Owner" 
     name="contact_owner"
     defaultValue={datas.contact_owner || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Department"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Department" 
     name="department"
     defaultValue={datas.department || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     
     <Form.Group as={Col} md="6">
     
     <FloatingLabel controlId="floatingSelect" 
     className='dropDown' label="Lead Source">
     <Form.Select aria-label="Floating label select example"
     name="lead_source"
     id='account_name' 
     placeholder="Account name" 
     defaultValue={datas.lead_source || ""}
     onChange={handleChangeInput}
     > 
     <option value="">--None--</option>
     <option value="Advertisement">Advertisement</option>
     <option value="Customer Event">Customer Event</option>
     <option value="Employee Referral">Employee Referral</option>
     <option value="Google AdWords">Google AdWords</option>
     <option value="Other">Other</option>
     <option value="Partner">Partner</option>
     <option value="Purchased List">Purchased List</option>
     <option value="Trade Show">Trade Show</option>
     <option value="Webinar">Webinar</option>
     <option value="Website">Website</option>
     <option value="Rajgopalan">Rajgopalan</option>
     <option value="Olivia">Olivia</option>
     
     </Form.Select>
     
     </FloatingLabel>
     </Form.Group> 
     
     
     
     </Row>
     <Row>
     <div className='col-md-12'>
     <h4 className='heading'>Contact Information</h4>
     </div>
     <Form.Group as={Col} md="6" id='contact-title'>
     <FloatingLabel
     controlId="floatingInput"
     label="Title"
     className="mb-3"
     >
     
     <Form.Control
     type="text" 
     placeholder="Title" 
     name="title"
     defaultValue={datas.title || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Contact Email"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Contact Email" 
     name="contact_email"
     defaultValue={datas.contact_email || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     
     
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Contact Mobile"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Contact Mobile" 
     name="contact_mobile"
     defaultValue={datas.contact_mobile || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     
     </Row>
     
     <Row>
     <div className='col-md-12'>
     <h4 className='heading'>Address Information</h4>
     </div>
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Mail Street"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Mail Street" 
     name="mail_street"
     defaultValue={datas.mail_street || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Mail postal code"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Mail postal code" 
     name="mail_postal_code"
     defaultValue={datas.mail_postal_code || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Mail city"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Mail city" 
     name="mail_city"
     defaultValue={datas.mail_city || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Mail state"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Mail state" 
     name="mail_state"
     defaultValue={datas.mail_state || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     <Form.Group as={Col} md="6">
     <FloatingLabel
     controlId="floatingInput"
     label="Mail country"
     className="mb-3"
     >
     
     <Form.Control type="text" 
     placeholder="Mail country" 
     name="mail_country"
     defaultValue={datas.mail_country || ""}
     onChange={handleChangeInput}/>
     </FloatingLabel>
     </Form.Group>
     
     </Row>
     <p className='edit-btn'>
     <button className='btn btn-primary' onClick={handleSaveEdit}>Save</button>
     <button className="btn btn-primary" onClick={handleCancelEdit}>Cancel</button>
     
     
     </p> </>

Sticky element makes popover content not close

I am using a MudTable with freeze first 3 columns (with sticky position). The first column has a MudMenu. When I click on the menu, a modal (or popover content) appears with an overlay. The problem is the modal won’t disappear when I click on the first three columns (region with sticky position). It makes same modal appears multiple times when I click on other menu.

I tried to change the z-index of all elements but it didn’t work.

This seems a common problem with sticky elements and overlay.

enter image description here

The contact form for bloggers becomes unresponsive approximately six hours after updating the homepage

The contact form on my blogger website’s homepage becomes unresponsive after approximately six hours. However, it starts working again when I make any updates to the homepage. I’m puzzled about why this is occurring. For instance, on my website https://www.hotelpeacefulphaplu.com.np/, after updating the homepage, the contact form operates for six hours before ceasing to function, displaying an error in the console that reads:

NOTE(https://www.hotelpeacefulphaplu.com.np/): I have updated the page so it might working till 9:36 AM Wednesday, December 27, 2023 GMT.

“Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.blogger.com/contact-form.do. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.”

Moreover, I have another blogger website (https://www.kalashsoap.com/p/index.html) that hasn’t been updated within this six-hour timeframe. On this site, the contact form is also not functioning and shows the same error.

However, the issue does not seem to persist on other pages besides the homepage, and they do not require updates to maintain functionality.

How to optimise reading in millions of data | AoC 2023 Day 5 Part 2 | JavaScript

I need a bit of help with my Part 2 solution for day 5. My code below works fine with the sample data provided in the exercise brief, and it returns the correct answer. However, when I replace my input data with the provided puzzle input data I keep getting memory issues related errors, or it just takes forever to run and then it eventually flatlines. I’m using Visual Studio Code and node.js, if that helps.

I’d appreciate any help in optimising my code. ChatGPT wasn’t that helpful with making the code more efficient. Thanks in advance! 🙂

const fs = require('fs');

function readFile(filePath) {
    try {
      return fs.readFileSync(filePath, 'utf-8');
    } catch (error) {
      console.error(`Error reading file: ${error.message}`);
    }
}  

// pull in the .txt file input data
let input = readFile('G:/My Drive/Visual Studio Code/Advent of Code/2023/day05.txt').split(/r?n/);

function isNumberInRange(number, start, end) {
    return number >= start && number <= (start + end);
}

function mappedNumber(number, start, mapStart) {
    return (number - start) + mapStart;
}

function mapSeeds2Location(seeds, location, mapping) {
    for (const originalSeed of seeds) {
        let seed = originalSeed; // we want to keep the original seed number so the mapSeeds2Location function is able to continue through the other seed numbers
    
        for (let i = 0; i < mapping.length; i++) {    
                  
            for (const map of mapping[i]) {
                var maps = map.split(" ").map(Number);
        
                if(isNumberInRange(seed, maps[1], maps[2])) {                    
                    seed = mappedNumber(seed, maps[1], maps[0]); // replace the original seed number with the next mapped number
                    break; // once we have mapped a number, then move onto the next mapping
                };                
            }
    
            // once we get to the final mapping (humidity-to-location) then push the location value to the array
            if(i == mapping.length - 1) {
               location.push(seed);
            }
        };    
    }
}

const arrays = input.reduce((acc, item) => (item === '' ? acc.push([]) : acc[acc.length - 1].push(item), acc), [[]]);

var [seeds, ...mapping] = arrays; // separate the first array from the rest - this is to separate the list of seeds

seeds = seeds[0].split(" ");
seeds.shift();
seeds = seeds.map(Number);
var location = [];

console.log(seeds);

/* Part One
mapSeeds2Location(seeds, location, mapping)
console.log("part one answer = " + Math.min(...location));*/

// Part Two
for (let x = 0; x < seeds.length; x+=2) {
    for (let y=0; y<seeds[x+1]; y++) {
        // for each seed in the range, find the mapped location number
        mapSeeds2Location([y + seeds[x]], location, mapping)
    }
}

let minLocation = location[0];
for (let i = 1; i < location.length; i++) {
    if (location[i] < minLocation) {
        minLocation = location[i];
    }
}

console.log("part two answer = " + minLocation);

// console.log("part two answer = " + Math.min(...location));
// Apparently Math.min() hinders performance if the array is large, thats why I had commented it out

How to use html template in react

I am confused on how should I use HTML template in React. The template is an admin dashboard and have multiple pages. I already copy the HTML codes and paste it into jsx files and fix the syntax.

What I’m currently doing:

  1. For each pages I make it into separate components. For example, Dashboard.jsx, Calendar,jsx and etc.

  2. For repeating items such as Navbar, Menu Side Bar and Footer, I make each of them in their own component. For example, Navbar.jsx, MenuSideBar.jsx and Footer.jsx.

  3. Import the script and css tags at index.html of React.

  4. Install related npm packages.

  5. Copy the HTML template’s assets folder and paste it under React’s public folder.

What I’m confused about:

  1. None of the js libraries are working unless if the component is inside React’s index.html. I can’t put the component’s codes inside index.html since I want to reuse the code. So what makes the js libraries aren’t working? Is it because the js libraries are corrupted or other files are the problem.

For example:

Left side bar is using metis menu npm package to make a menu bar. But the dropdowns are not working. Supposedly it can collapse and expand.

So right now
what should I do to make the components to work? This is my first time using HTML template in React. Any advice are greatly appreciated. Thank you.

Output

enter image description here

Left Side Bar

  • LeftSideBar.jsx
    (i’m not sure how to paste my without pasting all 400+ lines)
    enter image description here

  • App.js

import React from 'react';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom';
import Navbar from './Components/Navbar';
import Index from './Components/Index';
import LeftSideBar from './Components/LeftSideBar';
import Footer from './Components/Footer';
import Chat from './Components/Chat';

function App() {
  return (
    <Router>
      <Navbar />
      <LeftSideBar />
      <Footer />
      <Routes>
        <Route exact path="/index" element={<Index/>} />
        <Route exact path="/" element={<Index/>} />
        <Route exact path="/chat" element={<Chat/>} />
      </Routes>
    </Router>
  );
}

export default App;
  • index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import MetisMenu from 'react-metismenu';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

reportWebVitals();

  • index.html
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />    
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    
    <title>React App</title>
    <link
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"
      crossorigin="anonymous"
    />
    <meta content="Premium Multipurpose Admin & Dashboard Template" name="description" />
    <meta content="Themesdesign" name="author" />

    <!-- plugin css -->
    <link href="assets/libs/admin-resources/jquery.vectormap/jquery-jvectormap-1.2.2.css" rel="stylesheet" type="text/css" />
    <!-- Bootstrap Css -->
    <link href="assets/css/bootstrap.min.css" id="bootstrap-style" rel="stylesheet" type="text/css" />
    <!-- Icons Css -->
    <link href="assets/css/icons.min.css" rel="stylesheet" type="text/css" />
    <!-- App favicon -->
    <link rel="shortcut icon" href="assets/images/favicon.ico">
     <!-- App Css-->
     <link href="assets/css/app.min.css" id="app-style" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <!-- JAVASCRIPT -->
    <script src="assets/libs/jquery/jquery.min.js"></script>
    <script src="assets/libs/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="assets/libs/metismenu/metisMenu.min.js"></script>
    <script src="assets/libs/simplebar/simplebar.min.js"></script>
    <script src="assets/libs/node-waves/waves.min.js"></script>

    <!-- apexcharts -->
    <script src="assets/libs/apexcharts/apexcharts.min.js"></script>

    <!-- Plugins js-->
    <script src="assets/libs/admin-resources/jquery.vectormap/jquery-jvectormap-1.2.2.min.js"></script>
    <script src="assets/libs/admin-resources/jquery.vectormap/maps/jquery-jvectormap-world-mill-en.js"></script>
    <script src="assets/js/pages/dashboard.init.js"></script>
    <script src="assets/js/app.js"></script>
    <div id="root" class="py-5"></div>
    
  </body>
</html>

When using the Eris API, it is not possible to use the API with my own uploaded shapefile

When I was writing the webgis, I used eris’ API. The tutorial only taught how to use their own URL. When I used my own uploaded URL, it gave an error. How can I use my own URL?

<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no">
  <title>ArcGIS Maps SDK for JavaScript Tutorials: Add a feature layer</title>
  <style>
    html, body, #viewDiv {
      padding: 0;
      margin: 0;
      height: 100%;
      width: 100%;
    }
  </style>
  <link rel="stylesheet" href="https://js.arcgis.com/4.28/esri/themes/light/main.css">
  <script src="https://js.arcgis.com/4.28/"></script>

  <script>
  require([
    "esri/config",
    "esri/Map",
    "esri/views/MapView",

    "esri/layers/FeatureLayer"

  ], function(esriConfig, Map, MapView, FeatureLayer) {

  esriConfig.apiKey = "YOUR_API_KEY";

  const map = new Map({
    basemap: "arcgis/topographic"
  });

  const view = new MapView({
    container: "viewDiv",
    map: map,
    center: [-118.80543,34.02700],
    zoom: 13
  });

//Trailheads feature layer (points)
  const trailheadsLayer = new FeatureLayer({
    url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads/FeatureServer/0"
  });

  map.add(trailheadsLayer);

//Trails feature layer (lines)
  const trailsLayer = new FeatureLayer({
    url: "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trails/FeatureServer/0"
  });

  map.add(trailsLayer, 0);

// Parks and open spaces (polygons)
  const parksLayer = new FeatureLayer({
    url: "https://services3.arcgis.com/qPQQycqtkiAa89x6/arcgis/rest/services/xishan/FeatureServer"
  });

  map.add(parksLayer, 0);

  });
</script>

</head>
<body>
  <div id="viewDiv"></div>
</body>
</html>

I tried to change the URL to my own, but it will throw an error saying it cannot find my URL in the FeatureLayer.

Investment algorithm. How can I create a function that helps users find the amount that they need to invest?

Heres the problem:

Everytime you invest in a binary option you have 60% chances of winning and 40% chances of loosing. You start with a budget of $1000 and everytime you win, you win 1.3x. So if you invest $10 you will win $13.

So as an example:

  • Round 1: Start with $1000 and invest $10. Now you have $990. Result: you win. You win $13, now you have a budget of $1003.
  • Round 2: Start with $1003 and invest $10. Now you have $993. Result: you win. You win $13, now you have a budget of $1006.
  • Round 3: Start with $1006 and invest $10. Now you have $996. Result: you win. You win $13, now you have a budget of $1009.
  • Round 4: Start with $1009 and invest $10. Now you have $999. Result: you win. You win $13, now you have a budget of $1012.
  • Round 5: Start with $1012 and invest $10. Now you have $1002. Result: you lose. You don´t earn anything and lose what you invested, now you have a budget of $1002 and in the next round you need to invest an amount that makes you have a budget of $1012 (the highest historical budget).
  • Round 6: Start with $1002 and invest $X. Now you have ($1002 – $X). Result: you lose. You don´t earn anything and lose what you invested, now you have a budget of ($1002 – $X) and in the next round you need to invest an amount that makes you have a budget of $1012 (the highest historical budget).
  • Round 7: Start with ($1002 – $X) and invest $Y. Now you have ($1002 – $X – $Y). Result: you lose. You don´t earn anything and lose what you invested, now you have a budget of ($1002 – $X – $Y) and in the next round you need to invest an amount that makes you have a budget of $1012 (the highest historical budget).
  • Round 8: Start with ($1002 – $X – $Y ) and invest $Z. Now you have ($1002 – $X – $Y – $Z). Result: you win. You win $W, now you have a budget of $1012 again.
  • Round 9: Start with $1012 and invest $10. Now you have $1002. Result: you win. You win $13, now you have a budget of $1015.
  • Round 10: Start with $1015 and invest $10. Now you have $1005. Result: you win. You win $13, now you have a budget of $1018.

As you can see, when you are winning you keep investing only $10 but when you loose you need to find a number that its 1.3x gives you as a result the highest historical budget.

I need to create a function in Javascript like this calculateInvestment(currentBudget, historicalHighestBudget) and it should return the amount that the user needs to invest in order to reach the historicalHighestBudget. Taking into account the profit which is 1.3x.

For example if the function were like this calculateInvestment(1000, 1003) the function should return 10. This is the case in round one.

Thanks in advance.