javascript – The file uploads well to the folder but problem is : the name of the file which is in the folder is different from the one saved in the DB

enter image description here 1. This is my model

const mongoose = require('mongoose')
let TicketSchema = new mongoose.Schema({
     _id: String,
    ticketTitre:  String,
    ticketCategorie: String,
    ticketDescription: String,
    ticketImage:{
        data: Buffer,
        contentType: String
    }
})
module.exports = mongoose.model('Ticket', TicketSchema)
  1. Here is my index

    const boom = require(‘boom’)
    const { nanoid } = require(“nanoid”);
    const idLength = 2

//Get Data Models

const Ticket = require(‘./Ticket’)

const fastify = require('fastify')({
    logger: true
}),
    mongoose = require('mongoose'),
    fs = require('fs'),
    path = require('path'),
    fileUpload = require('fastify-file-upload'),
    fastifyStatic = require('fastify-static'),
    cors = require('fastify-cors');

fastify.register(fastifyStatic, {
    root: path.join(__dirname, 'public')
});

fastify.register(fileUpload);

// Connect to DB
mongoose.connect('mongodb://localhost:27017/bdfiles', { useNewUrlParser: true })
    .then(() => console.log('MongoDB connected...'))
    .catch(err => console.log(err))

fastify.post('/uploadd', function (req, reply) {
    // contains text field together with files
    //console.log(req.raw.body); 
    
    let ticketTitre = req.body.ticketTitre;
    let ticketCategorie = req.body.ticketCategorie;
    let ticketDescription = req.body.ticketDescription;
    //let ticketImage = req.raw.files('myImage').name;
    let ticketImage =  getPath('uploads', getRandomFileName());
    
   // console.log(ticketTitre,ticketCategorie,ticketDescription,ticketImage)
  //let tickett = { ticketTitre,ticketCategorie,ticketDescription,ticketImage}
    
    // return response to client
    //reply.header('Location', 'success.html').code(303).send();
    // (!) stream file to disk just for example, use it only if needed
    const imageBuffer = req.raw.files('myImage').data;
    //console.log(imageBuffer);
    const fileName = getPath('uploads', getRandomFileName());
    const stream = fs.createWriteStream(fileName);
    stream.once('open', function (fd) {
        stream.write(imageBuffer);
        stream.end();
    });
    
    /*var tickett = {
        ticketTitre: req.body.ticketTitre,
        ticketCategorie: req.body.ticketCategorie,
        ticketDescription: req.body.ticketDescription,
        ticketImage : {
            data: fs.readFileSync(path.join(__dirname + '/uploads/' + req.file.filename)),
            contentType: 'image/png'
        }
    }
    console.log(tickett)*/

    try {
        //req.raw.body
        const ticket = new Ticket({ticketTitre,ticketCategorie,ticketDescription,fileName})
        //const ticket = new Ticket({ticket})
        ticket._id = nanoid(idLength)
        return ticket.save()
      } catch (err) {
        throw boom.boomify(err)
      }
});

// Run the server!
const start = async () => {
    try {
        await fastify.listen(3000)
        fastify.log.info(`server listening on ${fastify.server.address().port}`)
    } catch (err) {
        fastify.log.error(err)
        process.exit(1)
    }
}

start()

function getRandomFileName() {
    return 'file' + String(parseInt(Math.random() * 10000)) + '.png';
}

function getPath(...parts) {
    return path.join(__dirname, ...parts);
}

javascript – Quiero que cada vez que hago click en un botón sume o acumule 1 punto

Necesito hacer que cada vez que hago click en un botón sume 1 punto y me de el resultado al final. Estoy empezando, así que aún no tengo el código en JS… pero lo que busco me sale cómo sumar o acumular pero con un input y yo necesito saber cómo acumular cada vez que se presione un botón sin yo darle un valor. Es para una especie de trivia.

Aunque no sé si sirva de algo… mintroducir la descripción de la imagen aquíi código html se ve algo así…

Não to conseguindo mostrar o que eu preciso em javascript

Assim, eu preciso que mostre no gráfico a variação do preço da moeda selecionada no período que foi escolhido. A parte do período tá certa, mas a moeda cada vez que você aperta “mostrar”, ela mostra uma moeda diferente, então por exemplo, você pode ter selecionado dólar, mas se apertar de novo vai mostrar libra, se apertar de novo, euro, e por aí vai. Ele também não tá mostrando mais de uma moeda de uma vez, e eu não to conseguindo fazer ele mostrar em tabela, mesmo que em gráfico de linha esteja funcionando.

