Why does console log of this array always skip the first element? [closed]

I have a JS program that generates an index a random number of times. The indexes are correlated to strings stored in another array. It then pushes those indexes into yet another array. When I console log the randomly generated indexes, it returns the strings associated with those indexes. However, when I log the array that holds the generated strings, it always skips the first generated string. How can I get the second array to log all of the generated strings without skipping the first one? (Note that getRandStrings is defined prior to this in the code.)

let stringsBlockArr = [];

let getStrings = () => {
    stringsBlock = [];
    let stringsBlock = [];
    let numStringsPerTurn = (Math.floor(Math.random() * 3));
    for (let i = 0; i < numStringsPerTurn; i++) {
        stringsBlock += getRandStrings();
    }
    stringsBlockArr.push(stringBlock);
}

getStringsPerTurn();

console.log(stringsBlockArr);

For example, if the generated strings are “a”, “b”, and “c”, logging stringsBlockArr only returns “b” and “c”.

I have tried only defining the getStringsArr locally. It didn’t work and I need that array to be available globally.

Map function show undefine

item.map line i am facing problem please guide me

function Map({items}) {
    return (
        <MapContainer center={[52.4797, -1.98269]} zoom={7} scrollWheelZoom={false} className='map'>
            <TileLayer
                attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />
            {items.map((item)=>(
                <Pin item={item} key={item.id}/>
            ))}
        </MapContainer>
    )
}

I tried to map using map funtion but it’s not working

How can I append hidden input to this file input after jquery simpleUpload success?

Trying to append a hidden form field after the file input that was used to upload a file within the simpleUpload call.

So far I have tried:

$(document).on('change', '.upfile', function(){
    var obj = $(this);
    $(this).simpleUpload("/upload.php", {
        start: function(file){ console.log("upload started"); },
        progress: function(progress){ console.log("upload progress: " + Math.round(progress) + "%"); },
        success: function(data){
            $(obj).append('<input type="text" name="images[]" value="'+data.message+'">');
            console.log("upload successful!");
            console.log(data);
        },
        error: function(error){ console.log("upload error: " + error.name + ": " + error.message); }
    });
});
$(document).on('change', '.upfile', function(){
    var obj = this;
    $(this).simpleUpload("/upload.php", {
        start: function(file){ console.log("upload started"); },
        progress: function(progress){ console.log("upload progress: " + Math.round(progress) + "%"); },
        success: function(data){
            $(obj).append('<input type="text" name="images[]" value="'+data.message+'">');
            console.log("upload successful!");
            console.log(data);
        },
        error: function(error){ console.log("upload error: " + error.name + ": " + error.message); }
    });
});

To no avail. There seems to be no way of setting a context: in simpleUpload or I would have tried that.

What am I doing wrong?

getting “Error: Cannot read properties of undefined (reading ‘username’)” in my POST request

My POST request isn’t working and it’s not updating? The error is:

TypeError: Cannot read properties of undefined (reading 'username')
app.post('/create-user', function(req, resp) { 
          const client = new MongoClient(uri);
          const dbo = client.db("eggyDB"); // Get the database object
          const collName = dbo.collection("users"); // Get the collection
    
          const info = {
              username: req.body.username,
              password: req.body.password
          };
    
          collName.insertOne(info)
              .then(function() {
                  console.log('User created');
                  resp.render("main", {
                    layout: "homepage",
                    title: "My Home page"
                  });
              })
              .catch(function(err) {
                  console.error('Error creating user:', err);
                  resp.status(500).send('Internal Server Error');
              })
      });

this is my html code (in the partials folder):

<form
    name="signup"
    action="/create-user"
    method="POST"
    class="popup-signup-content"
    onsubmit="return verifyPassword()"
    >
    <h1 onclick="closeSignup()" id="close-login" type="submit">x</h1>
    <img src="/images/LOGO-YL.png" alt="None" />
    <input
        id="username-signup"
        name="username"
        type="text"
        placeholder="Enter Username/Email"
        required
    />
    <input
        id="password-signup"
        type="password"
        placeholder="Enter Password"
        required
    />
    <input
        id="verify-password-signup"
        name="password"
        type="password"
        placeholder="Re-Enter Password"
        required
    />
    <button class="login-button bold" type="submit" onclick="console.log('Form Submitted')">Register</button>
</form>

it won’t add a new user to the database but it connects to the database. it also won’t show the onclick function when Register is pressed. what should i do?

i tried asking chatgpt but i think it was slowly drifting me away from the solution. what do you think should i do here?

Devias Kit Pro – Client and Admin Dashboard how to integrate API

My client bought the Devias Kit Pro to reach the deadline and I’m stuck in finding how to integrate our API with it. I work with our API on Postman fine but I don’t know how to to put it in this template. It is getting user data from data.js file it is work with static data:

enter image description here

If someone worked with it before can tell me how to do auth with my login API in all part of it like login logout orders all?

I tried to use all 4 auth method the templates provided but still all of them work on static data file they provided to get user.

What is a proper way to get the changed values from a table with hundreds of rows (To be sent as form to the backend)?

