Download file from cloud storage into cloud function temporarily

Having a hell of a time getting this to work. I wrote a cloud function to create PDFs. The PDFs can have images that are downloaded from cloud storage. All of this is not publicly accessible and all permissions are fine.

I’m able to see the metadata of the file I’m attempting to download, but the actual act of downloading to the filesystem temporarily is where I’m stuck. What I get is an empty array: [].

  const functions = require('@google-cloud/functions-framework');
  const {Storage} = require('@google-cloud/storage');

  functions.http('<my func>', async (req, res) => {
       const bucketName = '<my bucket>';
       const fileName = 'mytest.jpg';
       const cwd = path.join(__dirname, '..');
       const destFileName = path.join(cwd, 'tmp/mytest.jpg');

       const options = {
            destination: destFileName
       }

       const [meta] = await storage.bucket(bucketName).file(fileName).getMetadata();
       console.log(meta) <-- this is populated with the files metadata
       
       const file = await 
           storage.bucket(bucketName).file(fileName).download(options);
       console.log(file) <-- this is always []
      
       ....
 }

I’ve tried a few things I’ve seen in other posts with createReadStream()/createWriteStream() but no dice there either, namely because file is an empty array.

The above code is taken from the docs here: Here and Here

Thanks in advance for some guidance

Send an email with attachments via the GMAIL api from a webpage

I’m trying to send an email with attachments via js from a webpage, with the Gmail api. I managed to log in, to send an email without attachments But I got an error when I try to add attachments. The error is:

Uncaught TypeError: files[i] is undefined
onload http://localhost:8000/:189
sendEmailWithAttachments http://localhost:8000/:182
debugger eval code:1
Anyway files[i] is not undefined and I can see that from the console.log. The files attribute is from an input file element on the dom.

I tryed this

function sendEmailWithAttachments(to, subject, body, files) {
var message = new Object();
message.to = to;
message.subject = subject;
message.body = body;
var boundary = 'foo_bar_baz';
var multipart = '';
for (var i = 0; i < files.length; i++) {
var reader = new FileReader();
console.log("il primo file è ",files[i].name)
reader.readAsDataURL(files[i]);
reader.onload = function () {
if(reader.result!=undefined){
var base64Data = reader.result.split(",")[1];
multipart += '--' + boundary + 'rn' +
'Content-Type: application/octet-streamrn' +
'MIME-Version: 1.0rn' +
'Content-Transfer-Encoding: base64rn' +
'Content-Disposition: attachment; filename="' + files[i].name + '"rnrn' +
base64Data + 'rn';} else{
console.log("reader.result contains: ",reader.result)
}
};
}
var request = gapi.client.gmail.users.messages.send({
'userId': 'me',
'resource': {
'raw': window.btoa(
"Content-Type: multipart/mixed; boundary="" + boundary + ""rn" +
"MIME-Version: 1.0rn" +
"to: " + to + "rn" +
"subject: " + subject + "rnrn" +
"--" + boundary + "rn" +
"Content-Type: text/plain; charset="UTF-8"rn" +
"MIME-Version: 1.0rn" +
"Content-Transfer-Encoding: 7bitrnrn" +
body + "rnrn" +
multipart +
"--" + boundary + "--"
)
}
});
request.execute(function(response) {
console.log(response);
});
}

serviceWorker notificationclick never fires using Blazor WASM .NET Core Hosted

Everything else thus far has worked fine, but it seems like notificationclick just doesn’t want to fire at all.

I have this in service-worker.js:

self.addEventListener('notificationclick', function(event) {
    console.log("Notification clicked");
    event.notification.close();
    // Define actions to take when the notification is clicked
    event.waitUntil(
        console.log("Notification clicked"),
        clients.matchAll({ type: 'window' }).then(windowClients => {
            // This is where you'd put your logic for handling the notification click
            // For example, focusing an existing window or opening a new one
            console.log("Handling notification click inside waitUntil");

            // Example: Open a new window if no client windows are open
            if (!windowClients.length) {
                return clients.openWindow('https://example.com');
            }
        })
    );
});

self.addEventListener('push', event => {
    const data = event.data.json();
    console.log(data, "Notification data");
    event.waitUntil(
        self.registration.showNotification(data.title, {
            body: data.body,
            icon: data.icon,
            data: { callbackUrl: data.callbackUrl }
            //actions: [{ action: 'view', title: 'View' }]
        })
    );
});

This is how I setup my push notifications and subscriptions and everything except the notificationclick handler is working.

This is in jsfunctions.js and gets called when SignalR connects:

async function subscribeToPush(signalRService) {
    console.log("Checking for existing subscription...");
    const serviceWorker = await navigator.serviceWorker.ready;
    const existingSubscription = await serviceWorker.pushManager.getSubscription();

    if (existingSubscription) {
        console.log("Existing subscription found. Verifying with server...");
        // Send the existing subscription to the server for verification
        const isVerified = await sendSubscriptionToServer(signalRService, existingSubscription);
        console.log("Subscription verified with the server.");
    } else {
        console.log("No existing subscription found. Creating new subscription.");
        await createAndSendSubscription(signalRService);
    }
}

async function createAndSendSubscription(signalRService) {
    const serviceWorker = await navigator.serviceWorker.ready;
    const subscription = await serviceWorker.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array('key')
    });

    console.log("Subscription", subscription);
    console.log("Sending subscription to backend...");

    var finalSub = {
        endpoint: subscription.endpoint,
        p256dh: arrayBufferToBase64(subscription.getKey("p256dh")),
        auth: arrayBufferToBase64(subscription.getKey("auth"))
    };

    try {
        await signalRService.invokeMethodAsync("SendSubscriptionToBackend", finalSub);
        console.log("Subscription sent to backend successfully.");
    } catch (exception) {
        console.log("Error sending subscription to backend", exception);
    }
}
async function sendSubscriptionToServer(signalRService, subscription) {
    var finalSub = {
        endpoint: subscription.endpoint,
        p256dh: arrayBufferToBase64(subscription.getKey("p256dh")),
        auth: arrayBufferToBase64(subscription.getKey("auth"))
    };

    try {
        await signalRService.invokeMethodAsync("SendSubscriptionToBackend", finalSub);
        console.log("Subscription sent to backend successfully.");
        return true;
    } catch (exception) {
        console.log("Error sending subscription to backend", exception);
        return false;
    }
}