<body>
        <div class="pagina">
            <cabecalho>
                <p style="float: left;"><img class ="img" src="https://static.wikia.nocookie.net/jedipedia/images/2/2b/Credits.png/revision/latest?cb=20080623234636&path-prefix=de" height="80px" width="80px"></p>
                <center><h2>Plataforma de Checagem de Dados de Câmbio do Império Intergaláctico</h2></center>
            </cabecalho>
            <div class="box">
                <menu>
                    <h3>Obtenção de Dados de Câmbio</h3>
                        <label for="inicio">Período Inicial</label>
                        <input type="date" id="dateIni">
                        <p>
                        <label for="fim">Período Final</label>
                        <input type="date" id="dateFim">
                        <p>
                        <h4>Selecione a(s) moeda(s):</h4>
                        <input type="checkbox" class="moedas" name="dolar" checked>
                        <label for="dolar">Dólar Americano</label>
                        <p>
                        <input type="checkbox" class="moedas" name="euro" checked>
                        <label for="euro">Euro</label>
                        <p>
                        <input type="checkbox" class="moedas" name="libra" checked>
                        <label for="libra">Libra Esterlina</label>
                        <p>
                        <h4>Selecione o tipo de saída de dados:</h4>
                        <input type="radio" name="saida" value="tab">Tabela
                        <input type="radio" name="saida" value="graf">Gráfico de Linhas
                        </p>
                        <input id="submit" type="submit" value="Mostrar" class="botao">
                </menu>
            </div>
            <principal>
                  <div id="grafico" style="width: 900px; height: 500px"></div>
                  <div id="tabela"></div>
            </principal>
            <rodape>
                <center>
                    <button type="button" onclick="print()" class="botao">SOBRE</button>
                    <button type="button" onclick="print1()" class="botao">AJUDA</button>
                </center>
                <div id="sobre"> </div>
                <div id="ajuda"> </div>
            </rodape>

        </div>
        
        <script>
            function converterData(date){
                // converte um string de yyyy-mm-dd para mm-dd-yyyy
                const (ano, mes, dia) = date.split("-")
                return (mes, dia, ano).join("-")
            }
            
            // Mostra gráfico na tela
            function draw($dados){
                const tagDestino = document.getElementById('grafico');
                google.charts.load('current', {'packages':('corechart')});
                google.charts.setOnLoadCallback(drawChart);

                function drawChart() {
                var data = google.visualization.arrayToDataTable($dados);
                var options = {
                    title: 'Cotação',
                    curveType: 'function',
                    legend: { position: 'bottom' }
                };

                var chart = new google.visualization.LineChart(tagDestino);

                chart.draw(data, options);
                }
            }
            
            function drawCharts(dados){

                draw((("data", "cotacao"),...dados))
            }
            
            const convertToCharts = json => json.map(objeto => (objeto.dataHoraCotacao, objeto.cotacaoVenda))

            var servidor = 'https://dadosabertos.bcb.gov.br/dataset/taxas-de-cambio-todos-os-boletins-diarios';
            
            function print(){
                {document.getElementById('sobre').innerHTML = 'Sobre nós: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';}
            }
            
            function print1(){
                {document.getElementById('ajuda').innerHTML = 'FAQ: Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem.';}
            }
            
            function replaceUrl(dataInicial,dataFinal,moeda){
                return `https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/CotacaoMoedaPeriodo(moeda=@moeda,dataInicial=@dataInicial,dataFinalCotacao=@dataFinalCotacao)?@moeda='${moeda}'&@dataInicial='${dataInicial}'&@dataFinalCotacao='${dataFinal}'&$top=10000&$skip=0&$format=json&$select=cotacaoVenda,dataHoraCotacao`
            }

            function fetchData(dataInicial,dataFinal,moeda){
            const url = replaceUrl(dataInicial,dataFinal,moeda)

                console.log(url)

                const dados = fetch(url)
                .then(res => res.json())
                .then(dados => {
                    const dadosFiltrados = convertToCharts(dados.value)
                    drawCharts(dadosFiltrados)
                })
            
            }
            
            function execute(){


                const dataInicial = document.getElementById("dateIni").value
                const dataFinal = document.getElementById("dateFim").value
                
                console.log(dataInicial,dataFinal)

                fetchData(converterData(dataInicial),converterData(dataFinal),'USD')
                fetchData(converterData(dataInicial),converterData(dataFinal),'EUR')
                fetchData(converterData(dataInicial),converterData(dataFinal),'GBP')

            }

            const botao = document.getElementById("submit")
            botao.addEventListener("click",execute)
        </script>
    </body>

Essa é a parte do html e do javascript

regular languages – Add more button not working for my javascript code

regular languages – Add more button not working for my javascript code – Computer Science Stack Exchange

javascript – Erro Access-Control-Allow-Origin com aplicação NodeJs e ReactJs

Estou desenvolvendo uma aplicação de chat em tempo real, usando ReactJs no front-end e Node.js no back-end. Configurei o servidor Node com Socket.io para a aplicação. Ao entrar na página do chat em si, ele deve se conectar ao servidor em questão. No entanto, ao tentar se conectar o console retorna o erro:

Access to XMLHttpRequest at ‘http://localhost:5000/socket.io/?EIO=4&transport=polling&t=Nhg2TfS’ from origin ‘http://localhost:3000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
polling-xhr.js:198

e logo abaixo:

GET http://localhost:5000/socket.io/?EIO=4&transport=polling&t=Nhg2TfS
net::ERR_FAILED

O lado do cliente roda na porta 3000 e o servidor na porta 5000 do localhost.

  • Cors v2.8.5
  • Express v4.17.1
  • Nodemon v2.0.12
  • Socket.io v4.1.3
const express = require('express');
const socketio = require('socket.io');
const http = require('http');
const cors = require('cors');

const PORT = process.env.PORT || 5000;

const router = require('./router');

const app = express();
const server = http.createServer(app);
const io = socketio(server);