I have tables that have hundreds of rows displayed per page, and each row has inputs that can be changed by the user. I want to send only the updated data to the backend so that not too much data will be sent. There is a “save changes” button at the top.

I am not using a form element currently (So to not send the entire table)

What I do is, I give each <tr> the row id from the database as a dataset attribute, and listen to changes on inputs, then if one of the values of a row is changed, I add this entire row and its inputs to an object that holds all the changed rows. This object is then sent to the backend

let updatedData = {};
let table1Form = document.querySelector('#table_1');
table1Form.addEventListener("change", (event) => {
  let row = event.target.closest('tr');
  let rowId = row.dataset.dbRowId;
  let rowInputs = row.querySelectorAll('input');
  updatedData[rowId] = {};
  rowInputs.forEach((input) => {
    if (input.type === "checkbox") {
      updatedData[rowId][input.name] = input.checked;
    } else {
      updatedData[rowId][input.name] = input.value;
    }
  });
});

document.querySelector("#save-changes").addEventListener("click", () => {
  console.log(updatedData);
});
<button id="save-changes">Save Changes</button>
<table id="table_1">
  <tr data-db-row-id="1">
    <td><input type="text" name="email" value="[email protected]" /></td>
    <td><input type="text" name="name" value="Foo" /></td>
    <td><input type="checkbox" name="show" checked="checked" /></td>
  </tr>
  <tr data-db-row-id="2">
    <td><input type="text" name="email" value="[email protected]" /></td>
    <td><input type="text" name="name" value="Bar" /></td>
    <td><input type="checkbox" name="show" /></td>
  </tr>
</table>

But it feels cumbersome, and I need to check for each type of input (in the above example I had to have distinction between the checkbox and the text inputs because they are evaluated differently

Perhaps there’s a better way to do that (with the use of Form Data maybe as well?)

Electron app with Angular.js: Uncaught TypeError when using electron-store for storage

I am building an electron app with Angular.js. Here I am doing electron storage. But when I built it it always gives me some errors. which are

  1. “Uncaught TypeError: Cannot define property parameters, object is not extensible”
  2. at Function.defineProperty ()
  3. at a (main.14acdcbc49c5dc9c.js:1:354996)
  4. at 5629 (main.14acdcbc49c5dc9c.js:1:1923787)
  5. at a (runtime.874a5b2956b8256a.js:1:128)
  6. at main.14acdcbc49c5dc9c.js:1:2184662
  7. at o (runtime.874a5b2956b8256a.js:1:1030)
  8. at main.14acdcbc49c5dc9c.js:1:93

I have tried several things but it’s not working still. I have fixed all the linter errors & type errors too. It should work. But if I remove the electron storage related functionalities the build process works. Can anyone solve my issue?

cant download langchain anthropic on deno

Can I get langchain anthropic on deno? I keep getting this error: failed to load 'https://esm.sh/langchain/anthropic': Module not found "https://esm.sh/langchain/anthropic".
Here is my import:

import { ChatAnthropicTools } from "langchain/anthropic";

and here is my import map:

{
  "imports": {
    "@std/": "https://deno.land/[email protected]/",
    "@supabase/supabase-js": "https://esm.sh/@supabase/[email protected]",
    "langchain/": "https://esm.sh/langchain/",
    "langchain/anthropic": "https://esm.sh/langchain/anthropic"
  }
}

Thank you!

Vue apollo, throws error every time on load

<template>
  <div v-if="loading"><loading></loading></div>
  <div v-else-if="error"><error v-bind="error"/></div>
  <div v-else>
    <div class="title" v-if="!error"> <h1>Recently Added:</h1></div>
    <section class="adverts" >
      
      <adverts @update:isFavorited="updateIsFavorited" v-for="advert in adverts.list" v-bind:key="advert.id" v-bind="advert" />
    </section>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, watchEffect } from 'vue';
import { useQuery } from '@vue/apollo-composable'
import { GET_ADVERTS } from "@/graphql/advert";
import Adverts from '../components/Adverts.vue';
import Error from '../components/Error.vue';
import Loading from '../components/Error.vue';

interface Advert {
  id: number;
  location: string;
  price: number;
  title: string;
  createdAt: string;
  available: boolean;
  isFavorited: boolean;
}


export default defineComponent({
  name: 'App',
  components: {
    Adverts,
    Error,
    Loading,
  },
  methods: {
    async loadMoreAdverts() {
        if (this.loading) return; 
        const accessToken = localStorage.getItem("access_token") || "";
        this.loading = true;
        try {
          const { result, error } = await useQuery(GET_ADVERTS,  {
            variables: {
              accessToken,
              offset: this.adverts.list.length,
              limit: 10 
            }
          });

          if (result) {
            this.adverts.list.push(...result.value.getAdverts);
          } else if (error) {
            console.error(error);
          }
        } catch (error) {
          console.error(error);
        } finally {
          this.loading = false;
        }
    }
  },

  setup() {
    const adverts = reactive({ list: [] as Advert[] });

    const accessToken = localStorage.getItem("access_token") || "";


    const updateIsFavorited = (id: number, isFavorited: boolean) => {
      const index = adverts.list.findIndex((advert) => advert.id === id);
      const updatedAdverts = [...adverts.list];
      updatedAdverts[index] = { ...updatedAdverts[index], isFavorited };
      adverts.list = updatedAdverts;
    };

   
    const {result, loading, error} = useQuery(GET_ADVERTS, { accessToken, offset: 1, limit: 4 }, { fetchPolicy: 'network-only' });


    console.log(result, loading, error);

    

    watchEffect(() => {
      if (result.value) {
        adverts.list = result.value.getAdverts;
      }
    });


    

    return {
      adverts,
      loading,
      error,
      updateIsFavorited
    };
  },
  mounted() {
    // this.loadMoreAdverts();
    // const observer = new IntersectionObserver(entries => {
    //     if (entries[0].isIntersecting) {
    //       this.loadMoreAdverts();
    //     }
    // }, { threshold: 1 });

    // observer.observe(this.$refs.loadMoreTrigger);
  },

});
</script>