The problem is that notificationclick never logs anything to console or seems to do anything at all when I click the notification.

It’s worth noting that I’m testing this in visual studio locally at the moment using the IIS default debugger.

Wrapping an external library initialization function with just an error callback using async / await syntax

I’m using an external library that provides an initialization function.
That function accepts a parameter and only an error callback as inputs:

SampleLib.Initialize(
    identifier,
    (error: string) => { // error callback
        // handle error
    });

I would like to wrap it into an async function in order to be complaint with async / await syntax.

This is my attempt to do so. Do you think that I’m missing something?

async function utilitySampleLibInitialize(identifier: string): Promise<void> {
    const promise = new Promise<void>((_resolve, reject) => {
        SampleLib.Initialize(
            identifier,
            (error: string) => { // error callback
                reject(error);
            });
    });
    return promise;
}

Javascript Nav subcategories only good on first click

I have a nave pane on the left side of my webpage. The nav pane use to work perfectly fine, it would expand when the main category was clicked and collapse any previous category that was clicked prior.
As I have expanded the pages functionality somewhere along the line I broke this and cant figure for the life of me why…

The Problem: When I click any main Category then Subcategory for the first time on page load, everything works fine. However, when I try to move to a different subcategory within a different main category I get elementID not found/null error. JS as yall can tell is not my strong suite. Ive tried googling to avoid wasting yalls time but im at my wits end. Any help would be appreciated.

Nav HTML:

<div id="navPane">
            <!-- Navigation Pane -->
            <div class="logo-and-data-container">
                <img src="/images/Logo-2.png" alt="Company Logo" id="navLogo">
                <div id="systemLocation"></div>
            </div>
            
            <div class="category" onclick="toggleSubcategories('diagnostics', this)">
                <a href="javascript:void(0);">Diagnostics</a>
                <div id="diagnostics" class="subcategory" style="display:none;">
                    <a href="javascript:void(0);" onclick="showLogContent('sensorStatus', event)">Sensor Status</a>
                    <a href="javascript:void(0);" onclick="showLogContent('inputEvents', event)">Input Events</a>
                    <a href="javascript:void(0);" onclick="showLogContent('systemLogs', event)">System Log</a>
                    <a href="javascript:void(0);" onclick="showLogContent('swRelease', event)">S/W Release History</a>
                </div>
            </div>

            <div class="category" onclick="toggleSubcategories('alarms', this)">
                <a href="javascript:void(0);">Alarms</a>
                <div id="alarms" class="subcategory">
                    <a href="javascript:void(0);" onclick="showContent('currentAlarms', event)">Current Alarms</a>
                    <a href="javascript:void(0);" onclick="showContent('alarmHistory', event)">Alarm History</a>
                </div>
            </div>
            <div class="category" onclick="toggleSubcategories('inventory', this)">
                <a href="javascript:void(0);">Inventory</a>
                <div id="inventory" class="subcategory">
                    <a href="javascript:void(0);" onclick="showContent('currentInventory', event)">Current Inventory</a>
                    <a href="javascript:void(0);" onclick="showContent('shiftInventory', event)">Shift Inventory</a>
                    <a href="javascript:void(0);" onclick="showContent('inventoryHistory', event)">Inventory History</a>
                </div>
            </div>
            <div class="category" onclick="toggleSubcategories('delivery', this)">
                <a href="javascript:void(0);">Delivery</a>
                <div id="delivery" class="subcategory" style="display:none;">
                    <a href="javascript:void(0);" onclick="showContent('lastDelivery', event)">Last Delivery</a>
                    <a href="javascript:void(0);" onclick="showContent('deliveryHistory', event)">Delivery History</a>
                </div>
            </div>
            <div class="category" onclick="toggleSubcategories('environmental', this)">
                <a href="javascript:void(0);">Environmental</a>
                <div id="environmental" class="subcategory" style="display:none;">
                    <a href="javascript:void(0);" onclick="showContent('citld', event)">CITLD</a>
                    <a href="javascript:void(0);" onclick="showContent('vld', event)">VLD</a>
                </div>
            </div>
        </div>

Main Content where I dynamically render page content based on subcategory selection:

<div id="mainContent">
                <!-- Static Top -->
                <div class="static-top">
                    <span class="inline-elements">
                        <b>Company<sup>®</sup> Soda Tank Monitoring System:</b>
                        <div id="dataDisplayPar7" class="inline-div"></div>
                    </span>
                    <strong id="reports-title">SYSTEM REPORTS</strong>
                    <div id="date-time" class="date-time"></div>
                </div>
            
                <!-- Dynamic Content Area -->
                <div id="contentArea">
                    <!-- Filters Section -->
                    <div id="inventoryHistoryFilters" style="display: none; margin-bottom: 20px;">
                        <select id="tankFilter">
                            <option value="">All Tanks</option>
                            <option value="1">Tank 1</option>
                            <option value="2">Tank 2</option>
                            <option value="3">Tank 3</option>
                            <option value="4">Tank 4</option>
                        </select>
            
                        <input type="date" id="startDate">
                        <input type="date" id="endDate">
            
                        <button onclick="applyFilters()">Apply Filters</button>
                    </div>
                    </div>
            
                    <!-- Dynamic Content Section -->
                    <div id="dynamicContent">
                        <div id="selectCategoryMsg">
                            <p>Select a category.</p>
                        </div>
                    </div>
                </div>
            </div>

My subcategories toggle:

function toggleSubcategories(category, element) {
    var allSubcategories = document.getElementsByClassName('subcategory');
    
    for (var i = 0; i < allSubcategories.length; i++) {
        var subcategory = allSubcategories[i];

        // Hide all subcategories and remove 'expanded' class from their parent
        subcategory.style.display = 'none';
        if (subcategory.parentElement.classList.contains('expanded')) {
            subcategory.parentElement.classList.remove('expanded');
        }
    }

    // Get the subcategory element of the clicked category
    var subcategoryElement = document.getElementById(category);
    if (subcategoryElement) {
        // Toggle the display of the clicked subcategory
        if (subcategoryElement.style.display === 'none' || subcategoryElement.style.display === '') {
            subcategoryElement.style.display = 'block';
            element.classList.add('expanded');
        } else {
            subcategoryElement.style.display = 'none';
            element.classList.remove('expanded');
        }
    } else {
        console.error('Subcategory element not found:', category);
    }
}