io.on('connection', (socket) => {
    console.log('Novo usuário conectado!');

    socket.on('disconnect', () => {
        console.log('Usuário desconectado!');
    })
});

app.use(cors());
app.use(router);

server.listen(PORT, () => console.log(`Server has started on port ${PORT}`));
import React, { useState, useEffect } from 'react';
import queryString from 'query-string';
import io from 'socket.io-client';

let socket;

const Chat = ({ location }) => {
    const (name, setName) = useState('');
    const (room, setRoom) = useState('');
    const ENDPOINT = 'localhost:5000';

    useEffect(() => {
        const { name, room } = queryString.parse(location.search);

        socket = io(ENDPOINT);
        
        setName(name);
        setRoom(room);

        console.log(socket);
    });

    return (
        <h1>Chat</h1>
    );
}

export default Chat;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Gostaria que me ajudassem a resolver esse erro, por favor.

javascript – How to render the same instance of a React component that are defined in different places of the APP?

Let’s suppose that I have 2 top level components, A and B. The component will be created inside of both A and B. How do I ensure that the same instance of C is created in both. I.e., they are in sync, whatever happens to one the other will automatically update as well.

I have tried assigning the same key value to both, but it didn’t work.

javascript – JS script fetching GitHub API for personal website

I’ve built a quite simple personal website, everything is in a single file because it is very straightforward, but I think the JS script could be better structured. All it does is fetch some repos from the GitHub API and displays them in a horrible format.

