Can’t import openai in Node

I have Node 16.13.1 installed and I installed openai globally with ‘npm install -g openai’.
I imported the packages inside my script using:

const { Configuration, OpenAIApi } = require('openai')

However, when I ran my script, I got this error:

PS D:ProjectsOpenAI-Chat> node conversation.js
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'openai'
Require stack:
- D:ProjectsOpenAI-Chatconversation.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (D:ProjectsOpenAI-Chatconversation.js:1:38)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ 'D:\Projects\OpenAI-Chat\conversation.js' ]
}

How do I fix this?

How to sort language version code on my vue code

i want to ask something. No, i want you help me. how to make a function and the code to sort languange version or language code with github rest api on my vue code. if you can give me more, maybe you want give me the explanation of your answer

This is my sccript section

<script>
import axios from "axios";
import Repos from "@/components/Repos.vue";
export default {
  name: "Repositories",
  data() {
    return {
      repos: [],
      search: "",
      owner: "dimaswntech",
      filteredrepo: [],
      // searchData: false,
    };
  },
  components: {
    Repos,
  },
  methods: {
    setData(data) {
      this.repos = data;
      // console.log(this.repos.node_id);
    },
    searchData() {
      axios
        .get("https://api.github.com/users/" + this.owner + "/repos", {
          headers: {
            Authorization: "token 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",
          },
          owner: "dimaswntech",
        })
        .then((response) => {
          this.filteredrepo = response.data.filter((repo) => {
            return repo.name
              .toLowerCase()
              .startsWith(this.search.toLowerCase());
          });
          this.setData(this.filteredrepo);
        })
        .catch((error) => console.log(error));
      console.log(this.filteredrepo);
      console.log(this.search);
      // let cari = this.$refs.input.value;
      // const searchdata = this.repos.filter(function (dataRe) {
      //   return dataRe.name === cari;
      // });
      // this.filteredrepo = this.repos.name.filter((repo) => {
      //   return repo.toLowerCase().startsWith(this.search.toLowerCase());
      // });
      // this.setData(searchdata);
      // console.log(this.repos.name);
      // console.log(this.$refs.input.value);
    },
  },
  created() {
    axios
      .get(
        "https://api.github.com/users/" + this.owner + "/repos?per_page=10",
        {
          headers: {
            Authorization: "token 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",
          },
          owner: "dimaswntech",
        }
      )
      .then((response) => {
        this.setData(response.data);
        console.log("thisrepos", this.repos);
        // console.log("thissearc", response.data.name);
        // console.log("search", this.repos.name.find());
      })
      .catch((error) => console.log(error));
    // console.log(this.setData);
  },
};
</script>
<template>
  <div class="repositories">
    <div>
      <div class="input-section">
        <b-form-input
          class="form-control input-repo"
          type="text"
          v-model="search"
          @input="searchData"
          autocomplete="off"
          list="my-list-id"
          placeholder="Search repo"
        ></b-form-input>
        <div>
          <b-dropdown no-caret class="button-type m-md-1">
            <template #button-content>
              <span class="text-button">type</span>
            </template>
            <b-dropdown-item>All</b-dropdown-item>
            <b-dropdown-item>Public</b-dropdown-item>
            <b-dropdown-item>Private</b-dropdown-item>
            <b-dropdown-item>Sources</b-dropdown-item>
          </b-dropdown>
        </div>
        <div>
          <b-dropdown no-caret class="button-lang m-md-1">
            <template #button-content>
              <span class="text-button">language</span>
            </template>
            <b-dropdown-item>PHP</b-dropdown-item>
            <b-dropdown-item>Javascript</b-dropdown-item>
          </b-dropdown>
        </div>
        <div>
          <b-dropdown no-caret class="button-sort m-md-1">
            <template #button-content>
              <span class="text-button">sort</span>
            </template>
            <b-dropdown-item>Last Update</b-dropdown-item>
            <b-dropdown-item>Name</b-dropdown-item>
            <b-dropdown-item>Star</b-dropdown-item>
          </b-dropdown>
        </div>
        <button class="btn-new">
          <img src="../assets/journal-bookmark-fill.svg" alt="" /> new
        </button>
      </div>

      <datalist id="my-list-id" v-if="filteredrepo">
        <!-- <option>Manual Option</option> -->
        <option v-for="filterre in filteredrepo" :key="filterre.id">
          {{ filterre.name }}
        </option>
      </datalist>

      <div v-if="search">
        <div class="ls-repo" v-for="repo in repos" :key="repo.id">
          <Repos :repo="repo" />
        </div>
      </div>
      <div v-else>
        <div class="ls-repo" v-for="repo in repos" :key="repo.id">
          <Repos :repo="repo" />
        </div>
      </div>
    </div>
  </div>