My relevant showContent() JS:

function showContent(subcategory, event) {
    event.stopPropagation();

    var dynamicContentDiv = document.getElementById('dynamicContent');
    var selectCategoryMsg = document.getElementById('selectCategoryMsg');

    if (!dynamicContentDiv || !selectCategoryMsg) {
        console.error('Required element(s) not found in the DOM.');
        return;
    }

    if (subcategory === 'inventoryHistory') {
        var inventoryHistoryFilters = document.getElementById('inventoryHistoryFilters');

        if (!inventoryHistoryFilters) {
            console.error('inventoryHistoryFilters element not found');
            return;
        }

        selectCategoryMsg.style.display = 'none';
        inventoryHistoryFilters.style.display = 'block';

        fetch('php/get_inventory.php')
            .then(response => response.json())
            .then(data => {
                data.sort((a, b) => a.tank - b.tank);
                const groupedData = data.reduce((acc, item) => {
                    acc[item.tank] = acc[item.tank] || [];
                    acc[item.tank].push(item);
                    return acc;
                }, {});

                let tableHtml = '<h2>Inventory History</h2>';
                for (const tank in groupedData) {
                    tableHtml += `<div class="collapsible-container">
                <button class="collapsible">
                    Tank ${tank} <span class="arrow">&#9654;</span>
                </button>
                <div class="content">
                  <table>
                  <tr>
                    <th>Timestamp</th>
                    <th>Product Volume</th>
                    <th>Product Height</th>
                    <th>TC Volume</th>
                    <th>Water Volume</th>
                    <th>Water Height</th>
                    <th>Ullage</th>
                    <th>Temperature</th>
                  </tr>`;

                    groupedData[tank].forEach(item => {
                        const date = new Date(item.ts * 1000); 
                        const dateString = date.toLocaleString(); 
                        
                        tableHtml += `<tr>
                                        <td>${dateString}</td>
                                        <td>${item.pvol}</td>
                                        <td>${item.phgt}</td>
                                        <td>${item.tcvol}</td>
                                        <td>${item.wvol}</td>
                                        <td>${item.whgt}</td>
                                        <td>${item.ull}</td>
                                        <td>${item.tmp}</td>
                                      </tr>`;
                    });

                    tableHtml += '</table></div></div>';
                }

                dynamicContentDiv.innerHTML = tableHtml;
                setupCollapsible();
            })
            .catch(error => {
                console.error('There has been a problem with your fetch operation:', error);
            });
    } else {
        dynamicContentDiv.innerHTML = '<p>Select a different category.</p>';
    }
}

My showLogContent():

function showLogContent(subcategory, event) {
    var selectCategoryMsg = document.getElementById('selectCategoryMsg');
    if (!selectCategoryMsg) {
        console.error('selectCategoryMsg element not found');
        return;
    }
    selectCategoryMsg.style.display = 'none';
    event.stopPropagation();

    let logFilePath;
    let logTitle;
    if (subcategory === 'systemLogs') {
        logFilePath = 'my path';
        logTitle = 'System Logs';
    } else if (subcategory === 'inputEvents') {
        logFilePath = 'my path';
        logTitle = 'Input Events';
    } else if (subcategory === 'swRelease') {
        logFilePath = 'my path';
        logTitle = 'Software Release History';
    } else if (subcategory === 'sensorStatus') {
        logFilePath = 'my path';
        logTitle = 'Sensor Status';
    }

    if (logFilePath) {
        fetch('php/read_log.php', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: 'logFilePath=' + encodeURIComponent(logFilePath)
        })
        .then(response => response.text())
        .then(data => {
            let contentArea = document.getElementById('contentArea');
            if (contentArea) {
                contentArea.innerHTML = `<h2>${logTitle}</h2><pre>${data}</pre>`;
            } else {
                console.error('contentArea element not found');
            }
        })
        .catch(error => {
            console.error('Error fetching log file:', error);
        });
    }
}

