GPT OpenSource Project – Ingestion Issue

I am trying to get the following OpenSource project working:

https://github.com/mayooear/gpt4-pdf-chatbot-langchain

I am getting the following error when running the npm run ingest command:

error [Error: PineconeClient: Error calling upsert: Error: PineconeClient: Error calling upsertRaw: FetchError: The request failed and the interceptors did not return an alternative response]
c:UsersProjectschatpdfgpt4-pdf-chatbot-langchain-maingpt4-pdf-chatbot-langchain-mainscriptsingest-data.ts:44
    throw new Error('Failed to ingest your data');
          ^


[Error: Failed to ingest your data]

Node.js v18.15.0

I have the following configured in my .env file:

OPENAI_API_KEY='sk-XXXXXXX'

# Update these with your Supabase details from your project settings > API and dashboard settings
PINECONE_API_KEY= '7XXXXXXXXX'
PINECONE_ENVIRONMENT= 'us-east1-gcp'
PINECONE_INDEX_NAME= 'default'

I have edited the pinecone.ts file and set my namespace to:

const PINECONE_NAME_SPACE = 'pdfread'; //namespace is optional for your vectors

Although not relevant at this stage I have edited the makechain.ts file to capture I am using GPT-3.5 as I am on the waitinglist for GPT-4:

modelName: 'gpt-3.5-turbo',

Finally, the pdf I am using ingesting is the MorseVsFrederick which came with the repo.

Any thoughts on what I am doing wrong?

my both Varible showing same sotred array but one is asscending another is decending ,why showing same?

// const array1 = [1, 30, 4, 21, 100000, 99];
// const asscending=array1.sort((a,b)=>a-b); //for asending
// console.log(asscending);
// array1.sort((a,b)=>b-a); //for desecnding
// console.log(array1);
// console.log(asscending);
// output[ 1, 4, 21, 30, 99, 100000 ][ 100000, 99, 30, 21, 4, 1 ][ 100000, 99, 30, 21, 4, 1 ]

My doubt is why asscending variable is changed and how to resolve it

assecending variable will not channge

Simple page hit counter with Nuxt 3 using an API

I am trying to setup a simple page hit counter with Nuxt 3 using an API.

This is my template code:

// components/TheHeader.vue

<template>
    <header>
        <div class="counter">
            <div id="visits">0005024</div>
        </div>
    </header>
</template>

<script setup>
    const { data: count } = await useFetch('https://api.countapi.xyz/hit/$website.com.au/$apikeyXXXXXXXXX?callback=websiteVisits');

    setTimeout(() => {
        document.querySelector("#visits").textContent = count.value;
        console.log(count.value);
    }, 500);
</script>

I am new to Nuxt JS and am trying to adapt this tutorial to work with this Nuxt website. I am referencing this documentation on data fetching.

This is the data that it returns, which is printing in the DOM:

/**/ typeof websiteVisits === 'function' && websiteVisits({"code":200,"value":136});

screenshot

Is there a way to extract and print the “value” only (‘136’) with Javascript? Not sure if I am going about this the right way?

Thank you in advance and sorry for the novice question, I’m still learning !!

Calling jS function in a Modal Popup

There is a table consists of different record fetched from database. There is one button in-front of every record.This button is used to open the corresponding record in a modal popup.This modal popup is also used for updating that record.The popup is opening fine but it seems that the js function inside the element of this popup not working.
I have two radio box as ‘hard copy’ and ‘Soft copy’ in that modal the moment i click on soft copy one input type file should be visisble and on clcik on other button it should be hidden. but it is not working.My js is correct as it is working fine in normal page.I cannot put my code here. What may be reason for this
1.Is there any special syntax to call the id of modal popup.
2. I have included librarry files in the base page do it need to include them again in the modal popup
3.Any Other information about this type of problem is highly appreciated.

Javascript read part of a ReadableStream and then switch streams

I need to update a large blob of data from a Cloudflare worker.