</template>

maybe you must focusing on button-lang class. that is the html will render the sort function. i will render sort language funtion on dropdown

Is Largest Contentful Paint (LCP) measured only above the fold?

A lot of sources mention that LCP is measured only above the fold, and stops measurements after a user action like scroll or key press. Though, I am able to get LCP for an image which is lazy-loaded below the fold.

I am using sitespeed.io to run performance tests on my website using a script that scrolls the page until the end in order to look for CLS issues.

After running the test ~15 times, I can see 50% of the times it picks the topmost hero image as LCP, and the other 50% of the times it picks a slightly larger banner image which is below the fold. I found this PR on GoogleChrome’s web-vitals repo – https://github.com/GoogleChrome/web-vitals/pull/85, which talks about keeping click and keydown listeners to stop LCP measurements. I might be understanding this wrong, but does this mean that LCP can now be measured below the fold too?

array returning true and only loops through the first item. What am I doing wrong?

I am working on a 4×4 sudoku program. I am trying to loop through the column of 2d array and returning false if an elements is not present otherwise return true. I have checked using console.log and my function is only looping through the first item and returning true.
Here is my code:

function linearSearch(array, item) {
var n = array.length;
for (var i = 0; i < n; i++) {
    if (array[i] == item) {
        
        return true;
    }
}
return false;
}

function checkColumn(puzzle, j) {
//first make an array out of the values stored in column j
let check = [];

//call linearSearch on the array of column values for all values 
of k from 1 to 4
for(var i = 0; i < puzzle.length; i++)
{
    
    check.push(puzzle[i][j]);   
}
console.log(check);

for(var i = 0; i < check.length; i++)
{
    if(linearSearch(check,check[i]))
    {
        console.log(i,check[i])
        return true;
    }
    
}
return false;
}



var puzzle1 = [[1 , 2, 3, 4], [2, 3, 4, 1], [2, 3, 4, 1], [4, 1, 
2, 3]];
console.log(checkColumn (puzzle1, 2));
var puzzle = [[1 , 2, 3, 4], [2, 3, 4, 1], [3, 4, 1, 2], [4, 1, 
2, 3]];
console.log(checkColumn(puzzle , 1));

any help would be appreciated thanks

Have multiple audios but only the first one in the loop plays

I can search for a song using it’s name/artist/album/genre or something else, and songs that match that criteria, so songs matching certain genre will all appear. But only the first one that appears is playable, if I click to play any of the other songs, the first one plays.
enter image description here

I have the mp3 files inside a folder and the rest of the information in a database.

I have it so I can look for the audio that should be played by the name of the mp3 file, using the artist’s and song name.

html/php:

for($i=0; $i<$count; $i++){
                    $res = mysqli_fetch_array($result);
                    
                    echo('<tbody id="tbody">
                            <tr>
<audio id="audio" src="mp3/'.$res["song_artist"].'-'.$res["song_title"].'.mp3"> 
                                <td><button id="playbtn" onclick="playStop()">▷</button></td>
                                <td><img class="songimg" src="getimage.php?id='.$res["song_id"].'"/> </td>    
                                <td>'.$res["song_title"].'</td>
                                <td>'.$res["song_artist"].'</td>
                                <td>'.$res["song_genre"].'</td>
                                <td>'.$res["song_album_name"].'</td>
                                <td id="length"></td>
                                <script>window.onload = function() {displaylenght()}</script>
                            </tr>
                        </tbody>');
                    }    

javascrit:

function playStop() {
    if (!audio) {
        document.getElementById('playControl').style.visibility = 'visible';
        var audio = document.getElementById("audio");
        var progressed = document.getElementById("progressed");
        }
    if (audio.paused) {
        console.log(audio.duration);
        audio.play();
        audio.ontimeupdate = function(e) {   
            progressed.style.width = (Math.floor((audio.currentTime*100) / getDuration())+"%");     
        }          
        audio.volume = 0.05;
        document.getElementById('playbtn').innerHTML = "❚❚";
        document.getElementById('playbtns').innerHTML = "❚❚";

    } else {
        document.getElementById('playbtn').innerHTML = "▷";
        document.getElementById('playbtns').innerHTML = "▷";
        audio.pause();
        audio.currentTime = 0;
    }
}   

Any ideas?

Tyia

How to find minimum days – Javascript

A friend of Alex’s gave her a collection of movies as a gift, and Alex is excited to watch them all as soon as possible. The duration of movies is given in a duration vector [n], where n is the movie number, and each movie lasts between 1.01 and 3.00 hours (to two decimal places). Alex wants to spend a maximum of 3.00 hours watching movies a day, but she also wants to watch the entire collection in as few days as possible. Alex never stops watching a movie halfway through. That is, if Alex chose a movie, Alex would watch a full movie on the same day. Find the minimum number of days needed to watch the complete movie collection. Example:

n = 5 duration = [ 1.90, 1.04, 1.25, 2.5, 1.75 ]

Considering a 1-in-1 walkthrough, Alex can watch the movies in at least 3 days:

Day 1: first and second films: 1.90 + 1.04 = 2.94 -< 3.00
Day 2: fourth film: 2.5 -< 3.00
Day 3: third and fifth films: 1.25 + 1.75 = 3.00-<
Function Description: Complete the function findMinimoOfDays

findMinimoDeDias has the following parameter:

float durations [n] : the duration of each movie.
Returns:

int: the minimum number of days needed to watch all movies.
Restritions: 1 _< n _< 1000 1.01 _< duracoes [i] _< 3.0

code

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}