This is it (index.html):

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta
      name="description"
      content="The successful warrior is the average man, with laser-like focus."
    />
    <title>Mauricio Robayo</title>
    <link rel="preconnect" href="https://fonts.googleapis.com" />
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
    <link
      href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;700&display=swap"
      rel="stylesheet"
    />
    <style>
      :root {
        font-size: 14px;
      }
      * {
        margin: 0;
        color: gainsboro;
      }
      body {
        font-family: "IBM Plex Mono", monospace;
        background-color: darkblue;
        padding: 0.5rem;
      }
      h1,
      h2,
      h4 {
        font-size: 1rem;
      }
      h1 {
        margin-bottom: 2rem;
      }
      h2 {
        font-weight: 400;
      }
      h4 {
        margin-top: 1rem;
      }
      ul {
        list-style: none;
        list-style-position: inside;
        padding-left: 0rem;
      }
      .error,
      .error a {
        color: red;
      }
      section {
        margin: 2rem 0;
      }
      .repo-loader {
        margin-right: 0.5rem;
      }
      .meta {
        color: darkgray;
      }
      .repo-header > *:not(:last-child) {
        margin-right: 1rem;
      }
      @media screen and (min-width: 768px) {
        :root {
          font-size: 16px;
        }
        body {
          padding: 1rem;
        }
        .repo-header {
          display: flex;
          align-items: flex-end;
        }
      }
    </style>
  </head>
  <body>
    <h1>Mauricio Robayo</h1>
    <ul>
      <li>
        <a
          href="&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#114;&#102;&#109;&#97;&#106;&#111;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;"
          >&#109;&#97;&#105;&#108;&#116;&#111;&#58;&#114;&#102;&#109;&#97;&#106;&#111;&#64;&#103;&#109;&#97;&#105;&#108;&#46;&#99;&#111;&#109;</a
        >
      </li>
      <li>
        <a href="https://www.linkedin.com/in/mauriciorobayo"
          >https://www.linkedin.com/in/mauriciorobayo</a
        >
      </li>
    </ul>
    <section id="recent-projects"></section>
    <section id="starred-projects"></section>
    <footer>
      <p>No frameworks were harmed in the making of this site.</p>
      <p>Analytics and bloatware free.</p>
      <p>
        Updated:
        <a href="https://youtu.be/dQw4w9WgXcQ?autoplay=1">27 July 1987</a>.
      </p>
    </footer>
    <script>
      loadProjects(document.getElementById("recent-projects"), "updated", 3, (
        "language",
        "updated_at",
      ));
      loadProjects(document.getElementById("starred-projects"), "stars", 3, (
        "language",
        "stargazers_count",
      ));

      function loadProjects(projectsContainer, sort, limit, meta) {
        const url = `https://api.github.com/search/repositories?q=user:MauricioRobayo&sort=${sort}&per_page=${limit}`;
        const projectsTitle = document.createElement("h2");
        const projectsBody = document.createElement("div");
        const loader = document.createElement("span");
        const link = document.createElement("a");
        const cacheStatus = document.createElement("p");
        const cacheExpirationTime = document.createElement("p");
        const cacheKey = `projects-${sort}`;

        projectsBody.classList.add("projects-body");
        loader.classList.add("repo-loader");
        link.href = url;
        link.textContent = url;

        const loaderSymbols = ("\", "|", "/", "—");
        let i = 0;
        loader.textContent = loaderSymbols(i % loaderSymbols.length);
        const interval = setInterval(() => {
          i++;
          loader.textContent = loaderSymbols(i % loaderSymbols.length);
        }, 500);

        const cache = JSON.parse(localStorage.getItem(cacheKey));

        projectsTitle.append(
          loader,
          "Fetching ",
          link,
          cacheStatus,
          cacheExpirationTime
        );
        projectsContainer.append(projectsTitle, projectsBody);

        if (cache?.expirationTime > Date.now()) {
          cacheStatus.textContent = "localStorage cache hit";
          cacheExpirationTime.textContent = `Expires: ${cache.expirationTime}`;
          loadContent({ repos: cache.repos, projectsBody, loader, meta });
          clearInterval(interval);
        } else {
          cacheStatus.textContent = "localStorage cache miss";
          fetch(url, {
            headers: {
              accept: "application/vnd.github.v3+json",
            },
          })
            .then((response) => {
              if (!response.ok) {
                throw new Error(
                  `${response.status ? response.status : ""} ${
                    response.statusText ? response.statusText : ""
                  }`
                );
              }

              const rateLimitElements = Array.from(response.headers)
                .filter(((key)) => key.toLowerCase().startsWith("x-ratelimit"))
                .map((header) => {
                  const headerElement = document.createElement("p");
                  headerElement.textContent = header.join(": ");
                  return headerElement;
                });
              projectsBody.append(...rateLimitElements);

              return response.json();
            })
            .then(({ items: repos }) => {
              localStorage.setItem(
                cacheKey,
                JSON.stringify({
                  repos,
                  expirationTime: Date.now() + 60 * 60 * 1000,
                })
              );
              loadContent({ repos, projectsBody, loader, meta });
            })
            .catch((err) => {
              loader.textContent = "✗";
              projectsContainer.append(err);
              projectsContainer.classList.add("error");
            })
            .finally(() => {
              clearInterval(interval);
            });
        }
      }

      function loadContent({ repos, projectsBody, loader, meta }) {
        const reposContainers = repos.map(
          ({
            name,
            description,
            html_url,
            language,
            stargazers_count,
            updated_at,
          }) => {
            const repoContainer = document.createElement("div");
            const metaFields = { language, stargazers_count, updated_at };
            repoContainer.innerHTML = `
        <div class="repo-header">
          <h4><a href="${html_url}">${name}</a></h4>
          ${buildMeta(
            Object.fromEntries(
              Object.entries(metaFields).filter(((key)) => meta.includes(key))
            )
          )}
          </div>
          <div class="repo-body">
            <p>${description ? description : ""}</p>
          </div>
        `;
            return repoContainer;
          }
        );
        loader.textContent = "✔";
        projectsBody.append(...reposContainers);
      }

      function buildMeta(meta) {
        const rtf1 = new Intl.RelativeTimeFormat("en", { style: "narrow" });

        return Object.entries(meta)
          .map(((key, value)) => {
            if (key === "updated_at") {
              const updatedDate = new Date(value);
              const millisecondsDiff = updatedDate.getTime() - Date.now();
              const daysDiff = Math.floor(
                millisecondsDiff / 1000 / 60 / 60 / 24
              );
              const relativeTime = rtf1.format(daysDiff, "day");
              return `<span class="meta">updated ${relativeTime}</span>`;
            }
            if (key === "stargazers_count") {
              return `<span class="meta">${value} stars</span>`;
            }
            return `<span class="meta">${value}</span>`;
          })
          .join("");
      }
    </script>
  </body>
</html>

I would appreciate any input on the JS script to make it more readable, clean, and maintainable, althought any feedback regarding the CSS and the HTML (better structure, semantic markup, accessibility, etc) would also be great. Thanks in advance!

javascript – Similar scripts being used separately for each column, making page load slower

The page I’m creating is very simple, the problem is that I created the entire first <div class="column ..."> but then I had to use the famous Ctrl + C and Ctrl + V to create the other <div class="column ..."> because I don’t know how to group scripts.

The <select> elements for example is created from script’s. They told me that there is a way to make the 4 scripts (one in each <div class="column ...">) become one using looping, decreasing the loading the page, but I don’t know how to make this improvement.

I was also told about the risk of using so many equal headers, as I use the <script src="https://d3js.org/d3.v4.js"></script> four times but how I need it for the 4 scripts, I don’t know how I could place it only once unless I merge the 4 scripts into one.

References for code citations:

Scripts to <select> creation:

<script id="script-da-caixa-de-selecao-suspensa-1">
<script id="script-da-caixa-de-selecao-suspensa-2">
<script id="script-da-caixa-de-selecao-suspensa-3">
<script id="script-da-caixa-de-selecao-suspensa-4">

Example of the .csv file ("Lista_de_Jogos.csv") that is used to create dropdown selection boxes:

label,value
,
Oriente Petrolero v Aurora,http://sports.williamhill.com/bet/pt/betting/e/21185256/Oriente+Petrolero+v+Aurora.html
Pereira v Alianza Petrolera,http://sports.williamhill.com/bet/pt/betting/e/21150687/Pereira+v+Alianza+Petrolera.html
Tijuana (Women) v Toluca (Women),http://sports.williamhill.com/bet/pt/betting/e/21193317/Tijuana+%28Women%29+v+Toluca+%28Women%29.html
Cruz Azul v Mazatlan,http://sports.williamhill.com/bet/pt/betting/e/21090457/Cruz+Azul+v+Mazatlan.html

Screenshot to drop down box created by <script>:

enter image description here

There are other improvements that can be made to shorten the code and speed up the page, but my knowledge is still very small and I need help both to learn and produce results. Thank you in advance for your attention and help!

My Code:

<html>
    <head>
        <style>
            {
            box-sizing: border-box;
            }
            .column {
            text-align:center;
            float: left;
            width: 355;
            border: 1px solid white;
            border-collapse: collapse;
            }
            .row:after {
            content: "";
            display: table;
            clear: both;
            }
            .button {
            background-color: #33ccff;
            color: black;
            font-weight: bold;
            }
            body {
            overflow: hidden;
            }
        </style>
        <script id="auto-update-images">
            let interval_images
            window.addEventListener('DOMContentLoaded', () => {
                interval_images = setInterval(refresh_images, 500); // refresh every 0.5 secs
            })
            
            function refresh_images() {
                if (!document.images) return;
                document.images('grafico-betfair-1').src = document.getElementById('barra-de-texto-para-grafico-1').value;
                document.images('grafico-betfair-2').src = document.getElementById('barra-de-texto-para-grafico-2').value;
                document.images('grafico-betfair-3').src = document.getElementById('barra-de-texto-para-grafico-3').value;
                document.images('grafico-betfair-4').src = document.getElementById('barra-de-texto-para-grafico-4').value;
            }
        </script>
        <script id="auto-update-csv">
            let interval_csv
            window.addEventListener('DOMContentLoaded', () => {
                interval_csv = setInterval(refresh_csv, 60000); // refresh every 60 secs
            })
            
            function refresh_csv() {
                d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_1(data)});
                d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_2(data)});
                d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_3(data)});
                d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_4(data)});
            }
        </script>
    </head>
    <body style="background-color:black;">
        <div class="row">
            <div class="column left">
                <form action="" method="post" id="formulario-radar-1">
                    <div id="caixa-suspensa-1">
                        <button class="button" id="botao-do-radar-1" onclick="funcao_radar_1()">Radar 1</button>
                        <input type="text" id="barra-de-texto-para-radar-1" style="width: 283px;">
                    </div>
                </form>
                <iframe id="iframe-do-radar-1" width="100%" height="282" frameBorder="0" src="">
                </iframe>
                <script src="https://d3js.org/d3.v4.js"></script>
                <script id="script-da-caixa-de-selecao-suspensa-1">
                    var select_1 = d3.select("#caixa-suspensa-1")
                    .append("select")
                    .attr("id","select-box-1")
                    .style("width","100%");
                    
                    function caixa_suspensa_1(data) {
                    select_1
                        .on("change", function(d) {
                        var value_1 = d3.select(this).property("value");
                        document.querySelector('#barra-de-texto-para-radar-1').value = value_1;
                        document.getElementById('botao-do-radar-1').click();
                        });
                    let update_1 = select_1.selectAll("option")
                        .data(data);
                    update_1.exit().remove();
                    update_1.enter().append("option").merge(update_1)
                        .attr("value", function (d) { return d.value; })
                        .text(function (d) { return d.label; });
                    }
                    d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_1(data)});
                </script>
                <script id="script-para-ativar-iframe-1">
                    function funcao_radar_1() {
                        "use strict";
                        var url_setter = document.getElementById('formulario-radar-1'), url = document.getElementById('barra-de-texto-para-radar-1'), the_iframe = document.getElementById('iframe-do-radar-1');
                        url_setter.onsubmit = function (event) {
                            try {
                                let link = document.getElementById("barra-de-texto-para-radar-1").value;
                                let valor_da_barra_de_texto_1 = link.split("OB_EV")(1);
                                valor_da_barra_de_texto_1 = valor_da_barra_de_texto_1.split("/")(0);
                                    event.preventDefault();
                                    the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_1;
                            } catch (e) {
                                        try {
                                            let link = document.getElementById("barra-de-texto-para-radar-1").value;
                                            let valor_da_barra_de_texto_1 = link.split("betting/e/")(1);
                                            valor_da_barra_de_texto_1 = valor_da_barra_de_texto_1.split("/")(0);
                                                event.preventDefault();
                                                the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_1;
                                        } catch (e) {
                                                    event.preventDefault();
                                                    the_iframe.src = "https://image.flaticon.com/icons/png/128/26/26547.png";
                                        }
                            }
                        };
                    }
                </script>
                <form action="" method="post" id="formulario-grafico-1">
                    <div>
                        <input type="text" id="barra-de-texto-para-grafico-1" style="width: 100%;">
                    </div>
                </form>
                <img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="grafico-betfair-1">
                <form action="" method="post" id="formulario-para-limpar-texto-1">
                    <div>
                        <button class="button" style="width: 100%;" id="botao-de-limpar-texto-1" onclick="limpar_texto_1()">Limpar Tudo <br/>1</button>
                    </div>
                </form>
                <script id="script-para-limpar-dados-1">
                    function limpar_texto_1() {
                        var btn = document.getElementById('formulario-para-limpar-texto-1');
                        btn.onclick = function(e){ 
                            e.preventDefault();
                            document.getElementById('barra-de-texto-para-grafico-1').value="";
                            document.getElementById('barra-de-texto-para-radar-1').value="";
                            document.getElementById('botao-do-radar-1').click();
                            document.getElementById("select-box-1").selectedIndex = "0";
                        };
                    }
                </script>
            </div>
            <div class="column middle1">
                <form action="" method="post" id="formulario-radar-2">
                    <div id="caixa-suspensa-2">
                        <button class="button" id="botao-do-radar-2" onclick="funcao_radar_2()">Radar 2</button>
                        <input type="text" id="barra-de-texto-para-radar-2" style="width: 283px;">
                    </div>
                </form>
                <iframe id="iframe-do-radar-2" width="100%" height="282" frameBorder="0" src="">
                </iframe>
                <script src="https://d3js.org/d3.v4.js"></script>
                <script id="script-da-caixa-de-selecao-suspensa-2">
                    var select_2 = d3.select("#caixa-suspensa-2")
                    .append("select")
                    .attr("id","select-box-2")
                    .style("width","100%");
                    
                    function caixa_suspensa_2(data) {
                    select_2
                        .on("change", function(d) {
                        var value_2 = d3.select(this).property("value");
                        document.querySelector('#barra-de-texto-para-radar-2').value = value_2;
                        document.getElementById('botao-do-radar-2').click();
                        });
                    let update_2 = select_2.selectAll("option")
                        .data(data);
                    update_2.exit().remove();
                    update_2.enter().append("option").merge(update_2)
                        .attr("value", function (d) { return d.value; })
                        .text(function (d) { return d.label; });
                    }
                    d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_2(data)});
                </script>
                <script id="script-para-ativar-iframe-2">
                    function funcao_radar_2() {
                        "use strict";
                        var url_setter = document.getElementById('formulario-radar-2'), url = document.getElementById('barra-de-texto-para-radar-2'), the_iframe = document.getElementById('iframe-do-radar-2');
                        url_setter.onsubmit = function (event) {
                            try {
                                let link = document.getElementById("barra-de-texto-para-radar-2").value;
                                let valor_da_barra_de_texto_2 = link.split("OB_EV")(1);
                                valor_da_barra_de_texto_2 = valor_da_barra_de_texto_2.split("/")(0);
                                    event.preventDefault();
                                    the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_2;
                            } catch (e) {
                                        try {
                                            let link = document.getElementById("barra-de-texto-para-radar-2").value;
                                            let valor_da_barra_de_texto_2 = link.split("betting/e/")(1);
                                            valor_da_barra_de_texto_2 = valor_da_barra_de_texto_2.split("/")(0);
                                                event.preventDefault();
                                                the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_2;
                                        } catch (e) {
                                                    event.preventDefault();
                                                    the_iframe.src = "https://image.flaticon.com/icons/png/128/26/26547.png";
                                        }
                            }
                        };
                    }
                </script>
                <form action="" method="post" id="formulario-grafico-2">
                    <div>
                        <input type="text" id="barra-de-texto-para-grafico-2" style="width: 100%;">
                    </div>
                </form>
                <img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="grafico-betfair-2">
                <form action="" method="post" id="formulario-para-limpar-texto-2">
                    <div>
                        <button class="button" style="width: 100%;" id="botao-de-limpar-texto-2" onclick="limpar_texto_2()">Limpar Tudo <br/>2</button>
                    </div>
                </form>
                <script id="script-para-limpar-dados-2">
                    function limpar_texto_2() {
                        var btn = document.getElementById('formulario-para-limpar-texto-2');
                        btn.onclick = function(e){ 
                            e.preventDefault();
                            document.getElementById('barra-de-texto-para-grafico-2').value="";
                            document.getElementById('barra-de-texto-para-radar-2').value="";
                            document.getElementById('botao-do-radar-2').click();
                            document.getElementById("select-box-2").selectedIndex = "0";
                        };
                    }
                </script>
            </div>
            <div class="column middle2">
                <form action="" method="post" id="formulario-radar-3">
                    <div id="caixa-suspensa-3">
                        <button class="button" id="botao-do-radar-3" onclick="funcao_radar_3()">Radar 3</button>
                        <input type="text" id="barra-de-texto-para-radar-3" style="width: 283px;">
                    </div>
                </form>
                <iframe id="iframe-do-radar-3" width="100%" height="282" frameBorder="0" src="">
                </iframe>
                <script src="https://d3js.org/d3.v4.js"></script>
                <script id="script-da-caixa-de-selecao-suspensa-3">
                    var select_3 = d3.select("#caixa-suspensa-3")
                    .append("select")
                    .attr("id","select-box-3")
                    .style("width","100%");
                    
                    function caixa_suspensa_3(data) {
                    select_3
                        .on("change", function(d) {
                        var value_3 = d3.select(this).property("value");
                        document.querySelector('#barra-de-texto-para-radar-3').value = value_3;
                        document.getElementById('botao-do-radar-3').click();
                        });
                    let update_3 = select_3.selectAll("option")
                        .data(data);
                    update_3.exit().remove();
                    update_3.enter().append("option").merge(update_3)
                        .attr("value", function (d) { return d.value; })
                        .text(function (d) { return d.label; });
                    }
                    d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_3(data)});
                </script>
                <script id="script-para-ativar-iframe-3">
                    function funcao_radar_3() {
                        "use strict";
                        var url_setter = document.getElementById('formulario-radar-3'), url = document.getElementById('barra-de-texto-para-radar-3'), the_iframe = document.getElementById('iframe-do-radar-3');
                        url_setter.onsubmit = function (event) {
                            try {
                                let link = document.getElementById("barra-de-texto-para-radar-3").value;
                                let valor_da_barra_de_texto_3 = link.split("OB_EV")(1);
                                valor_da_barra_de_texto_3 = valor_da_barra_de_texto_3.split("/")(0);
                                    event.preventDefault();
                                    the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_3;
                            } catch (e) {
                                        try {
                                            let link = document.getElementById("barra-de-texto-para-radar-3").value;
                                            let valor_da_barra_de_texto_3 = link.split("betting/e/")(1);
                                            valor_da_barra_de_texto_3 = valor_da_barra_de_texto_3.split("/")(0);
                                                event.preventDefault();
                                                the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_3;
                                        } catch (e) {
                                                    event.preventDefault();
                                                    the_iframe.src = "https://image.flaticon.com/icons/png/128/26/26547.png";
                                        }
                            }
                        };
                    }
                </script>
                <form action="" method="post" id="formulario-grafico-3">
                    <div>
                        <input type="text" id="barra-de-texto-para-grafico-3" style="width: 100%;">
                    </div>
                </form>
                <img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="grafico-betfair-3">
                <form action="" method="post" id="formulario-para-limpar-texto-3">
                    <div>
                        <button class="button" style="width: 100%;" id="botao-de-limpar-texto-3" onclick="limpar_texto_3()">Limpar Tudo <br/>3</button>
                    </div>
                </form>
                <script id="script-para-limpar-dados-3">
                    function limpar_texto_3() {
                        var btn = document.getElementById('formulario-para-limpar-texto-3');
                        btn.onclick = function(e){ 
                            e.preventDefault();
                            document.getElementById('barra-de-texto-para-grafico-3').value="";
                            document.getElementById('barra-de-texto-para-radar-3').value="";
                            document.getElementById('botao-do-radar-3').click();
                            document.getElementById("select-box-3").selectedIndex = "0";
                        };
                    }
                </script>
            </div>
            <div class="column right">
                <form action="" method="post" id="formulario-radar-4">
                    <div id="caixa-suspensa-4">
                        <button class="button" id="botao-do-radar-4" onclick="funcao_radar_4()">Radar 4</button>
                        <input type="text" id="barra-de-texto-para-radar-4" style="width: 283px;">
                    </div>
                </form>
                <iframe id="iframe-do-radar-4" width="100%" height="282" frameBorder="0" src="">
                </iframe>
                <script src="https://d3js.org/d3.v4.js"></script>
                <script id="script-da-caixa-de-selecao-suspensa-4">
                    var select_4 = d3.select("#caixa-suspensa-4")
                    .append("select")
                    .attr("id","select-box-4")
                    .style("width","100%");
                    
                    function caixa_suspensa_4(data) {
                    select_4
                        .on("change", function(d) {
                        var value_4 = d3.select(this).property("value");
                        document.querySelector('#barra-de-texto-para-radar-4').value = value_4;
                        document.getElementById('botao-do-radar-4').click();
                        });
                    let update_4 = select_4.selectAll("option")
                        .data(data);
                    update_4.exit().remove();
                    update_4.enter().append("option").merge(update_4)
                        .attr("value", function (d) { return d.value; })
                        .text(function (d) { return d.label; });
                    }
                    d3.csv("Lista_de_Jogos.csv", function(data){caixa_suspensa_4(data)});
                </script>
                <script id="script-para-ativar-iframe-4">
                    function funcao_radar_4() {
                        "use strict";
                        var url_setter = document.getElementById('formulario-radar-4'), url = document.getElementById('barra-de-texto-para-radar-4'), the_iframe = document.getElementById('iframe-do-radar-4');
                        url_setter.onsubmit = function (event) {
                            try {
                                let link = document.getElementById("barra-de-texto-para-radar-4").value;
                                let valor_da_barra_de_texto_4 = link.split("OB_EV")(1);
                                valor_da_barra_de_texto_4 = valor_da_barra_de_texto_4.split("/")(0);
                                    event.preventDefault();
                                    the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_4;
                            } catch (e) {
                                        try {
                                            let link = document.getElementById("barra-de-texto-para-radar-4").value;
                                            let valor_da_barra_de_texto_4 = link.split("betting/e/")(1);
                                            valor_da_barra_de_texto_4 = valor_da_barra_de_texto_4.split("/")(0);
                                                event.preventDefault();
                                                the_iframe.src = "https://sports.staticcache.org/scoreboards/scoreboards-football/index.html?eventId=" + valor_da_barra_de_texto_4;
                                        } catch (e) {
                                                    event.preventDefault();
                                                    the_iframe.src = "https://image.flaticon.com/icons/png/128/26/26547.png";
                                        }
                            }
                        };
                    }
                </script>
                <form action="" method="post" id="formulario-grafico-4">
                    <div>
                        <input type="text" id="barra-de-texto-para-grafico-4" style="width: 100%;">
                    </div>
                </form>
                <img src="https://sitedeapostas-com.imgix.net/assets/local/Company/logos/betfair_logo_transp.png?auto=compress%2Cformat&fit=clip&q=75&w=263&s=c1691b4034fd0c4526d27ffe8b1e839c" name="grafico-betfair-4">
                <form action="" method="post" id="formulario-para-limpar-texto-4">
                    <div>
                        <button class="button" style="width: 100%;" id="botao-de-limpar-texto-4" onclick="limpar_texto_4()">Limpar Tudo <br/>4</button>
                    </div>
                </form>
                <script id="script-para-limpar-dados-4">
                    function limpar_texto_4() {
                        var btn = document.getElementById('formulario-para-limpar-texto-4');
                        btn.onclick = function(e){ 
                            e.preventDefault();
                            document.getElementById('barra-de-texto-para-grafico-4').value="";
                            document.getElementById('barra-de-texto-para-radar-4').value="";
                            document.getElementById('botao-do-radar-4').click();
                            document.getElementById("select-box-4").selectedIndex = "0";
                        };
                    }
                </script>
            </div>
        </div>
    </body>
