How can I optimize a Twilio function?

I’m trying to make a whatsapp bot that provides OpenAI’s GPT3.5 with Twilio’s whatsapp messaging services via their API. I’m using the following serverless function:

const fetch = require('node-fetch');
exports.handler = async(context, event, callback) => {
    const history = [{"role": "system",
        "content": "Eres un asistente educativo para estudiantes de una escuela primaria"}, {'role': 'user', 'content': event.message}];
    try{
        const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${context.OPENAI_KEY}`
            },
            body: JSON.stringify({
                "model": "gpt-3.5-turbo",
                "max_tokens": 750,
                "n": 1,
                "temperature": 0,
                "messages": history
            })
        });
        const data = await response.json();
        return callback(null, data.choices[0].message.content);
    }catch(error){
        console.log(error);
        return callback(error);
    }
}

However, the execution usually takes more than 10 seconds and its automatically stopped by Twilio. I need to use a function specifically because I need to send the API key as a header, and the flow HTTP request widget doesn’t allow custom headers.

I’ve already streamlined and removed extra functionality, but the functions still takes a long time, am I doing something wrong or is there a way to further optimize the function?

Script not working when there is another layer present above smart object

JJMack’s legendary batch mockup script is not working if there is another layer above smart object

I have started recently to use late JJMack’s legendary mockup batch replacement script and I am fascinated with it.

However, I have noticed that it will not work in a condition if there is any layer above the layer with a smart object. In these conditions script will return an error. This is sometimes not handy if I want to apply stylistic lightning above smart object to give better impression. Does anyone thinks if it is possible to modify this script to achieve such a result. I am uploading example with PSD template file and a copy of JJMack’s script:
https://drive.google.com/drive/folders/1hj56qzdwGRHuQlpe8_byJ9pgktnlY481?usp=sharing

Any help or leads would be greatly appreciated.
Best regards.

Moved the top layer below the smart object and then of course script works. However, in that case the lightning effect above the replaced smart object is not applied.

Why is this flatlist not showing? [closed]

I am a beginner and don’t understand why this component is not showing in Android but is showing for IOS

const CatagoriesList = ({flatListData}) => {
  return (
    <View style={styles.container}>
      <FlatList
        horizontal
        data={flatListData}
        keyExtractor={(item) => Math.random().toString()}
        renderItem={(itemData) => {
          return (
            <Pressable style={styles.itemContainer}>
              <Text style={styles.itemText}>{itemData.item.name}</Text>
            </Pressable>
          );
        }}
      />
    </View>
  );
}

const styles = StyleSheet.create({
 
    itemContainer: {
      alignSelf: "flex-start",
      marginRight: 10,
      borderRadius: 30,
      backgroundColor: "#f5f5f5",
      height: 40,
      justifyContent: "center",
      alignItems: "center"
    },
    itemText: {
        marginHorizontal: 20
    }
})

This is the current code. The data that is passed into the flatlist seems to be right as it works for IOS ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Why does my Node.js application not stop when using –inspect?

I have the following Node.js application here:

const express = require("express")
const bodyParser = require("body-parser")
const mysql = require("mysql2")
const path = require("path")

const app = express()
app.use(bodyParser.json())

const connection = mysql.createConnection({
    host: process.env.MYSQL_HOST,
    user: process.env.MYSQL_USER,
    password: process.env.MYSQL_PASSWORD,
    database: process.env.MYSQL_DATABASE
})

connection.connect((err) => {
    if (err) {
        console.error(err);
    }
})

connection.query("CREATE TABLE IF NOT EXISTS todo (id INTEGER AUTO_INCREMENT, todo VARCHAR(255), PRIMARY KEY(id))", err => {
    if(err) {
        console.error(err);
    }
})

app.get("/todos", (req, res) => {
    connection.query("SELECT todo FROM todo", (err, results) => {
        if(err) {
            console.error(err);
            res.sendStatus(500);
        }
        res.status(200);
        res.send(results);
    })
})

app.post("/todo", (req, res) => {
    connection.query("SELECT COUNT(*) AS count FROM todo", (err, results) => {
        if (err) {
            console.error(err);
            res.sendStatus(500);
        }
        const id = results[0].count + 1;
        connection.query("INSERT INTO todo (id, todo) VALUES (?, ?)", [id, req.body.todo], (err) => {
            if(err) {
                console.error(err);
                res.sendStatus(500);
            }
            res.status(201);
            res.send(id.toString())
        })
    })
})

app.get("/", (req, res) => {
    res.sendFile(path.join(__dirname, "index.html"));
})

app.get("/client.js", (req, res) => {
    res.sendFile(path.join(__dirname, "client.js"))
})

app.listen(8000);

If I execute this server with node --inspect (or --inspect-brk) app.js and set a breakpoint somewhere, the application does not stop there.

I have already tried this with the code lines const id = results[0].count + 1; and app.listen(8000);. I expected the application to stop when these lines were reached. I used the application in a way which reaches these lines by sending an HTTP Post request to reach the former line and I simply started the app to reach the latter line. I tried it with WebStorm and Chrome DevTools as well. What could be the reason, why this does not work? I would be very grateful for any tips.

Nested axios call within a loop does not render data

My component makes three different axios call where two of the axios calls gets called within another inside a loop which is shown below. When the component is finished rendering it only renders the data from the first axois call getAllSearchResults but the other two axios call getProductsByIds and getLegalNamesById does not render the data when the component first renders unless I interact with the component like clicking on the component then it renders. I am not sure what I am doing wrong?

let panels = {documentSource: {summary: 'Document Source', content: new Set()},
  legalName: {summary: 'Legal Name', content: new Set()},
  productName: {summary: 'Product Name', content: new Set()},};

const RenderData = () => {

  const [accordionResults, setAccordionResults] = useState(null);
  const [isLoadingLegalName, setIsLoadingLegalName] = useState(true);
  const [isLoadingProductName, setIsLoadingProductName] = useState(true);

  useEffect(() => {
      fetchResults();
  }, []);
  
  const fetchResults = () => {
    return searchService()
    .getAllSearchResults("search", 650)
    .then((response) => {
      let results = response.data.results;
      if (results.length > 0) {
        return Promise.all(results.map((obj, index) => {
          panels.documentSource.content.add(obj.A.value[0]);
          getLegalName(obj.B.value[0]);
          getProductName(obj.C.value[0]);
        }))
      }
      setAccordionResults(panels);
    }).catch((error) => {
      console.log(error);
    });
  };

  const getLegalName = (id) => {
    return CommonRefService()
    .getLegalNamesById([id])
    .then((response) => {
      const legalName = response.data.results[0];
      panels.legalName.content.add(legalName.name + ' - ' + legalName.id);
      setIsLoadingLegalName(false);
    }).catch((error) => {
      console.log(error);
    });
  };

  const getProductName = (id) => {
    return commonService()
    .getProductsByIds([id])
    .then((response) => {
      const productName = response.data[0].prodType;
      panels.productName.content.add(productName);
      setIsLoadingProductName(false);
    }).catch((error) => {
      console.log(error);
    });
  };
  
  if(isLoadingProductName || isLoadingLegalName) {
    return <div>Loading...</div>;
  }

I tried the above approach

Firebase is not updating with react.js

Im creating a blog for learning full-stack development, and im tryning to update a post with firestore, a firebase feature. But isnt working, i dont know how to solve this problem. Can someone help me? Im using a hook called “useUpdateDocument.jsx” for connect with database and collection and do the update. and a page called “EditPost.jsx”

useUpdateDocument.jsx code:

import { useEffect, useReducer } from "react";
import { db } from "../firebase/config";
import { doc, updateDoc } from "firebase/firestore";

export const useUpdateDocument = (docCollection) => {
  const updateReducer = (state, action) => {
    switch (action.type) {
      case "LOADING":
        return { loading: true, error: null };
      case "UPDATED_DOC":
        return { loading: false, error: null };
      case "ERROR":
        return { loading: false, error: action.payload };
      default:
        return state;
    }
  };

  const [response, dispatch] = useReducer(updateReducer, {
    loading: null,
    error: null,
  });

  const updateDocument = async (id, data, cancelled) => {
    dispatch({ type: "LOADING" });

    try {
      if (cancelled) {
        throw new Error("Operation cancelled");
      }

      const docRef = await doc(db, docCollection, id)
      const updatedDocument = await updateDoc(docRef, data)

      if (!cancelled) {
        dispatch({ type: "UPDATED_DOC", payload: updatedDocument });
      }
    } catch (error) {
      if (!cancelled) {
        dispatch({ type: "ERROR", payload: error.message });
      }
    }
  };

  useEffect(() => {
    let cancelled = false;

    return () => {
      cancelled = true;
    };
  }, []);

  return { updateDocument: (document) => updateDocument(document), response };
};

EditPost.jsx code:

import styles from './EditPost.module.css'

import { useState, useEffect } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { useAuthValue } from "../../context/AuthContext.jsx"
import {useFetchDocument} from "../../hooks/useFetchDocument.jsx"
import { useUpdateDocument } from '../../hooks/useUpdateDocument.jsx'

const EditPost = () => {
  const {id} = useParams()
  const {document:post} = useFetchDocument('posts', id)

  const [title, setTtile] = useState("")
  const [image, setImage] = useState("")
  const [body, setBody] = useState("")
  const [tags, setTags] = useState([])
  const [formError, setFormError] = useState("")

  const navigate = useNavigate()

  const {updateDocument, response} = useUpdateDocument("posts")
  const {user} = useAuthValue()

  useEffect(() => {
    if(post){
      setBody(post.body)
      setTtile(post.title)
      setImage(post.image)

      const textTags = post.tags.join(", ")
      setTags(textTags)
    }
  }, [post])
  useEffect(() => {
    console.log(response);
  }, [response]);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setFormError('');
  
    // Validar URL da imagem
    try {
      new URL(image);
    } catch (error) {
      setFormError('A imagem precisa ser uma URL.');
      return;
    }
  
    // Criar o array de tags
    const tagsArray = tags.split(',').map((tag) => tag.trim().toLowerCase());
  
    // Checar todos os valores
    if (!title || !image || !tags || !body) {
      setFormError('Por favor, preencha todos os campos!');
      return;
    }
  
    try {
      const data = {
        title,
        image,
        body,
        tags: tagsArray,
        uid: user.uid,
        createdBy: user.displayName,
      };
      console.log('Data:', data); // Adicione este console log
      await updateDocument(id, data);
  
      // Redirect to home page after the document is successfully inserted
      navigate('/dashboard');
    } catch (error) {
      console.error('Error inserting document:', error.message);
    }
  };
  return (
    <div className={styles.edit_post}>
      {post && (
        <>
          <h2>Editando post: {post.title}</h2>
          <p>Altere os dados do post como desejar!</p>
          <form onSubmit={handleSubmit}>
            <label>
              <span>Título</span>
              <input type="text" 
              name="title" 
              required 
              placeholder='Pense num bom título'
              onChange={(e) => (setTtile(e.target.value))}
              value={title} />
            </label>
            <label>
              <span>URL da imagem</span>
              <input type="text" 
              name="image" 
              required 
              placeholder='Insira uma imagem que represente seu post'
              onChange={(e) => (setImage(e.target.value))}
              value={image} />
            </label>
            <p className={styles.preview_title}>Preview da imagem atual:</p>
            <img src={post.image} className={styles.image_preview} />
            <label>
              <span>Conteúdo</span>
              <textarea type="text" 
              name="image" 
              required 
              placeholder='Insira o conteúdo do seu post'
              onChange={(e) => (setBody(e.target.value))}
              value={body}>
              </textarea>
            </label>
            <label>
              <span>Tags</span>
              <input type="text" 
              name="image" 
              required 
              placeholder='Insira tags separadas por vírgulas'
              onChange={(e) => setTags(e.target.value)}
              value={tags} />
            </label>
            {!response.loading && <button className='btn'>Cadastrar</button>}
            {response.loading != null && <button className='btn' disabled>Aguarde...</button>}
            {response.error && <p className='error'>{response.error}</p>}
            {formError && <p className='error'>{formError}</p>}

          </form>
        </>
      )}
    </div>
  )
}

export default EditPost

The error is:

Function updateDoc() called with invalid data. Data must be an object, but it was: undefined (found in document posts/pDxac50g4Ow21ksEQqDz)

Script web-scrapping ayuda

estoy intentando crear un script con el que obtener los precios y productos de los mcdonald’s que hay en ubereats. Estoy teniendo problemas a la hora de hacer el parse buscando mediante etiquetas y clases ya que he detectado que el código cambia con cada url diferente que introduzco, No se como hacer

public static void main(String[] args) {

    String url = ;

    try {
       
        Document document = Jsoup.connect(url).get();

      
        Element specificDiv = document.selectFirst("div.ch.d2.cj.d3");

      
        if (specificDiv != null) {
  
            Element spanTag = specificDiv.selectFirst("span[data-testid=rich-text].f3.ei.f4.ch.d2.cj.d3.b1");

            
            if (spanTag != null) {
                System.out.println("Etiqueta span dentro del div ch d2 cj d3:");
                System.out.println(spanTag.outerHtml());
            } else {
                System.out.println("No se encontró la etiqueta span dentro del div ch d2 cj d3.");
            }
        } else {
            System.out.println("No se encontró el div ch d2 cj d3.");
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

Converting API response to mapped class object

I’m working on an angular project that has Firebase integrated. Once the data is fetched, I want the plain object to have some additional properties and maybe a few methods in the future. These new properties will be calculated based on the existing data and some business logic. Some of these properties are only UI-specific (I know I can create a pipe for such properties but if there are like 10 of them that needs to be transformed for presentation, should I be making 10 different pipes assuming that each one uses different logic?)

To represent the raw response, I’ve created a DTO using an interface and in order to have additional data, I made a separate class.

Moreover, the raw JSON response doesn’t have the same format. Some properties are in the snake case while some are in the camel case. I want every property in my class to follow the camel case and when it’s time to save the data back to the database, I want to convert my class back to the exact format as it was in the DTO (any additional properties and methods from must be removed during transformation.)

Let’s take an example of UserDataDto. Assuming that it looks like this along with its corresponding class:

export enum AppLangCode {
  english = 'en_US',
  german = 'de_DE',
}

export interface UserDataDto {
    settings: Record<AppLangCode, string>;
    fullName: string;
    email: string;
    user_name: string;
    // Some more properties from the response
}

// Question: Should this implement "UserDto"? If I do, then I'm unable to rename or change the type of the property
export class UserData {
    userName: string; // in DTO, it was user_name
    email: string;
    fullName: string;
    settings: Map<AppLangCode, string>; // Changed the type here
}

I know I can always go with the manual mapping but isn’t there any good library that would help me to go through all this? I’ve seen solutions that ask you to add a method like toJSON or toDTO on the class that would do manual transformation but this will make me rewrite the properties again which is quite annoying.

Now, a few questions here:

  1. Am I over-complicating stuff or is this how it is supposed to be done?
  2. I’ve tried the class-transformer library but I’ve some doubts like the last published date of this package was 2 years ago. As more years pass by, this could get worse if the project is updated to the latest version but the library isn’t updated.
  3. I want to avoid getters because binding with those in the HTML makes them trigger on every change detection cycle. Is it really the case?
  4. Do you prefer immutable.js with this especially when playing with the classes and not plain objects?
  5. If I have separate classes that are binding in the HTML of the components, should all these properties of the class be public?

I’m open to any suggestions and looking forward to hearing a better way of doing everything above in the best way.

Distinguish Trackpad and mouse on wheel event

How can I Distinguish that which device triggers wheel event

node.addEventListener('wheel', handleWheel)

I want to do the following

  1. For mouse wheel: zoom in/out
  2. For pinch via trackpad: zoom in/out
  3. For two finger pan: moving pan

I don’t have questions about zoom in/out and moving pan action, these are Application specific action

My question is, How can I detect that the event is triggered by Mouse wheel or trackpad

Oracle Apex Interactive Report issue – Need to refresh the browser every time after changing select list value

I am new to Oracle Apex.

I have an issue with Interactive Report with checkbox. The query for the IR is like below:

SELECT APEX_ITEM.checkbox2 (1, deptno, p_attributes => ‘class=”deptno_cb”‘) “Select”,
deptno,
dname,
loc
FROM dept
WHERE deptno = NVL ( :p16_department_list, deptno);

Oracle apex page has a select list at the top of the page. On selecting a list value, IR report updates. Select list dynamic action refreshes the IR region.

Page Javascript in “Function and Global Variable Declaration” has below code to restrict user to select/check one checkbox at a time.

$(‘#object_details_static_id input[type=checkbox][name=f01]’).on(‘change’,function(){
$(‘#object_details_static_id input[type=checkbox][name=f01]’).not(this).prop(‘checked’,false);
});

The issue is, when I change the select list value, user can select more than one checkbox

enter image description here

When I refreshes the browser , page(checkbox) works fine and page restricts user to select only one checkbox at a time.
enter image description here

I was expecting above javascript code would restrict user to select only one checkbox at all times but it is not happening when I change the select list value. I have to refresh the browser to make the page work.

Am I doing anything wrong here. Any help would be much appreciated.

Thanks

Oracle Apex.

I was expecting javascript code

$(‘#object_details_static_id input[type=checkbox][name=f01]’).on(‘change’,function(){
$(‘#object_details_static_id input[type=checkbox][name=f01]’).not(this).prop(‘checked’,false);
});

would restrict user to select only one checkbox at all times but it is not happening when I change the select list value. I have to refresh the browser to make the page work as expected after changing the select list..

Getting Instagram cookies from Js chrome extension

I’m trying to get my Instagram cookies with my js chrome extension and document.cookie is missing a lot of needed cookies that i can see using cookie editor extensions.
here are the permissions i set.

"permissions": ["activeTab","scripting" , "cookies","tabs"],
    "content_scripts": [
      {
        "matches": ["*://soundcloud.com/*","*://*.findsocial.io/*","*://*.instagram.com/*"],
        "js": ["content.js"]
      }
    ]

console.log(document.cookie)
Onyl showing few cookies

Why does JS allow the creation of non-private (public) fields of the same label as privated fields?

I’m jumping back into JS after a while.
JS now allows the explicit indication of private object properties using ‘#’, which is great.
If getters and setters are not created for those fields, they cannot be retrieved or modified accordingly.

So, with the following snippet:

class TestClass {
  #testField;
}

let test = new TestClass();

// due to the missing `get` and `set` methods, both of the following throw
// `Uncaught SyntaxError: reference to undeclared private field or method #testField`
console.log(test.#testField);
test.#testField = {}; 

// however, with the same class definition, the following is permitted
test.testField = {};

// viewing `test` yields the following
console.log(test);    //  Object { 
                      //    testField: {}, 
                      //    #testField: undefined 
                      //  }

So, in the absence of ‘getters’ and ‘setters’ for a private field, JS differentiates between fields that share the same name, but have different access modifiers (testField vs #testField).

If, TestClass is tweaked to include a setter method for testField

class TestClass {
  #testField;

  set testField() {
    return this.#testField;
  }
}

let test = new TestClass();

test.testField = {};

// now, viewing `test` yields the following
console.log(test);    //  Object {  
                      //    #testField: { }
                      //  }

// attempting to directly acccess the private field still throws an error,  as expected
test.#testField = {}; // throws `Uncaught SyntaxError: reference to private field #testField ... `

So, with the specification of a setter, referencing testField is clearly linked to the private field, #testField, and doesn’t create a new, separate property named testField.

This most likely was a conscious language design choice(?), I am mostly wondering what the possible reasons are. Shouldn’t object properties/fields be unique (or have unique labels) regardless of their access modifier, so it wouldn’t be possible to have two identical properties such as #testField and testField, even in the absence of a setter method?

Someone sent me a zip containing js format file

I am not a techie person but I just encountered someone who is inquiring about our travel services so I asked the person if he could send me a pdf file of their travel plan, so he sent me a zip file but when I opened it, its just CSS codes and I couldnt understand anything.

So I extracted it and change the file to PDF but it wont open since the file was JS, the person said to open it on word or memopad but same codes appear, so I do not know what he is basically up to.

What I am worrying is that since I have opened the file, it might be a scam or phishing..I dont know..maybe someone could give me an advise on what I should do?

I immediately deleted the file, and run my mcafee livesafe…it didnt detect any malware or anything, but it is somehow bothering me since I am doing a small business so I am afraid of the consequences.

Extracted the file
changed the file to several format and saw codes

I was expecting the file to provide me the details of an itinerary

JS only works when page is reloaded

I have this page on my website that behaves strangely: https://ugolize.com/contact.html

If you arrive there directly from the link, the JavaScript works, but if you arrive there from a button, it no longer works.

Let me explain further: if, once on the page, you click the ‘Sì’ button, you end up on a page called ‘yes.html’. If, on that page, you click the ‘Contattaci’ button, which leads back to contact.html, the JavaScript in contact.html no longer works, and contact.html appears duplicated when checking the files in the console.

No idea what to do

I tried changing the link of the button to the full link ogf the page (https://ugolize.com/contact.html) instead of /contact.html but it doesn’t seem to work