/*
 * Complete the 'acharMinimoDeDias' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts FLOAT_ARRAY duracoes as parameter.
 */

function acharMinimoDeDias(duracoes) {
    // Write your code here

}
function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const duracoesCount = parseInt(readLine().trim(), 10);

    let duracoes = [];

    for (let i = 0; i < duracoesCount; i++) {
        const duracoesItem = parseFloat(readLine().trim());
        duracoes.push(duracoesItem);
    }

    const result = acharMinimoDeDias(duracoes);

    ws.write(result + 'n');

    ws.end();
}

Regex javascript replace word within double quotations only

I want to replace the word “and” with “+” only within the double quotations using regex. For example:

string = graphene and “carbon and composites”

final = graphene and “carbon + composites”

Most of my regex statements are picking up every instance of and, but I want to limit it to ones enclosed in quotations

How to change routs in selected option in vue 3

I am dynamically geting data and rendering them in 

navbar.vue

``` 

    <template>
    <div>
    
    <select
      v-model="selected"
      id="location"
      name="projectId"
      v-on:change="changeRoute($event)"
      class="my-5 block w-full pl-3 pr-10 py-2 text-base border-gray-300 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm rounded-md"
    >
      <!-- <option selected> {{ jsonClientsProjects[0].name }}  {{ jsonClientsProjects[0].id }}</option> -->
      <option
        v-for="project in jsonClientsProjects"
        :key="project.id"
        :value="project.id"
      >
        {{ project.name }} {{ project.id }}
      </option>
    </select>
    
    <div>
    <template>
    
    <script>
      data() {
        return {
          customJsonAllClient: [],
          jsonClientsProjects: [],
          projectData: [],
          selected: '',
        };
      },
      async created() {
        await SERVICES.gitlab.getClientsProjects(this.projectData.gitlabId);
        this.jsonClientsProjects = SERVICES.gitlab.jsonClientsProjects;
      },
      methods: {
        changeRout(e) {
          this.$router.push("/" + e.target.value);
        },
      },
    
    </script>

``` 

my.ts file here are  routs included
 ```

    const router = createRouter( {
      history: createWebHistory( '/' ),
      routes: [
        {
          path: '/',
          component: Dashboard,
          name: 'Dashboard'
        },
         {
           path: '/project/:id/',
           props: true,
           name: 'MainBoard',
           component: MainBoard,
           children: [
              {
                path: 'uebersicht',
                name: 'overview',
                component: overview,
                children:[
                  {
                    path: 'aufgaben',
                    name: 'issues',
                    component: issues,
                  },
                  {
                    path: '/project',
                    name: 'projects',
                    component: projects,
                  },
                ]
              },
              {
                path: 'vertrage',
                name: 'invoices',
                component: invoices,
              },
              {
                path: 'design',
                name: 'design',
                component: design,
              },
              {
                path: 'zusatzaufwande',
                name: 'extraCosts',
                component: extraCosts,
              },
              {
                path: 'protokolle',
                name: 'protokols',
                component: protokols,
              },
              {
                path: 'frage',
                name: 'questions',
                component: questions,
              },
              {
                path: 'termin-plan',
                name: 'termins',
                component: termins,
              },
           ]
         },
        {
          path: '/:catchAll(.*)',
          component: error404,
          name: 'NotFound'
        }
      ],
    } );
    
    
    const app = createApp( {
      components: {},
      directives: {
      }
    } );
    
    VServices( {
      dateService,
      bexioDataService,
      gitlabDataService,
    } );
    
    app.use( router );
    
    // Add Axios plugin for AJAX requests
    app.use( VueAxios, axios );
    
    app.mount( '#vue-app' );

```