As described in the above, I am trying to be able to switch between each subcategory to view varies logs or inventories. I can only do this once, before the nav gets broken. It takes a page refresh in order to make it work again. Ive tried googling this issue, browsing stack and event AI input to no avail.

Internet Explorer don’t POST

I am working on a SAP interface project, in which the standard call is usually the Internet Explorer. I am trying to gather the information processed by HTML within the IE and send it to SAP using the following code:

REPORT demo_html_input.

INCLUDE: ZCAS_TEXT_POST_HTML_SRC.

TYPES: typ_html_code TYPE TABLE OF char255 WITH EMPTY KEY,
       typ_source    TYPE TABLE OF string.

CLASS html_start DEFINITION.
  PUBLIC SECTION.
    METHODS: constructor,
             txt_html RETURNING VALUE(lt_codigo) TYPE string.
  PRIVATE SECTION.


    data: lv_html_code type string.
    METHODS: get_source,
             descomented
             IMPORTING
               lt_source    TYPE typ_source
             EXPORTING
               lv_html_code TYPE string.

ENDCLASS.

CLASS html_start IMPLEMENTATION.
  METHOD constructor.
    get_source( ).
  endmethod.

  METHOD txt_html.
    lt_codigo = lv_html_code.
  ENDMETHOD.

  METHOD get_source.
    DATA: lt_source TYPE TABLE OF string.

    CALL METHOD cl_reca_rs_services=>get_source
      EXPORTING
        id_objtype = 'PROG'
        id_objname = 'ZCAS_TEXT_POST_HTML_SRC'
      IMPORTING
        et_source  = lt_source.

    descomented( EXPORTING
                        lt_source = lt_source
                       IMPORTING
                         lv_html_code = lv_html_code ).
  ENDMETHOD.


  METHOD descomented.
    DATA: ls_html_code TYPE char255.
    DATA: ls_source TYPE string.

    DATA: lv_len_data TYPE i,
          lv_len_source TYPE i,
          lv_len_total TYPE i,
          lv_str_max  type i,
          lv_string TYPE string.

    LOOP AT lt_source INTO ls_source.
      TRY .
          ls_source = ls_source+1.
        CATCH cx_sy_range_out_of_bounds.
      ENDTRY.


      SHIFT ls_source RIGHT DELETING TRAILING ' '.
      SHIFT ls_source LEFT DELETING LEADING ' '.

      lv_string = ls_source .
      CONCATENATE lv_html_code lv_string INTO lv_html_code.
    ENDLOOP.
  ENDMETHOD.

ENDCLASS.

CLASS demo DEFINITION.
  PUBLIC SECTION.
    CLASS-METHODS main.
  PRIVATE SECTION.
    CLASS-METHODS handle_sapevent
      FOR EVENT sapevent
                  OF cl_abap_browser
      IMPORTING action
                  query_table.
ENDCLASS.

CLASS demo IMPLEMENTATION.
  METHOD main.
    DATA error_list TYPE cl_abap_browser=>html_table.

    SET HANDLER handle_sapevent.

    DATA: retorncode TYPE REF TO html_start.

    CREATE OBJECT retorncode.

    DATA(html_str) = retorncode->txt_html( ).

    cl_abap_browser=>show_html(
      EXPORTING
        html_string = html_str
        title       = 'Input Demo'
      IMPORTING
         html_errors = error_list ).

    IF error_list IS NOT INITIAL.
      MESSAGE 'Error in HTML' TYPE 'I' DISPLAY LIKE 'E'.
    ENDIF.
  ENDMETHOD.
  METHOD handle_sapevent.
    BREAK-POINT.
    DATA(out) = cl_demo_output_stream=>open( ).
    SET HANDLER cl_demo_output_html=>handle_output FOR out.
    out->write_data( iv_name = 'ACTION'      ia_value = action ).
    out->write_data( iv_name = 'QUERY_TABLE' ia_value = query_table ).
    out->close( ).
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  demo=>main( ).

In the ABAP call, any information sent to the URL with the prefix SAPEVENT: is redirected to the handle_sapevent method. I based myself on this code, which also works using IE;