</html>

javascript – Problemas con Chart.js

Estoy realizando unas gráficas y tengo un pequeño problema que no soy capaz de solucionar.
Este es el resultado de la gráfica que tengo que lograr, mi problema es, como conseguir poner texto en medio de la gráfica.

introducir la descripción de la imagen aquí

Este es mi código HTML.

<canvas id="grafica1"></canvas>

Y el código Js

   ctx = document.getElementById('grafica1').getContext("2d");

    gradientStroke = ctx.createLinearGradient(500, 0, 100, 0);
    gradientStroke.addColorStop(0, '#80b6f4');
    gradientStroke.addColorStop(1, chartColor);

    gradientFill = ctx.createLinearGradient(0, 170, 0, 50);
    gradientFill.addColorStop(0, "rgba(128, 182, 244, 0)");
    gradientFill.addColorStop(1, "rgba(249, 99, 59, 0.40)");
    
    
    myChart = new Chart(ctx, {
      type: 'line',
      responsive: true,
      data: {
        labels: ('ene', '2','3','4','5','6'),
        datasets: ({
          label: "",
          borderColor: "#f96332",
          pointBorderColor: "#FFF",
          pointBackgroundColor: "#f96332",
          pointBorderWidth: 1,
          pointHoverRadius: 1,
          pointHoverBorderWidth: 1,
          pointRadius: 1,
          fill: true,
          backgroundColor: gradientFill,
          borderWidth: 2,
          data: (0,3,3,5,2,3),
          tension: 0.2
        })
      },
      options: {
      maintainAspectRatio: false,
      plugins: {
        legend: {
          display: false
        },
        tooltip: { 
          enabled: false
        } 
      },
      responsive: true,
      scales: {
        y: {
          display: false, //quita las lineas del eje y
          ticks: {
            display: false //quita el texto del eje y
          }
        },
        x: {
          display: false, //quita las lineas del eje x
          ticks: {
            display: false //quita el texto del eje x
          }
        }
      }
    }
    });