<style scoped>
  .adverts {
    display:flex;
    justify-content:flex-start;
    align-items:center;
    flex-direction: row;
    flex-wrap:wrap;
    gap:30px 30px;
    margin:50px 150px;
  }

  .error {
    height:100%;
  }

  .title {
    display:grid;
  }

  h1 {
    color: rgb(var(--v-theme-text));
    margin: 50px 150px 20px 150px;
    justify-self: flex-start;
  }

</style>



i have this code, it fetch adverts, but every time on load i see error message for 1 sec or less,
this pattern is from official documentation https://apollo.vuejs.org/guide-composable/query.html, and i dont think it should work like that, i think it should display loading but not error, because when i check error.value in script it is null

Google Sheets App Script – How to Get and Set Formulas as a text string with GetFormulas and SetFormulas?

Firstly, I apologise if I am asking a silly question as I am a javascript novice and fairly new to understanding and handling arrays.

I need a bit of help figuring out how to get and set formulas in App Script while converting them to text strings in-between. For example:

I have 3 sheets, Sheet 1 contains source formulas, Sheet 2 that is supposed to store the source formulas as strings (acting as a database), Sheet 3 where I’m supposed to set formulas that I get from Sheet 2 .

Sheet1!A1 contains formula “=B1*C1”

Sheet1!A2 contains formula “=B2*C2”

etc.

Sheet2!A1:A is blank.

Sheet3!A1:A is blank.

What I need to achieve:

Task A. I would like to get all formulas from Sheet1!A1:A with the getFormulas() method and then store them as a text string in Sheet2!A1:A with setValues() method but I have no idea how to convert the array generated by getFormulas() into strings that I can then store with setValues(). Something like this:

var formulas = s.getRange('Sheet1!A1:A').getFormulas();
s.getRange('Sheet2!A1:A').setValues(formulas.toString());

Problem is of course that I get a method signature mismatch if I try to use toString().

Task B. After storing the formula strings in Sheet2!A1:A, I would like to get them with getValues() then set them as formulas in Sheet3!A1:A with setFormulas().

var text_formulas = s.getRange('Sheet2!A1:A').getValues();
s.getRange('Sheet3!A1:A').setFormulas(text_formulas);

Any idea how I could go about achieving this in an efficient manner? Thank you in advance for helping out a novice!

is it possible to change the color of a specific window button in electron.js

I wanted to remove the default windows top bar and keep only the minimize, maximize and close buttons and i was able to do this with the below config values.

win = new BrowserWindow({
    width: 800,
    height: 600,
    icon: path.join(__dirname, "./src/assets/images/favicon.ico"),
    maximizable: false,
    titleBarStyle: "hidden",
    titleBarOverlay: {
      color: "#FFF",
      symbolColor: "#999",
      height: 30
    }
  })

but here the problem is that the disabled button is also getting the color #999, but i want it to be a different color to indicate that the button is disabled which was happening when i added only maximizable: false propery but it seems like this was overriden by the titleOverlay property.

Is there a way to do this ? other than replacing the default icons with custom icons.

This is what i tried

win = new BrowserWindow({
    width: 800,
    height: 600,
    icon: path.join(__dirname, "./src/assets/images/favicon.ico"),
    maximizable: false,
    titleBarStyle: "hidden",
    titleBarOverlay: {
      color: "#FFF",
      symbolColor: "#999",
      height: 30
    }
  })

and i was expecting the electron.js would automatically apply a lighter color to maximize button since it is disabled but it didn’t.

Shapes rendered using ThreeJs have shaky/hazy edges

I am trying to render this cube in ThreeJs using basic Box Geometry but the lines are weird and shaky. Even if I set wireframe to false and put a solid cube, the edges of the cube still remain like this.

cube

I am using WebGlRenderer and box geometry for the cube.

    const renderer = new THREE.WebGLRenderer();
    const scene = new THREE.Scene();

    const camera = new THREE.PerspectiveCamera(
      45,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );

    const boxGeo = new THREE.BoxGeometry(2, 2, 2);
    const boxMat = new THREE.MeshBasicMaterial({
      color: 0x00ff00,
      wireframe: true,
    });
    const boxMesh = new THREE.Mesh(boxGeo, boxMat);
    scene.add(boxMesh);