Mapping through an Array and Appending Axios Response to each Object

I have an array of objects that I queried from my database. Now I’d like to iterate through each one and use Axios to append response data to each one. I’m struggling with getting the map to wait for axios to get the data. Is there a standard practice for doing this?

I tried Promise.all, async/await, and axios.all and am getting a variety of undesired results.

weird array result during slice/shift operations

Intro

Please bear with me for a bit, and if you need clarification, please let me know, I will try my best.

I been working on a new HL7 Parser/Builder/Client etc. in Node. I am reusing most of the code though from an old “package” that is no longer maintained. However, it has functionality that I want to have. I am as well as expanding and working on a fully TypeScript version and also a few other goodies. The code in question is current here in this GitHub branch. Of course, welcomed for PR’s and help if you want. 🙂

In any case, the issue I am now running into is I got my “code” to spit of the right “HL7” message header defining the HL7 properties to the server when it’s being sent.

In the “Message” class is created at the constructor level: Code Here

this.set('MSH.7', Util.createDate(new Date()))
this.set('MSH.9.1', this._opt.mshHeader.msh_9.msh_9_1.toString())
this.set('MSH.9.2', this._opt.mshHeader.msh_9.msh_9_2.toString())
this.set('MSH.9.3', `${this._opt.mshHeader.msh_9.msh_9_1.toString()}_${this._opt.mshHeader.msh_9.msh_9_2.toString()}`)
this.set('MSH.10', this._opt.mshHeader.msh_10.toString())
this.set('MSH.12', this._opt.specification.name.toString())

I specifying the the MSH.7, etc. it does output it correctly. Adding a new segment onto the “parent child” is done like the unit test here, but for this site:

const message = new Message({
    mshHeader: {
        msh_9: {
            msh_9_1: "ADT",
            msh_9_2: "A01"
        },
        msh_10: "12345"
    }
})
message.set('MSH.7', '20081231')
const segment = message.addSegment('EVN')
segment.set('EVN.2', '20081231')

This should result in "MSH|^~\&|||||20081231||ADT^A01^ADT_A01|12345||2.7rEVN||20081231".

Issue #1

So running the code line by line for hours debug I narrowed down to the issue here in line #61 in nodeBase.ts code here

set (path: string | number, value?: any): Node {
    if (arguments.length === 1) {
      return this.ensure(path)
    }

    if (typeof path === 'string') {
      if (Array.isArray(value)) {
        for (let i = 0; i < value.length; i++) {
          this.set(`${path}.${i+1}`, value[i])
        }
      } else {
        const _path = this.preparePath(path as string) // this is the point of failure
        this.write( _path, this.prepareValue(value))
      }

      return this
    } else if (Util.isNumber(path)) {
      if (Array.isArray(value)) {
        const child = this.ensure(path)
        for (let i = 0, l = value.length; i < l; i++) {
          child.set(i, value[i])
        }
        return this
      } else {
        this.setChild(this.createChild(this.prepareValue(value), path), path)
      }

      return this
    }

    throw new HL7FatalError(500, 'Path must be a string or number.')
  }

When the MSH.7, MSH.9 the _preparePath sends over from NodeBase _reminderOf code

["MSH", "7"]

or

["MSH", "9", "1"]

and returns the path correctly as:

[7"]

or

["9", "1"]

But when it sends over:

["EVN", "2"]

it gets back the same thing:

["EVN", "2"]

Problem to Issue #1

This obviously fails the code here at line #64 in the segment class when it passed back through from the initial this.write( _path, this.prepareValue(value)) method since the shift from NodeBase _reminderOf other.slice should already took out EVN which causes the this.write( _path, this.prepareValue(value)) to fail the logic testings.

Workaround to Issue #1

So a workaround I have figured out is:

const segment = message.addSegment('EVN')
segment.set(2, '20081231')

or

const segment = message.addSegment('EVN')
segment.set('2', '20081231')

or

const segment = message.addSegment('EVN')
segment.set('2.1', '20081231')
segment.set('2.2', '20081231')

Does work since there is no string and the code can accept a number or a number split. The first three letters of the HL7 segment should be allowed not not included.

Feedback

Welcome any input and suggesting, even a PR in Github itself.

Thanks,
Shane

Having trouble ensuring JavaScript events are triggered during Selenium scraping

Process: I am trying to scrape data within a web page. The process involves me inputting text in a search box, then selecting the top option from a dropdown — selecting an option then triggers the data in the division to be updated and then I iterate through this process to collect the data for all inputs.

Issue: The drop down is not popping up when the text is input, and thus I can’t update the data within the division I am scraping.

I see (using inspect element) that when I do the process manually, the name of the search input division class changes and a new division for the dropdown appears but this doesn’t happen in the browser triggered by selenium. I’ve tried sending code to change the class name but this still doesn’t trigger the dropdown.

Any insight on how I can trigger this JavaScript event?

Here’s the code I have for this part of the scrape:

def search_for_company(driver, company_name):
    # find search input
    search_input = driver.find_element_by_css_selector(config.SEARCH_INPUT_SELECTOR)
    search_box_div = search_input.find_element_by_xpath('//*[@id="dd-container"]/div/div/div[3]')
    # Remove the readonly attribute
    driver.execute_script("arguments[0].removeAttribute('readonly')", search_input)
    # clear the current text and update with new text
    search_input.clear()
    #search_input.send_keys(company_name)
    # you can see here I tried experimenting with trying to mimic actually user input, to no avail...
    for char in company_name:
        search_input.send_keys(char)
    # Change the class of the div
    driver.execute_script("arguments[0].setAttribute('class', 'dtd-search-box is-open is-focused')", search_box_div)

    time.sleep(10)  # Allow time for potential results to load

    # Check if there are no results (skip if no dropdown results pop up)
    try:
        # this is an actual div class that pops up when there are no results
        no_results = driver.find_element_by_css_selector("div.dtd-noresults")
        if no_results.is_displayed():
            print("No results displayed >>> SKIPPED.")
            return False  # No results found
    except:
        # If no such element, proceed with pressing return
        search_input.send_keys(Keys.RETURN)
        time.sleep(config.REQUEST_DELAY)
        print("Returning results.")
        return True  # Results found

Object Destructuring and where I should put it [closed]

I’m having some trouble with my api parsing through my object apparently because it cannot destructure it. Also, If I do put the destructured object where would it go in side the code.

export const storeProducts = [
    { 
        id: 1,
        title: "Fingerheart hat-Black",
        img: "img/hat.png",
        price: 10,
        info: "fingerheart hat (dri-fit black)",
        inCart: false,
        count: 0,
        total: 0
    },

React server component cache function not caching result

I have the following very simple function for getting data asynchronously. I am calling it from multiple server components in the same page, expecting it to be only called once thanks to the cache wrapper. However when loading a page it seems to be called multiple times (I see the console output logged multiple times). How can I get the cache to work?

import { cache } from 'react'

export const getProductBySlug = cache(async ({slug}) => {
    const supabase = createServerComponentClient()
    const { data, error } = await supabase.from('Product').select().eq('slug', slug).single()
    if (error)
        throw error
    return data
})

Sequelize: original: Error: Unknown column ” in ‘field list’ when include model without `attributes` field

Im trying to use Sequelize for MySQL queries, in my code I defined my Models and links them with his respective associations.

Trying to simulate a music playlist that have:
Artists, they can have multiples songs.

Playlist, has multiples songs too.

Songs, they are part of 1 or multiple playlists and have 1 or multiple artists.

That models are defines like this:

In each model I defined a interface with his respective fields for safe type and comfort

ARTIST

export interface IArtist {
    ID_ARTIST: number,
    NAME: string
}

export const Artist = seq.define<Model<IArtist>>("Artist", {
    ID_ARTIST: {
        primaryKey: true,
        type: DataTypes.INTEGER,
        allowNull: false,
        autoIncrement: true
    },
    NAME: DataTypes.STRING(30)
}, {
    timestamps: true,
    createdAt: true,
    updatedAt: false,
    tableName: "ARTISTS",
})

PLAYLIST

export interface IPlaylist {
    ID_PLAYLIST: number,
    NAME: string
}

export const PlayList = seq.define<Model<IPlaylist>>("Playlist", {
    ID_PLAYLIST: {
        primaryKey: true,
        type: DataTypes.INTEGER,
        allowNull: false,
        autoIncrement: true,
    },
    NAME: DataTypes.STRING(20)
}, {
    timestamps: true,
    createdAt: true,
    updatedAt: false,
    tableName: "PLAYLISTS"
})

SONG

export interface ISong {
    ID_SONG: number,
    ID_ARTIST: number,
    ID_PLAYLIST: number,
    DURATION: number,
    NAME: string
}

export const Song = seq.define<Model<ISong>>("Song", {
    ID_SONG: {
        primaryKey: true,
        type: DataTypes.INTEGER,
        allowNull: false,
        autoIncrement: true
    },
    ID_ARTIST: {
        type: DataTypes.INTEGER,
        references: {
            model: Artist,
            key: "ID_ARTIST"
        }
    },
    ID_PLAYLIST: {
        type: DataTypes.INTEGER,
        references: {
            model: PlayList,
            key: "ID_PLAYLIST"
        }
    },
    DURATION: DataTypes.INTEGER,
    NAME: DataTypes.STRING(40)
}, {
    timestamps: true,
    updatedAt: false,
    tableName: "SONGS"
})

And the relations of each table:

Artist.hasMany(Song)
PlayList.hasMany(Song)
Song.belongsTo(Artist, { foreignKey: "ID_ARTIST" })
Song.belongsTo(PlayList, { foreignKey: "ID_PLAYLIST" })

Then when I try to do a ‘findAll’ operation like this:

const query = await Song.findAll({
      include: {
        model: Artist,
        required: true
      },
      where: {
        ID_ARTIST: idArtist
      }
    })

idArtist is a function parameter -> idArtist: string

I get the next error:
sqlMessage: “Unknown column ‘Song.ArtistIDARTIST’ in ‘field list'”

And the query result from sequelize:
sql: “SELECT Song.ID_SONG, Song.ID_ARTIST, Song.ID_PLAYLIST, Song.DURATION, Song.NAME, Song.createdAt, Song.ArtistIDARTIST, Song.PlaylistIDPLAYLIST, Artist.ID_ARTIST AS Artist.ID_ARTIST, Artist.NAME AS Artist.NAME, Artist.createdAt AS Artist.createdAt FROM SONGS AS Song INNER JOIN ARTISTS AS Artist ON Song.ID_ARTIST = Artist.ID_ARTIST WHERE Song.ID_ARTIST = ‘1’;”

Why sequelize tries to get an nonexistent column like Song.PlaylistIDPLAYLIST or Song.ArtistIDARTIST when not use ‘attributes’ field in findAll or similar methods

Thanks in advance, if other info is needed tell me 🙂

Vue 3 data not retreactive

i’ve been trying to upgrade from Vue 2 to 3 for months and I’m having trouble with a data property not being reactive. The parent component has this:

<component
      :class="parentBlock.blockType"
      v-model="parentBlock"
      :is="getType(parentBlock.blockType)"
      :context="context"
    />

The child component has a block data property that gets updated by a 3rd party. The block successfully updates within the child in the updateImage() and then the watch fires and emits to the parent, parent updates the parentBlock and it successfully updates down to the child. The modelValue in the child is updated but the block resets to the old value and for the life of me, I have no idea why. I have tried using a watch on modelValue but Vue throws a lot of errors in the console.

// NOTE this is actually Vue 3
<script>
import { reactive } from 'vue'

export default {
  name: 'RWImage',
  props: {
    modelValue: {
      type: [Array, Object],
    }
  },
  created() {
    this.block = reactive(this.modelValue);
  },
  watch: {
    block: {
      deep: true,
      // immediate: true,
      handler(newVal) {
        // The newVal is right. This emits up to the parent which updates that
        // modelValue and comes back down to this child where the block gets updated with the 
        // old value. However if you use the vue tools, the modelValue is right. Just this
        // keeps hanging on to old value even though it updated down in updatedImage(). 
        this.$emit('update:modelValue', newVal);
      },
    },
  },
  data() {
    return {
      block: {}
    };
  },
  mounted() {
    // EventBus is using mitt. Asset Chosen gets fired when the block gets changed using a
    // 3rd party plugin. This gets fired properly.
    EventBus.on('asset-chosen', this.updateImage);
  },
  method: {
    updateImage(data) {
      if (this.$.uid === data.uid) {
        this.block = Object.assign({}, this.block, {
          src: data.asset.secure_url,
          cloudinaryId: data.asset.public_id,
          cloudinary: data.asset,
        })

        // Right here, the block is updated properly. This fires the watch.
        console.log(this.block);
      }
    },
  }
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

Has anyone ran into it where the a data property resets? I’m so confused.
Thanks!

Error: cannot estimate gas; transaction may fail or may require manual gas limit SERVER_ERROR

I am trying to deploy a SimpleStorage solidity contract using javascript on WSL studio and Ganache.

My deploy.js code is:

const ethers = require("ethers");
const { readFileSync } = require("fs");
const fs = require("fs-extra");
async function main() {
  //
  const provider = new ethers.providers.JsonRpcProvider(
    "http://172.24.176.1:7545"
  );
  const wallet = new ethers.Wallet(
    "0x757b08fac160cc001a4adfebadc26ac10a6e59e2490fda35bce0c35939f265f1",
    provider
  );
  const abi = fs.readFileSync("./SimpleStorage_sol_SimpleStorage.abi", "utf8");
  const binary = fs.readFileSync(
    "./SimpleStorage_sol_SimpleStorage.bin",
    "utf8"
  );
  const contractFactory = new ethers.ContractFactory(abi, binary, wallet);
  console.log("Deploying, please wait...");
  const contract = await contractFactory.deploy(); //STOP here wait for contract to deploy
  console.log(contract);
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  });

I tried the command “node deploy.js” on the terminal and I got the following error:

root@LAPTOP-UFP1511I:~/folder/hh-fcc/ethers-simple-storage-fcc# node deploy.js
Deploying, please wait…

<ref *1> Error: cannot estimate gas; transaction may fail or may require manual gas limit [ See: https://links.ethers.org/v5-errors-UNPREDICTABLE_GAS_LIMIT ] (error={“reason”:”processing response error”,”code”:”SERVER_ERROR”,”body”:”{“id”:49,”jsonrpc”:”2.0″,”error”:{“message”:”VM Exception while processing transaction: invalid opcode”,”stack”:”RuntimeError: VM Exception while processing transaction: invalid opcoden at exactimate (C:\Program Files\WindowsApps\GanacheUI_2.7.1.0_x64__rb4352f0jd4m2\app\resources\static\node\node_modules\ganache\dist\node\1.js:2:182136)”,”code”:-32000,”name”:”RuntimeError”,”data”:{“hash”:null,”programCounter”:24,”result”:”0x”,”reason”:null,”message”:”invalid opcode”}}}”,”error”:{“code”:-32000,”data”:{“hash”:null,”programCounter”:24,”result”:”0x”,”reason”:null,”message”:”invalid opcode”}},”requestBody”:”{“method”:”eth_estimateGas”,”params”:[{“type”:”0x2″,”maxFeePerGas”:”0xd09dc300″,”maxPriorityFeePerGas”:”0x59682f00″,”from”:”0x08d5cb97517f8a7189b7b9f34ca26f554827179f”,”data”:”0x608060405234801561000f575f80fd5b506108f28061001d5f395ff3fe608060405234801561000f575f80fd5b5060043610610055575f3560e01c80632e64cec1146100595780636057361d146100775780636f760f41146100935780638bab8dd5146100af5780639e7a13ad146100df575b5f80fd5b610061610110565b60405161006e919061029f565b60405180910390f35b610091600480360381019061008c91906102f3565b610118565b005b6100ad600480360381019

Could somebody tell me what is going on please?

CombinedPropertyError discord.js v14 comando inventario

intento ejecutar este codigo, en mi bot de discord, pero no funciona, y no entiendo porque, expliqueme por favor

`const fs = require(‘fs’);
const { EmbedBuilder } = require(‘discord.js’);

const objetos = require(‘./objects.json’); // Importa el archivo de objetos

module.exports = (client) => {
client.on(‘messageCreate’, (message) => {
if (message.mentions.has(client.user) && message.content.toLowerCase().includes(‘user’)) { // Comando ‘user’
const userId = message.author.username; // Obtener el ID del usuario
console.log(message.author)
const userAccountPath = ./users/${userId}.json; // Ruta del archivo de la cuenta del usuario

  // Verificar si existe el archivo de la cuenta del usuario
  if (fs.existsSync(userAccountPath)) {
    // Leer el archivo de la cuenta del usuario
    fs.readFile(userAccountPath, 'utf8', (err, data) => {
      if (err) {
        console.error('Error al leer el archivo de la cuenta:', err);
        return;
      }

      try {
        const userData = JSON.parse(data); // Parsear los datos del archivo JSON
        const inventarioEmbed = new EmbedBuilder()
          .setTitle(`Inventario de ${message.author.username}`)
          .setColor('#00ff00')
          .setDescription('Aquí está tu inventario:');

        // Iterar sobre el inventario del usuario y obtener los nombres de los objetos
        for (const objetoId in userData.inventario) {
          const objetoNombre = objetos[objetoId] || 'Objeto Desconocido'; // Obtener el nombre del objeto del archivo objects.json
          const cantidad = userData.inventario[objetoId].length;

          inventarioEmbed.addFields({ name: objetoNombre, value: cantidad, inline: true });
        }

        message.channel.send({ embeds: [inventarioEmbed] });
      } catch (error) {
        console.error('Error al analizar los datos del archivo de la cuenta:', error);
        message.reply('Ocurrió un error al obtener tu inventario.');
      }
    });
  } else {
    message.reply('No se encontró la cuenta para tu usuario.');
  }
}

});
};`

quiero que cuendo se ejecute este comando
@bot user

se despliegue el inventario almasenado en un archivo

HTNL form, json undefined on fetch intercept of POST response

Serving a web page with nodejs, I’ve copied example code pretty much verbatim from online examples. In chrome debugger log console I get the message:
(index):83 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘json’)

I’m trying “fetch” operations for the first time, so I might be missing something. I can find no mention online of why this is happening. I did npm install json but that didn’t help. Nothing I’ve found mentions something else that should be installed or otherwise included.

Below is my code, the error is marked on the line containing “resoinse.json()

<script>

   const {fetch: originalFetch } = window;
   window.fetch = async (...args) => {
      let [ resource, config ] = args;
      console.log("resource: " + resource);
      console.log("config: " + config);
      const response = await(resource, config);
      console.log(" -- got response!");
   }

   fetch("/form-1.html", { method: 'POST'})
      .then ((response) => response.json())
         .then((json) => console.log(json));

</script>

Thanks in advance.

JS Library to display data in formats .shp, .tiff, .kml, csv, geoJSON

I’m a developer facing a problem. Currently, I’m working on an app where I need to display a map and load additional information. The app should be able to receive data in formats such as .shp, .tiff, and .kml/kmz, as well as at least CSV. However, I’m unsure if there’s a library capable of handling all of this. I was considering using Google Maps for JavaScript or Leaflet, but I can’t find documentation or examples on how to display some of these data types (I can display KML and CSV without any issues).

Could you help me and provide recommendations on how to tackle this problem? Thank you very much for your time.

I tried using the Google Maps app, but I couldn’t find a way to display .shp, .tiff, and some kmz files were causing errors. I attempted to use a parser like parse2-kmz, but I can’t get it to work since some dependencies are deprecated. I’ve been reviewing documentation, and in some places like https://blog.fileformat.com/gis/top-5-gis-file-formats-for-google-maps/, it mentions that these formats are accepted. However, I have no idea how to actually do it. I’ve spent hours and hours in the documentation, looking at examples, and I can’t find anything. Now, I’m exploring Leaflet since I found that it may be able to display more formats, but I’m not sure if anyone has a more expert opinion.

Inline buttons are not displayed when creating a telegram bot on Telefraf

A message is displayed without an inline keyboard. I didn’t notice any syntax errors, and I couldn’t find anything on the Internet.

function addDescription(ctx) {
    const keyboard = Markup.inlineKeyboard([
        [Markup.button.callback('❌ Пропустить', 'noDescription')],
    ]);

    ctx.reply("Теперь добавьте описание к фотографии", { reply_markup: keyboard, parse_mode: 'Markdown' });
}

Can we no longer export static pages in nextjs 14?

I’m trying to export my project to static HTML pages and I don’t get the CSS styles

My configuration in next.config.js

** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    unoptimized: true,
  },
  output: "export",
  reactStrictMode: false,
};

module.exports = nextConfig;

and when I try to run npm run build I find that the files do appear in the output folder but when I put them on a web server the CSS styles are not there

Try making a new example by running

npx create-next-app@lates

in next.config.js I put
output: "export",
and execute

npm run build

and the CSS is not exported either

Maybe nextjs no longer allows you to export static pages?

In the console I don’t get any errors, only the files are without styles and probably also without JavaScript