My data is (effectively) a 2-d array of unknown width or height. I’d like to read the dta one row at a time (width) to modify the row. The first three array elements of the stream will tell me the dimensions of the rest of the array.

I am writing a TransformStream to process each row at a time (set highwatermark to row size), but in order to set the highwater mark, I have to read those first three array elements.

Is there a way to read part of a stream, then switch readers?

What I’ve tried so far…

function DataSizeReader(srcStream) {

    return new TransformStream(
        {
            transform(chunk, controller){
                let sizes = new Uint32Array(chunk.buffer);
                oldWidth = sizes[0];
                oldFirstDay = sizes[1];
                oldLastDay = sizes[2];

                controller.close();
            },
        },
        undefined,
        new ByteLengthQueuingStrategy({highWaterMark: 12})
    );
}

function DataShapeStreamer(updFields, updRecs) {
    updRecs = PrepareUpdateRecords(updRecs);

    return new TransformStream(
        {
            transform(chunk, controller) {
                // ... do stuff ...
            }
        },
        undefined,
        new ByteLengthQueuingStrategy({highWaterMark: oldWidth*4})
    );
}


await stm.pipeTo(DataSizeReader(stm).writable,{preventCancel:true});
stm = stm.pipeThrough(DataShapeStreamer(oldWidth, oldLastDay, oldFirstDay));

How to add Page Number in the header of webpage when printing when that webpage?

Good day everyone this is my first time here so pls help me in better understanding

I am working on a project where I have to create computerized contracts for banks using html and they will be converted into PDF format. I am trying to add page numbers in the header of each page of the contract using html and css tags but my code is not responding any manner my codes is mentioned below.

@page {  
    @bottom-right {    
        content: counter(page);
    }
    @bottom-center{
    white-space: pre;
    content:'Read and Accepted A Signed';
  }margin:2cm;
}

and this code is not working at all.

Does React Redux not support pass-through functions from Parent -> Child?

I recently ran into a bug with my React Native & React Redux mobile app project.

In a nutshell, I have a parent component that then has a child component – where the child will call on a function that is passed in by the parent. Before this function is called, an initially empty array is added with +1 item (which both have access to) via dispatch by the child.

Let’s call this function onConfirm(). Then, when onConfirm() (the prop function passed by the parent) is called, it then calls the parent’s own local onActionConfirmed() method like so: < ...props passed in.. onConfirm={() => onActionConfirmed()}... />.

The contents of that exact array is printed out in the onActionConfirmed function – but instead of showing a populated array of length 1, it was empty in this function (a state behind). And to affirm my confusion, the FlatList that renders that data shows the item. How does that make sense.. at all..?

I have tried refactoring my code to ensure all components use the useSelector provided by React Redux, and ensured that neither component used passed-in state data. This did not resolve the issue. Every time I add in an item to the array (like in the example above), the array is one action (or state) behind when I print out its length / contents. For example, if I just added one item when it’s a length of 0, it will print as length 0, or [] for empty array.

Page restart when creating token with REST API in PHP

I create a token and when receiving it on the front-end, the webpage restarts. If I remove the code that saves the tokens to a file, everything else works fine. However, if I keep the code for saving tokens to a file, the error occurs.

LoginController.php

<?php
require_once __DIR__ . '/../../tools/Connection.php';
class LoginController{

    public function login()
{
    $data = json_decode(file_get_contents('php://input'), true);
    $username = $data['username'];
    $password = $data['password'];

    $resultado = $this->authenticate($username, $password);
    if (!isset($resultado['error'])) {
        $token = bin2hex(random_bytes(64)); // Genera un token aleatorio
        $token_data = [
            'user_id' => $resultado['id'], // Donde 'id' es el ID del usuario
            'user_role' => $resultado['rol'], // Donde 'rol' es el rol del usuario
            'exp' => time() + (60 * 60 * 24), // El token expirará en 24 horas
        ];
        file_put_contents(__DIR__ . '/../../api_token.txt', json_encode([$token => $token_data]));
        $response = [
            'success' => true,
            'token' => $token,
            'message' => 'Inicio de sesión exitoso'
        ];
        header('Content-Type: application/json');
        echo json_encode($response);
    } else {
        $response = [
            'success' => false,
            'message' => 'Nombre de usuario o contraseña incorrectos'
        ];
        header('Content-Type: application/json');
        http_response_code(401);
        echo json_encode($response);
    }
}.