I am using  ```<router-view> </router-view> ```
 in components Dashboard, MainBoard and overview.
Whatever I try to do I always get error 

runtime-core.esm-bundler.js:38 [Vue warn]: Unhandled error during execution of native event handler
at <Anonymous as=”template” enter=”transition ease-in-out duration-300 transform” enter-from=”-translate-x-full” … >
at
at <PortalGroup target= <div class=​”fixed inset-0 flex z-40 md:​hidden” id=​”headlessui-dialog-4″ role=​”dialog” aria-modal=​”true”>​…​​ flex >
at
at
at <Dialog as=”div” class=”fixed inset-0 flex z-40 md:hidden” onClose=fn … >
at <Anonymous onBeforeEnter=fn onAfterEnter=fn onBeforeLeave=fn … >
at
at
at <MainBoard id=”a093aee4-59d8-4714-95c1-d2e216cac058″ onVnodeUnmounted=fn ref=Ref< Proxy {…} > >
at
at
warn @ runtime-core.esm-bundler.js:38
logError @ runtime-core.esm-bundler.js:212
handleError @ runtime-core.esm-bundler.js:204
callWithErrorHandling @ runtime-core.esm-bundler.js:158
callWithAsyncErrorHandling @ runtime-core.esm-bundler.js:164
invoker @ runtime-dom.esm-bundler.js:366
ListPicker._handleWindowTouchEnd @ unknown
sidebar.vue:91 Uncaught TypeError: _ctx.changeRoute is not a function
at onChange._cache.._cache. (sidebar.vue:91:32)
at callWithErrorHandling (runtime-core.esm-bundler.js:155:1)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:164:1)
at HTMLSelectElement.invoker (runtime-dom.esm-bundler.js:366:39)

I am using VUE 3

Unable to use Vue Test Utils v1 Find method for nested dom elements

I have some html markup and have jest + vue test utils installed in my project.
In my test file I am able to use Vue Test Utils@1 .find() to find a parent div by it’s #id. But when I try to find a 2 level nested html element the test runner always returns am ErrorWrapper…thus preventing me from finishing my tests.

Why is this happening?

Vue Component Markup

<template>
  <div id="selection-container">
    <div class="checkbox-container">
      <label id="my-label" for="checkboxes">My Test Label</label>
        <input type="checkbox" id="myCheckbox"/>
    </div>
  </div>
</template>

My Test

  const wrapper = mount(CheckboxComponent)
  const firstDiv = wrapper.find('#selection-container')
  console.log(firstDiv)//Properly returns a VueWrapper
  const secondDiv = wrapper.find('.checkbox-container') //Returns a Wrapper{selector: ...}
  
  const label = wrapper.find('#selection-container > .checkbox-container > #myCheckbox'); //Returns ErrorWrapper{} object

  //Directly trying to get my label
  const label2 = wrapper.find('#myCheckbox'); //ErrorWrapper { selector: '#myCheckbox' }

Why is this happening? And how do I alleviate the issue?

Thanks!

Waiting to get a response from a function before using it in a line below?

I’m working on something in an older version of Node (8.x), and I wrote a function that counts values from a bunch of hashes in redis.

The problem is, the code always uses the default value of 0, because the function seems to run after its being used in the lines below it. I can see in my logs that the value returned from the function is not 0.

How can I ensure the function runs before it moves on and is used in the redis commands below it?

Thanks, sorry if this is a rookie qestion:

You can see below i’m defining blockEffort = 0. I then call the function below to get the real values. but by the time blockEffort is used in “redisCommands.push([‘sadd’, coin + ‘:blocksExplorer’, [dateNow, shareData.height, shareData.blockHash, shareData.worker, blockEffort].join(‘:’)]);” it’s still zero.

