Cannot find module ‘express’ even though ‘express’ is already installed

I ran the command npm start and got the following error.

node:internal/modules/cjs/loader:928
  throw err;
  ^

Error: Cannot find module 'express'
Require stack:
- C:CodecodeFilecode-file-appdistserverserver.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:925:15)
    at Function.Module._load (node:internal/modules/cjs/loader:769:27)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (C:CodecodeFilecode-file-appdistserverserver.js:6:35)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:76:12) {
  code: 'MODULE_NOT_FOUND',
}
npm ERR! code 1
npm ERR! path C:CodecodeFilecode-file-appserver
npm ERR! command failed
npm ERR! command C:WINDOWSsystem32cmd.exe /d /s /c node ../dist/server/server.js

npm ERR! A complete log of this run can be found in:
npm ERR!     C:Userspatriv5AppDataLocalnpm-cache_logs2023-04-20T15_45_54_540Z-debug.log

I already ran the command npm install express and see express listed in my package.json dependencies and in my node_modules folder yet I am still receiving the error. Has anybody else encountered this issue?

How to access individual properties in an array of objects returned from axios post?

I am trying to search a database for records on specific workout data to use Chart.js to display a line graph showing progress. I have the data returned from axios, but when trying to use chart.js, it give me an error saying I can’t use an array of objects as input for chart, so I need to access the individual properties of each object to create an array for the x and y axis.

What would be the syntax for accessing each date and weightOne from all objects?

one of the 14 objects returned from axios post

I have tried accessing the properties from the axios response in a loop and adding each date and WeightOne to an array, but the arrays are still empty.

Vaadin and Quill Editor: Issues with saving the current content

I am having an issue with integrating the Quill Editor into my Vaadin application. When I change the content of the editor and save it, I do not get the current content of the editor but the previous content instead. I have tried to get the content using CompletableFuture and executeJs, but it still doesn’t work as expected. When I try to save the new content, setValue is called, but futureContent.get() returns null.

Here is the relevant code:

@JsModule("./js/quill.js")
public class QuillEditor extends AbstractSinglePropertyField<QuillEditor, String> {

  public QuillEditor() {
        super("value", "", false);
        getElement().executeJs("createQuillEditor($0)", getElement());

        getElement().addEventListener("text-change", event ->
                fireEvent(new ComponentValueChangeEvent<>(this, this, getEmptyValue(), false)));
    }