https://help.sap.com/doc/abapdocu_750_index_htm/7.50/en-US/abenhtml_input_abexa.htm

and I used this HTML:

<!DOCTYPE html>
<html lang="pt-br">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=9" />
    <title>Document</title>
</head>

<body>
    <input type="button" id="btn" onclick="">

</body>

<script>
    document.getElementById('btn').addEventListener('click', function sendTOAbap(ev) {

        var oOutput = document.querySelector("div"),
            oData = {
                campo: "sucesso",
                field: "insucesso"
            };

        oData.append("CustomField", "This is some extra data");

        var oReq = new XMLHttpRequest();
        oReq.open("POST", "SAPEVENT:SAPEVENT", true);
        oReq.onload = function (oEvent) {
            if (oReq.status == 200) {
                console.log("Uploaded!");
            } else {
                console.log("Error " + oReq.status + " occurred when trying to upload your file.");
            }
        };

        oReq.send(oData);
        ev.preventDefault();
    }, false);
</script>

</html>

The problem is that when I try to run it specifically using Internet Explorer, it returns an “access denied” or “not transported” error. I cannot change the browser version as it is the SAP standard.
Tankyou to help-me.

I tried changing the access policies and changing the post methods, and changing the body.

I would like to know how to divide an image in sections on Krpano

Im creating a 360 tour but i want to implement a game mecanic where i use the default image
The game consist in solving a puzle where the image is divided in sections and i need to place them in the original plave

I tried inplementing a javascript code where i subdivided the image and organized it on a grid
but im having trouble passing from the 2d space to 3d

Socket IO – options for sending to specific socket/user

Currently, in my socket Io server, whenever a user connects I add them to an array, and join them to a room with the name of their user Id.

Server.js:

var users  = []

io.on('connect', (socket) => {
    socket.on('join', (data) => {
       // Add user to array
       users.push({socketId: socket.id, username: data.username, userId: data.uid})
       // Join a user into their own room with the name being their unique user Id
       socket.join(data.uid)
    }) 
})

When sending to one specific user, currently I am doing the following:

// Find the user from the users array
const user = users.find(u => u.userId = userId)
// Emit to room that I joined them to after connecting
io.to(user.userId).emit("send message", messageData)

An alternative approach would be to not join a room with the users own id, as soon as a user connects, and instead send directly send events to users socket Ids.This would look like the following:

io.to(user.socketId).emit("sendMessage", messageData)

Using this approach, users would not need to join their own room as soon as they connect.

Is there any benefit to using this second approach as opposed to the first? Is there any scenarios where one solution would fit better, e.g due to performance.

Also, instead of joining a user to their own room on connect, could I just use io.to(user.socketId).emit("send message", data) which uses the user’s socket id as the room name, as I believe socket IO always automatically connects a user to their own room using their socket Id. However, this feature is mentioned in v3 of socket io documentation and not v4, therefore is this still a built in feature? Thanks.

Problem with saving the data from an API response to a global variable

I am complete newbie in JavaScript and Still understanding async and await programs

I have a program with a axios resquest.

axios.request(config)
.then((response) => {
  console.log(response.data);
})

The request is working fine and I am getting the Data . I want to save this data to an external variable. Like this.

let data;

axios.request(config)
.then((response) => {
  data = response.data;
})

console.log(data);

But this is showing data is undefined. Any suggestions or solutions

I have tried using async and await functions but couldn’t lead to a solution.

zod validation in javaScript [duplicate]

export type ResetPassword = {
  password: string
  confirmPassword: string
}

export const resetPasswordSchema: ZodType<ResetPassword> = z.object({
  password: z.string().refine((value) => value !== '', {
    message: 'Password is required'
  }),
  confirmPassword: z.string().refine((value) => value !== '', {
    message: 'Password is required'
  }).refine((data) => data.password === data.confirmPassword, {
    message: "Passwords don't match",
    path: ["confirmPassword"], // path of error
  })
})

i’m trying to use zod validation to check if the confirm password matches the password and i got this error!

Property ‘password’ does not exist on type ‘string’.
Property ‘confirmPassword’ does not exist on type ‘string’.