He probado de diferentes formas, haciendo:

var c = document.getElementById("grafica1");
var ctx = c.getContext("2d");
ctx.textAlign = "center";
ctx.fillText("textAlign=center",c.width/2, c.height/2);

Esto si me da el resultado que quiero, pone el texto en su lugar, el problema es, que cuando paso el cursor del ratón por encima de las gráficas, exactamente en los puntos, esto desaparece.

Estoy utilizando Chart.js v3.3.2

Gracias!

javascript – No entiendo el funcionamiento de google places

Estoy haciendo unas pruebas y quise probar google places para obtener cordenadas, según google: 1.000 solicitudes son 7 USD pensé que sería una conversión a mil usuarios, pero cuando ya había creado todo y ver el resultado, solo dos busquedas que realicé generaron 93 solicitudes ¿?

Es decir que solo un usuario o la misma competencia de aposta me puede poner a pagar 7 USD por usar la app mía de busquedas de direcciones? no sé si escribí mal el código y está generando algún problema, o entiendo mal el funcionamiento de places y se cobra de otra manera o las solicitudes si se cuentan por el total de resultados arrojados en ese momento, de ser así, no tiene sentido ya que es perdida de dinero.

Aquí el código:

var autocomplete;
    autocomplete = new google.maps.places.Autocomplete((document.getElementById(searchInput)), {
        types: ('geocode')
    });

    google.maps.event.addListener(autocomplete, 'place_changed', function() {

        var near_place = autocomplete.getPlace();

        document.getElementById('latitude').innerText = near_place.geometry.location.lat();

        document.getElementById('longitude').innerText = near_place.geometry.location.lng();

    });

introducir la descripción de la imagen aquí

DreamProxies - Cheapest USA Elite Private Proxies 100 Cheap USA Private Proxies Buy 200 Cheap USA Private Proxies 400 Best Private Proxies Cheap 1000 USA Private Proxies 2000 USA Private Proxies 5000 Cheap USA Private Proxies ExtraProxies.com - Buy Cheap Private Proxies Buy 50 Private Proxies Buy 100 Private Proxies Buy 200 Private Proxies Buy 500 Private Proxies Buy 1000 Private Proxies Buy 2000 Private Proxies ProxiesLive.com Proxies-free.com New Proxy Lists Every Day Proxies123.com Best Quality USA Private Proxies