    public function logout()
    {
        session_destroy();
        $response = [
            'success' => true,
            'message' => 'Cierre de sesión exitoso'
        ];
        header('Content-Type: application/json');
        echo json_encode($response);
    }

    public function authenticate(string $username, string $password)
    {
        if (empty($username) || empty($password)) {
            return ['error' => 'Usuario o contraseña vacíos', 'code' => 401];
        }
        $conn = connect();
        $sql = "SELECT p.*, CASE 
                WHEN a.IdPersona IS NOT NULL THEN 'Administrador' 
                WHEN t.IdPersona IS NOT NULL THEN 'Tutor' 
                WHEN al.IdPersona IS NOT NULL THEN 'Alumno' 
                ELSE NULL 
            END AS Rol
            FROM Persona p
            LEFT JOIN Administrador a ON a.IdPersona = p.IdPersona
            LEFT JOIN Tutor t ON t.IdPersona = p.IdPersona
            LEFT JOIN Alumno al ON al.IdPersona = p.IdPersona
            WHERE p.CorreoElectronico = :username";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':username', $username);
        $stmt->execute();
        $result = $stmt->fetch();
        if (!$result || $result['Password'] !== $password) {
            return ['error' => 'Usuario o contraseña incorrectos', 'code' => 401];
        }
        switch ($result['Rol']) {
            case 'Administrador':
                $userType = 'administrador';
                break;
            case 'Tutor':
                $userType = 'tutor';
                break;
            case 'Alumno':
                $userType = 'alumno';
                break;
            default:
                return ['error' => 'Tipo de usuario inexistente', 'code' => 401];
        }
        return [
            'id' => $result['IdPersona'],
            'nombre' => $result['Nombre'],
            'apellidos' => $result['Apellidos'],
            'email' => $result['CorreoElectronico'],
            'rol' => $userType
        ];
    }
}

Login.js

$(document).ready(function() {
  $('#login-form').submit(function(event) {
    event.preventDefault(); // Evitar el comportamiento por defecto del formulario
    const username = $('#email').val();
    const password = $('#password').val();
    fetch('http://localhost/web/back/public/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        username: username,
        password: password
      }),
      credentials: 'include'
    })
    .then(response => {
      if (response.ok) {
        document.getElementById("unauthorized").textContent = "";
        return response.json();
      } else {
        throw new Error('Error en la respuesta del servidor');
      }
    })
    .then(data => {
      console.log(data);
    })
    .catch(error => {
      document.getElementById("unauthorized").textContent = "*Usuario o contraseña incorrectos";
    });
  });
});

The project uses a routing system for the API URLs. I am providing a link to the project on Git in case there is something that needs to be reviewed regarding the routes. However, the problem should not be related to the routes since it was working without a token:
https://github.com/IvanMartinBlanco/MateMagicas

Thank you!

How should I test for an API Call reject that is in a Context?

Before, I simply mocked the API response since it had a custom hook inside that delivered the data, the “Loading…” message and, in case of failure, an error message. I used the “mockRejectedValue” method to simulate said rejection:

Information Panel Component:

function AgentInformationPanel({ agentID, renderPanel }) {
    const { agent, loading, error } = useAgent(
        'https://valorant-api.com/v1/agents/',
        agentID
    );

    if (renderPanel)
        return (
          <div>
          {
            error && (
                    <div>
                        <p>Error: {error.message}</p>
                    </div>
            )
          }
          </div>

          // ...
        )

Test:

import React from 'react';
import { render, screen } from '@testing-library/react';
import AgentInformationPanel from './AgentInformationPanel.js';
import agentsMock from '../../../agentsMock/agentsMock.js';
import axios from 'axios';

const agent = agentsMock[0];
const agentID = agent.uuid;

jest.mock('axios');

beforeEach(() => {
    axios.get.mockResolvedValue({
        data: { data: agent },
        loading: true,
        error: 'Something went wrong D:'
    });
});

afterEach(() => {
    axios.mockRestore();
});

test('Should render "Error" message when API call fails', async () => {
    axios.get.mockRejectedValue(new Error('Something went wrong D:'));

    render(<AgentInformationPanel agentID={agentID} renderPanel={true} />);

    const errorElement = await screen.findByText(
        'Error: Something went wrong D:'
    );

    expect(errorElement).toBeInTheDocument();
});

// Other tests...

But NOW that I refactored my code, and was making use of Context API, I also refactored all the test file for this same component. I was able to mock the Context data and all but when I try to run the test for mock a rejected call from the API then I don’t really know how to make it work :/

Panel Context:

import React, { useState, createContext } from 'react';
import { useAgent } from '../hooks/useAgent.js';

export const PanelContext = createContext();

export function PanelContextProvider({ children }) {
    const [id, setId] = useState();
    const [renderPanel, setRenderPanel] = useState(false);

    const { agent, loading, error } = useAgent(
        'https://valorant-api.com/v1/agents/',
        id
    );

    // This and the "restartDataForPanel" are just for a few buttons in the app.
    function setDataForPanel(agentId) {
        setId(agentId);
        setRenderPanel(true);
    }

    function restartDataForPanel() {
        setId();
        setRenderPanel(false);
    }

    return (
        <PanelContext.Provider
            value={{
                agent,
                loading,
                error,
                renderPanel
            }}>
            {children}
        </PanelContext.Provider>
    );
}

Information Panel Component (REF):

import { PanelContext } from '../../contexts/Panel.context.js';

function AgentInformationPanel() {
    const { agent, loading, error, renderPanel } = useContext(PanelContext);

    if (renderPanel)
        return (
          <div>
          {
            error && (
                    <div>
                        <p>Error: {error.message}</p>
                    </div>
            )
          }
          </div>

          // ...

Test (REF):

import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import AgentInformationPanel from './AgentInformationPanel.js';
import agentsMock from '../../agentsMock/agentsMock.js';
import { PanelContext } from '../../contexts/Panel.context.js';

const agent = agentsMock[0];

// I used this object to run other tests, and it worked.
const Context = {
    agent: agent,
    loading: true,
    error: 'Something went wrong! D:',
    renderPanel: true
};

test('Should render "Error" message when API call fails', async () => {
    const rejectContext = {
        agent: null,
        loading: true,
        error: 'Something went wrong! D:',
        renderPanel: true
    };

    render(
        <PanelContext.Provider value={rejectContext}>
            <AgentInformationPanel />
        </PanelContext.Provider>
    );

    const errorElement = await screen.findByText(
        'Error: Something went wrong D:'
    );

    expect(errorElement).toBeInTheDocument();
});

// Othe tests...

Also, the “useAgent” custom hook is the same for both versions, but if you want to know how the “useAgent” hook is built:

useAgent Custom Hook:

import { useState, useEffect } from 'react';
import axios from 'axios';

export function useAgent(url, id) {
    const [agent, setAgent] = useState();
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState();

    useEffect(() => {
        setAgent();

        if (!id) return;

        setLoading(true);

        axios
            .get(url + id)

            .then(({ data: { data } }) => {
                setAgent(data);
            })

            .catch(error => setError(error))

            .finally(() => setLoading(false));
    }, [id]);

    return { agent, loading, error };
}

Destructuring error depending on order of variables

I encountered some strange destructuring behavior when reversing a linked list in this problem:

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var reverseList = function(head) {
    let previous = null
    while (head) {

        // Version 1 - works
        [head.next, head, previous] = [previous, head.next, head]

        // Version 2 - doesn't work
        // [previous, head, head.next] = [head, head.next, previous]

        // Version 3 - doesn't work
        // [head, head.next, previous] = [head.next, previous, head]

    }
    return previous
};

I cannot for the life of me figure out why destructing assignments v2 and v3 don’t work while version 1 does. The head.next assignment is causing the problem. The error is:

Line 16 in solution.js
        [previous, head, head.next] = [head, head.next, previous]
                              ^
TypeError: Cannot set properties of null (setting 'next')

Can someone explain way version 1 works and versions 2 and 3 do not?

How can I smoothly animate adding new elements to a flexbox? i.e. animated justify

I’m trying to create a container that is centered on the page, and two javascript functions that add a circle to the container (ensuring that the circle is centered) and continues to add circles, so that they are horizontally distributed in the center of the web page. The second javascript function removes the first circle, and then the remaining circles move to the left so that they are centered on the page collectively. These two functions work fine, however.. when a circle is added or removed, the remaining circles ‘jump’ and I’m struggling to figure out how to make it smoothly animate over a second or so.

Does anyone have a method for this in css or other? I’d like any dom insertions to animate so it is not jarring to the viewer.

(Screenshot attached to show what this looks like currently.)
Screenshot

I have html, css and javascript functioning to add and remove the circles, however when a circle is added or removed, the process of moving the remaining circles into a collectively centered position is jarring and I can’t work out how to animate this smoothly using css.

Existing code added for reference:

function addCircle() {
  const circleContainer = document.querySelector('.circle-container');
  const circle = document.createElement('div');
  circle.classList.add('circle');
  circleContainer.appendChild(circle);

  setTimeout(() => {
    circle.classList.add('visible');
  }, 100);
}

function removeFirstCircle() {
  const circleContainer = document.querySelector('.circle-container');
  const firstCircle = circleContainer.querySelector('.circle');
  if (firstCircle) {
    firstCircle.classList.remove('visible');

    firstCircle.addEventListener('transitionend', () => {
      circleContainer.removeChild(firstCircle);
    });
  }
}
html,
body {
  margin: 0;
  padding: 0;
  height: 100%;
}

body {
  display: flex;
}

.circle-container {
  display: flex;
  justify-content: center;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  transition: width 3000ms;
}

.circle {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  background-color: #1abc9c;
  opacity: 0;
}

.circle.visible {
  opacity: 1;
}

.button-container {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  flex-grow: 1;
}

button {
  margin: 0 10px 20px;
}
<div class="circle-container"></div>
<div class="button-container">
  <button onclick="addCircle()">Add Circle</button>
  <button onclick="removeFirstCircle()">Remove First Circle</button>
</div>

I’m open to a better way of achieving this.

Need to compare argument Object ‘x’ with data called from API and extract name or metadata from JSON when successfully compared

Novice here. There are two API’s storing interfaces and switches. Right now I’m testing my function with interfaces API. I am taking object ‘x’ which looks like 00:00:00:00:00:00:00:02:300:00:00:00:00:00:00:02:4294967294 and passing it as an argument to the function. Before I can use it, I am trying any and every way I can to work with the data in const response (also stored in const data as json). I tried using an await keyword to get the variable value or item so I can take it and convert it to a string and compare it to const data which is composed of JSON. If they are equal, I will check the data JSON members for “switch.metadata.node_name” (or interface.name if no metadata) or “interface.metadata.port_name” (or switch.id if no metadata) and display that on the web browser instead of 00:00:00:00:00:00:00:02:ABCXYZ

My problem begins at extracting the data to store in a variable so I can work with it. I just need to compare strings and access Json data. It is displayed as a Promise on the Web Browser, it is “undefined” upon inspection in the browser, I cannot take Json data from it, and it is only viewable with console.log()

async fetch_dpids(x) {
      try {
          const response  = await fetch('/api/myAPI/topology/v3/interfaces');
          const data      = await response.json();
          const dpids = Object.entries(data.interfaces).map(([key, value]) => {
            let item = key;
            if (value.name) {
              item = `${value.name} - ${item}`;
              console.log(item);
              
              
            }
            return item;
          });

          this.dpids = dpids;


      } catch (error) {
          console.error(error);
      }
    },
   },

I tried to include screenshots of output and data, but stackoverflow says this is either spam or I need more reputation to post the links. Sorry.
1
2

Trying to access JSON
3
4

Next way I tried
5
6

This is the output with just item = ${value.name} – ${item}; and console.log(item); washout code to extract JSON data.
7
8

I can’t delete the html tag in react

I’m trying to remove the Placemark tag so that I can replace it with a Placemark with a different picture. This event should occur when you click on the image. React error: Cannot read properties of null (reading ‘removeChild’) TypeError: Cannot read properties of null (reading ‘removeChild’)

import React from "react";
import './SearchPower.css';
import { YMaps, Map, Placemark} from '@pbe/react-yandex-maps';

function App() {
  // Определение геопозиции пользователя 
  var getLocationPromise = new Promise((resolve) => {
    navigator.geolocation.getCurrentPosition(async function (position) {
    resolve([position.coords.latitude, position.coords.longitude])
    })
  })
    var [lat, setLat] = React.useState(0)
    var [lng, setLng] = React.useState(0)
  getLocationPromise.then((location) => {
    setLat(location[0])
    setLng(location[1])
  })
  if (lat == 0 && lng == 0) {
    lat = 55.75
    lng = 37.57 }

    

  // Создание карты
  var myMap = React.useMemo(
    () => ({ center: [lat, lng], zoom: 9 })
  );
  
  // Работа с метками
  var IconGeoPosition = "images/Marks/ZemMark.png"
  function GeoPositionMarkChanged(LinkMark) {
    IconGeoPosition = LinkMark
    ChangedMyPosition()
  }

  function ChangedMyPosition() {
    var elem = document.getElementById("myPosition");
    elem.removeChild(elem); // THE ERROR OCCURS HERE.

    return <Placemark geometry={[lat, lng]} 
    options={{
      iconLayout: 'default#image',
      iconImageHref: IconGeoPosition,
      iconImageSize: [40, 40],
      iconImageOffset: [100, -10]
    }} className="myPosition"/>;
  }
  
    return (
      <div className="ContextSP">
        <div className="DivMarks">
        <img className="MarkLeftImage" src="images/Marks/ZemMark.png" onClick={function() {GeoPositionMarkChanged("images/Marks/ZemMark.png")}}/>
        <img className="MarkImage" src="images/Marks/Redcar1Mark.png" onClick={function() {GeoPositionMarkChanged("images/Marks/Redcar1Mark.png")}}/>
        <img className="MarkImage" src="images/Marks/Redcar2Mark.png" onClick={function() {GeoPositionMarkChanged("images/Marks/Redcar2Mark.png")}}/>
        <img className="MarkImage" src="images/Marks/GreencarMark.png" onClick={function() {GeoPositionMarkChanged("images/Marks/GreencarMark.png")}}/>
        <img className="MarkRightImage" src="images/Marks/YellowcarMark.png" onClick={function() {GeoPositionMarkChanged("images/Marks/YellowcarMark.png")}}/>
        </div>
          <YMaps>
          <Map style={{width: '100%', height: '100%', margin: '0 0 10px 0'}} state={myMap}>
              <Placemark geometry={[lat, lng]} 
                  options={{
                    iconLayout: 'default#image',
                    iconImageHref: IconGeoPosition,
                    iconImageSize: [40, 40],
                    iconImageOffset: [100, -10]
                  }} id="myPosition"></Placemark>
          </Map>
          </YMaps>
        </div>
        )
    }
    export default App;