in this line

  }).refine((data) => data.password === data.confirmPassword, {

…………………

need guidance if this code is good enough for an answer on an interview question? [closed]

the challenge: Have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several characters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.

My solution and pseudo code:
// if(str[i] === letter) check if its a + at str[i – 1] || str[i + 1]

let a = "abcdefghijklmnopqrstuvwxyz"
let letters = a.split('')
for(let i = 0; i < str.length; i++){

if(letters.includes(str[i])){// if str[i] == d
for(let j = i; j < str.length; j++){//start a for loop that starts at d and ends at the index behind d
if(str[j + 1] === "+"){
for(let k = str.length - 1; k > 0; k--){
if(str[i - 1] === "+"){
return true
} else{
return false
}
}
}
//if(i[j] === "+"){//if the index is str[i] == +
//   for(let k = str[i]; k >= str[i + 1]; k++){//start another loop that starts at str[i] and moves forward twice
//     if(str[i + 1] === "+"){
//       return true
//     } else{
//       return false
//     }
//   }
// }
}
}
}

}

I needed to console.log a lot to see exactly where i was. originally i tried to execute a loop at the exact location of a letter. from there i only wanted to move backwards once and identify if “+” was there. If that was true i wanted to move forward twice from that exact location and check if there was another “+”. It identified a letter, checked for a “+” behind the letter, moved passed the letter to check for another “+”. I didnt understand how to implement that so i figured how to just loop through the entire length at the same position and once it found the “+” both ways we recieved the desired outcome.

Input: “+d+=3=+s+”
Output: true

Input: “f++d+”
Output: false

would this be considered easy code to read. I ask chatGPT and to me it was wayyy more complex then my code.

Toggle between content

I have the following code.

visit the following website to view output

https://jsfiddle.net/name_123/qzx3auev/1/

i would like to change the background color of active toggle to white.

 <div class="col-md-9 register-right">
                        <ul class="nav nav-pills nav-tabs nav-justified" id="myTab" role="tablist">
                            <li class="nav-item">
                                <a class="nav-link " id="home-tab" data-toggle="pill" href="#home" role="tab" aria-controls="home" aria-selected="true">Buyer</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link " id="profile-tab" data-toggle="pill" href="#profile" role="tab" aria-controls="profile" aria-selected="false">Seller</a>
                            </li>
                        </ul>
                       
            </div>

css is

 
.nav-tabs{
    margin-top: 3%;
    border: none;
    background: #0062cc;
    border-radius: 1.5rem;
    width: 28%;
    float: right;
}
.nav-tabs .nav-link{
    padding: 2%;
    height: 34px;
    font-weight: 600;
    color: #fff;
    border-top-right-radius: 1.5rem;
    border-bottom-right-radius: 1.5rem;
}
.nav-tabs .nav-link:hover{
    border: none;
}
.nav-tabs .nav-link.active{
    width: 100px;
    color: #d8dfe6;
    border: 2px solid #0062cc;
    border-top-left-radius: 1.5rem;
    border-bottom-left-radius: 1.5rem;
}

 

Frequently getting “localhost not found” error in Vite React project, and the project started once but my JS elements didn’t show up

I’m consistently encountering a “localhost not found” error in a project I’m developing using Vite and React. I’ve tried changing the port, but the issue persists. Additionally, I managed to start the project once, but at that time, my JavaScript elements were not visible on the page.

What can I do to resolve this issue? What steps should I follow, or what configurations in my project should I check?

The steps I’ve taken so far include:

Changing the port
Updating dependencies
Checking project configuration files
However, these steps haven’t resolved the issue. Thank you in advance for your assistance!

Edit: when i use npm run build i’m getting this error

Could not resolve entry module "index.html".
error during build:
RollupError: Could not resolve entry module "index.html".
    at error (file:///C:/Users/lcyke/OneDrive/Masa%C3%BCst%C3%BC/Chatbot/node_modules/rollup/dist/es/shared/parseAst.js:337:30)
    at ModuleLoader.loadEntryModule (file:///C:/Users/lcyke/OneDrive/Masa%C3%BCst%C3%BC/Chatbot/node_modules/rollup/dist/es/shared/node-entry.js:17990:20)
    at async Promise.all (index 0)