    @Override
    public String getValue() {
        CompletableFuture<String> futureContent = new CompletableFuture<>();

        ui.access(() -> {
            PendingJavaScriptResult pendingResult = getElement().executeJs("return getHtmlContent($0)", getElement());
            pendingResult.then(jsonValue -> futureContent.complete(jsonValue.asString()));
        });

        try {
            return futureContent.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    @Override
    public void setValue(String htmlContent) {
        getElement().executeJs("setQuillEditorHtmlContent($0, $1)", getElement(), htmlContent);
    }
}

quill.js

window.createQuillEditor = function (element) {
    const quill = new Quill(element, {
        theme: 'snow',
        modules: {
...... etc.

window.getHtmlContent = function (element) {
    const quill = Quill.find(element);
    console.log('Current content:', quill.root.innerHTML);
    return quill.root.innerHTML;
};

window.setQuillEditorHtmlContent = function (element, htmlContent) {
    const quill = Quill.find(element);
    quill.setContents(quill.clipboard.convert(htmlContent));
    console.log('HTML Content:', quill.root.innerHTML);
};
}

I have added various console.log() statements to check the content of the editor, and it seems that the JavaScript code is correctly retrieving the current content. However, the new content is not being properly passed to the Java code.

Does anyone have experience with integrating the Quill Editor and Vaadin or have an idea how I can fix this issue? Any help is greatly appreciated!

Thank you in advance!

In my other class, I have implemented the following binding:

binder.forField(quillEditor).bind(CustomTextblock::getContent, CustomTextblock::setContent);

Grabbing content from tag and passing to OpenAI API for processing

I am building a script using the OpenAI API that grabs text content from a clicked on

tag in index.html and passes to a separate script in explanation.html where the content from the clicked on

tag in index.html is passed to the script in explanation.html where OpenAI processes the content as “What does this sentence mean?” +

content and returns an output that is an explanation of the

content provided to the OpenAI API.

Here is the code I am working with:

index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Example</title>
    <script type="text/javascript">
      function showExplanation(element) {
        const sentence = element.textContent.trim();

        fetch('/explanation.html?sentence=' + encodeURIComponent(sentence))
          .then(response => response.text())
          .then(explanation => {
            const win = window.open('', '_blank');
            win.document.write('<html><head><title>Explanation</title></head><body><p>' + explanation + '</p></body></html>');
          })
          .catch(error => console.log(error));
      }
    </script>
  </head>
  <body>
    <a href="#" onclick="showExplanation(this)">Sentence 1</a>
    <a href="#" onclick="showExplanation(this)">Sentence 2</a>
    <a href="#" onclick="showExplanation(this)">Sentence 3</a>
  </body>
</html>

explanation.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Explanation</title>
  </head>
  <body>
    <p>Loading...</p>
    <script type="text/javascript">
      const sentence = new URLSearchParams(window.location.search).get('sentence');
      const api_key = 'YOUR_OPENAI_API_KEY_HERE';

      fetch('https://api.openai.com/v1/engines/davinci-codex/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer ' + api_key
        },
        body: JSON.stringify({
          'prompt': "What does this sentence mean? " + sentence,
          'max_tokens': 512,
          'n': 1,
          'stop': '.'
        })
      })
        .then(response => response.json())
        .then(output => {
          const explanation = output.choices[0].text;
          const pElement = document.createElement('p');
          pElement.textContent = explanation;
          document.body.innerHTML = '';
          document.body.appendChild(pElement);
        })
        .catch(error => console.log(error));
    </script>
  </body>
</html>

I tried running the code on My live site and it seems to be getting stuck with a “Loading…” response. The static “Loading…” in the code is not being replaced by the dynamic explanation being fetched from the OpenAI using the provided prompt + sentence extracted from the

tag. Any ideas on how to get this script to return the dynamic explanation?

convert xml to json and force element into array

from this xml:

<pazienti type="array">
<paziente type="Paziente">
<pz-ds-cognome>COGNOME</pz-ds-cognome>
<pz-ds-nome>NOME</pz-ds-nome>
</paziente>
</pazienti>

using this javascript:

// Function to convert XML -> JSON
function convertXmlToJson(xml) {
  const parser = new xml2js.Parser({ explicitArray: false, ignoreAttrs: true });
  return new Promise((resolve, reject) => {
   parser.parseString(xml, (err, result) => {
    if (err) {
      reject(err);
    } else {
      const pazienti = result.pazienti;

      if (pazienti && pazienti.paziente && !Array.isArray(pazienti.paziente)) {
        pazienti.paziente = [pazienti.paziente];
      }
      resolve(result);
    }
});

});
}

when there are more “pazienti” it works fine, when there is only one “paziente” i get:

"pazienti": {"paziente": {"pz-ds-cognome": "COGNOME.","pz-ds-nome": "NOME"}}

I would like to get:

"pazienti": { "paziente":[{"pz-ds-cognome": "COGNOME.","pz-ds-nome": "NOME"}]}

Otherwise when there are more “pazienti”:

"pazienti": { "paziente":[{"pz-ds-cognome": "COGNOME1.","pz-ds-nome": "NOME1"},
                          {"pz-ds-cognome": "COGNOME2.","pz-ds-nome": "NOME2"}]}

How to store multilevel conditions in an array

I want to code a function to handle definable conditions.

The reference data is contained in an object and a simple condition is stored in a 3 elements array like this :

["name", "==", "John Doe"]

here is the code that works well to test a simple condition:

function getResultOfSimpleCondition(data, condition) {
    let c1 = data[condition[0]],
        operateur = condition[1],     
        c2 = condition[2], cond=true;
        switch(operateur){
                case "==" :
                case "="  :         cond = (c1 == c2 ); break;
                case "!=" :         cond = (c1 != c2 ); break;
                case ">"  :         cond = (c1 >  c2 ); break;
                case "<"  :         cond = (c1 <  c2 ); break;
                case ">=" :         cond = (c1 >= c2 ); break;
                case "<=" :         cond = (c1 <= c2 ); break;
                case "like":        cond = (c1.indexOf(c2) >  -1); break;
                case "not like":    cond = (c1.indexOf(c2) == -1); break;
                default   :         cond = (c1 == c2 ); break;
        }
    return cond
}

let myData = { name:'John Doe', age:'28', town:'PARIS', qty:5, uptodate: true},

    condition_0 = ["name", "==", "Jack Sparrow"],    // result false
    condition_1 = ["age", ">=", "24"],               // result true
    condition_2 = ["uptodate", "==", false],         // result false
    condition_3 = ["town", "==", "PARIS"];           // result true

console.log( getResultOfSimpleCondition(myData, condition_0) )

what I’m looking for is how to implement more complex conditions on the same principle.

For example:

on 2 levels:

[ condition_0, "OR", condition_1 ] // result true

or

[ condition_1, "AND", condition_2 ] // result false

on more levels:

[[ condition_0, "OR", condition_1 ], "AND", condition_3] // result true

or

[[ condition_0, "OR", condition_1 ], "AND", condition_3, "AND NOT", [condition_5, "OR", condition_23 ] ]

thank you in advance

How to make cards scroll vertically

What is the best way to create a vertical scroll when one card is stacked on top of another, similar to the example shown in the link below?

Link here

I’ve searched some information and examples but haven’t found anything.

If anyone knows or has examples, please share.

Is it faster to work with array or with dict?

I have ~1Kb dict looking like:

db = {"word": 0, "something": 1, "another": 2, ..., "last": 36000}

and I use the following operations:

  1. find an index of some word (like db["something"]);
  2. find word by its index (like Object.keys($db)[1234])

It works slowly. Would it help if I switch to array?

Chrome Extension – Jquery not loading

I am trying to run JQuery on the chrome extension I built. I am getting the following errors when I load the extension. Uncaught ReferenceError: $ is not defined and Refused to load the script ‘https://code.jquery.com/jquery-3.5.1.min.js’ because it violates the following Content Security Policy directive: “script-src ‘self’ blob: filesystem:”. Note that ‘script-src-elem’ was not explicitly set, so ‘script-src’ is used as a fallback.

So currently I have a thirdParty folder with jQuery-3.5.1.js file

This is how manifest.json looks:

    "manifest_version" : 2,
    "name" : "Calculator",
    "version" : "1.0",
    "description" : "Calculate Anywhere",
    "icons" : {
        "128" : "img/icons128.png",
        "48" : "img/icons48.png",
        "16" : "img/icons16.png"
    },
    "background":
    {
        "scripts": ["thirdParty/jquery-3.5.1.min.js", "background.js"]
    },
    "browser_action" : {
        "default_icon" : "img/icons16.png",
        "default_popup" : "popup.html"
    }
}

this is my backround.js

chrome.browserAction.onClicked.addListener(function (tab) {
    chrome.tabs.executeScript({
        file: 'thirdParty/jquery-3.5.1.min.js'
    });
    chrome.tabs.executeScript({
        file: 'popup.js'
    });
});

popup.js has the main JS and Jquery code for my extension.
Furhtermore I have a script tag to call jquery script in my popup.html which looks like this

    
    <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Can someone please tell me what I am missing in the code!!

How to make a Framework 7 toolbar animation?

I am currently developing an app using F7, i have a toolbar ( the bottom menu) , what i want to achieve is, when i the active page changes, the background color from the previous item slides to the new active page indicator.

This is an example of what i am trying to achieve:

https://www.jqueryscript.net/menu/sliding-active-nav-item-indicator.html

Yet, this does not work with F7

This is my current design, i need the white background color to slide horizontally to the page i click on

This is my first time attempting something like this

¿Como puedo validar un objeto o array con react yup? [closed]

Tengo que validar un formulario de react utilizando YUP.
En el mismo tengo un objeto Estado: {nombre: “”}
Y otros objetos o atributos que dependen su obligatoriedad, dependiendo el valor del estado inicial.
Encontre la funcion .when que utilizo en el siguiente ejemplo

export const formValidation = Yup.object().shape({
  documento: Yup.string().required("*Requerido"),
  estado: Yup.object({
    nombre: Yup.string().required("*Requerido"),
  }),

  vidautil: Yup.number()
    .positive("Valor negativo")
    .when("estado.nombre", {
      is: (value) => value !== "Fin" && value !== "Inicio",
      then: Yup.number().required("*Requerido"),
      otherwise: Yup.number(),
    })
});

La misma funciona perfectamente en el atributo vidautil. Pero al momento de aplicar la misma logica en un objeto o un array, ya deja de funcionar.

export const formValidation = Yup.object().shape({
  documento: Yup.string().required("*Requerido"),
  estado: Yup.object({
    nombre: Yup.string().required("*Requerido"),
  }),

  vidautil: Yup.number()
    .positive("Valor negativo")
    .when("estado.nombre", {
      is: (value) => value !== "Fin" && value !== "Inicio",
      then: Yup.number().required("*Requerido"),
      otherwise: Yup.number(),
    }),

  deposito: Yup.object({
    nombre: Yup.string().when("estado.nombre", {
      is: (value) => value !== "Prospeccion" && value !== "Exploracion inicial",
      then: Yup.string().required("*Requerido"),
      otherwise: Yup.string(),
  }),
});

Por ejemplo, aqui aplico la misma logica en el objeto Departamento: {nombre: “”} y ya no funciona. Siempre me lo toma como requerido.

Desde ya, muchas gracias

Probe validarlo de varias formas, cambiando los operadores de comparación. Pero siempre me arroja el mismo error

How to genrate a blurhash string of a image in react native?

I am using the package **react-native-blurhash **but the problem with that package it is making app very very slow on a real device and on an android emulator it just stops working this all happens if I try to encode the image and try to generate a blurhash string to display a blur placeholder to my image

So is there any other fast way to to genrate a blurhash string of a image in react native? reducing image size do not helps me my images are in 100kbs

const blurhash = await Blurhash.encode(image, 4, 3)

The n operator seems to have no effect on webpage

I’m currently trying to first generate string and then set some text-content on my webpage to this string. This string consists of multiple Javascript objects. I would like each of these objects to be printed on a new line. For all I know, I can simply add n after each object within my string and it should work. However, it doesn’t. Here is my code:

function stringifyObjects(objects) {    
    if (objects.length > 0) {
        str = objects.slice(0, 5).reduce( function (acc, o) { 
            return acc + " " + stringifyObject(o) + "n"
        }, "") 
        if (objects.length > 5) {
            str = str + " and " + (objects.length - 5) + " more"
        }
        console.log(str)
        return str               
    } else {
        return "No objects to show"
    }    
}

function stringifyObject(object) {
    const content = JSON.stringify(object.content).replaceAll('"', '')
    return message.type + ": " + content 
}

paragraph.textContent = stringifyObjects(someObjects)

The console.log() seems to work just fine, showing every object on a seperate line. Within the paragraph however, there are no newlines. Example below:

enter image description here

Any idea what might be causing this and how I would resolve this?