if (isValidBlock) {
            var blockEffort = parseFloat(0);
            this.getCurrentRoundShares(function (roundShares) {
                    logger.debug("calling GetCurrentRoundShares");
                    blockEffort = [roundShares / shareData.blockDiff];
                    logger.debug(`{"message": "Calculating Block Effort", "totalRoundShares": "${roundShares}", "blockEffort": "${blockEffort}"}`);
                });
            redisCommands.push(['rename', coin + ':shares:roundCurrent', coin + ':shares:round' + shareData.height]);
            redisCommands.push(['rename', coin + ':shares:timesCurrent', coin + ':shares:times' + shareData.height]);
            redisCommands.push(['sadd', coin + ':blocksPending', [shareData.blockHash, shareData.txHash, shareData.height].join(':')]);
            redisCommands.push(['sadd', coin + ':blocksExplorer', [dateNow, shareData.height, shareData.blockHash, shareData.worker, blockEffort].join(':')]);
            redisCommands.push(['zadd', coin + ':lastBlock', dateNow / 1000 | 0, [shareData.blockHash, shareData.txHash, shareData.worker, shareData.height, dateNow].join(':')]);
            redisCommands.push(['zadd', coin + ':lastBlockTime', dateNow / 1000 | 0, [dateNow].join(':')]);
            redisCommands.push(['hincrby', coin + ':stats', 'validBlocks', 1]);
            redisCommands.push(['hincrby', coin + ':blocksFound', shareData.worker, 1]);
}



this.getCurrentRoundShares = function(cback) {
        
        connection.hgetall('ravencoin:shares:roundCurrent', function(error,result) {
            if (error) {
                logger.error(`{"message": "Error getCurrentRoundShares", "data": "${error}"}`);
                cback(error);
                return;
            } else {
                logger.debug(`{"message": "Calculating all shares in current round"}`);
                logger.debug(result.toString());

                var _shareTotal = parseFloat(0);
                for (var worker in result) {
                    logger.debug(`{"message": "Shares for each Worker", "worker": "${worker}", "shares": "${parseFloat(result[worker])}"} }`);
                    _shareTotal += parseFloat(result[worker]);
                }
                logger.debug("Total Shares: " + _shareTotal );
                cback(_shareTotal);
            }
        });         
        },
        function(err) {
              if (err) {
                logger.error(`{"message": "Error getCurrentRoundShares", "data": "${err}"}`);
                cback(0);
                return;
            }
    };

The full file is here: https://github.com/devdevdevdev1/rvnpool/blob/main/shareProcessor.js

Js queryselector dando elemento null

Bom fiz o front-end, resolvi me desafiar a criar uma funçao que trocasse os textos de acordo com o tema que fosse clicado no menu da ul, mas nao consigo chamar um elemento para o js, ja tentei o get elemnt for id, por tag, e o queryselector mas o sempre retorna o elemnto como null segue o codigo abaixo:

<ul class="nav2  botoes">
            <li> <i class="fa-brands fa-html5"></i> Html </li> 
            <li onclick="mudar()"> <i class="fa-brands fa-css3-alt"></i> Css</li> // aqui leva 
            <li> <i class="fa-brands fa-js"></i> Javascript </li>                pra a funçao 
            <li> <i class="fa-brands fa-node"></i> NodeJs </li>                 de trocar os 
            <li> <i class="fa-brands fa-react"></i> React </li>                  textos
        </ul>
    </nav>

    <div class="textos">

       <span id="texto1"> textoteste textoteste textoteste textoteste textoteste </span>

    </div>

// Javascript

var test = document.querySelector(“#texto1”);
console.log (test)

function mudar () { // vai ser uma funçao de trocar o texto exibido quando clicar num caractere

console chrome – null

Jest test environment with Fetch – ¿How to use fetch.mock.calls properly?

I am learning javascript and testing and I don’t know how to continue with this test.

I have this file api.test.js, I want to test my function getInfo() that have some fetch…

global.fetch = jest.fn();


async function getInfo(url){
  try{
    const response = await fetch(`https://dwec-tres-en-raya.herokuapp.com` + url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        withCredentials: true,
        credentials: 'include',
        "authorization": `Bearer token`
      }
    });
    const data = await response.json();
    return data;
  }catch(error){
   console.log(error);
  }
}
   


describe('(your function for doing API requests here)', () => {

  it('returns the json data', async () => {
    const response = {
    status: 200,      
    json: () => { return {id: 3, username: 'player1', name: 'Player 1'}}
    }

    fetch.mockResolvedValueOnce(response);
    return getInfo('/player/3/')
    .then(response => 
    {expect(response).toStrictEqual({id: 3, username: 'player1', name: 'Player 1'});
    console.log(fetch.mock.calls);
        })
      }
    );
})

I know I have to use fetch.mock.calls but how to use it in this situation? What I am doing wrong? Any advice?

Thank you so much.