Cannot send query to AWS RDS trought Express Nodejs

I have free AWS RDS database and I’m trying to configure it with my Node Express server.

Database is creating connection with server but when I try to send some Query it says:

code: ‘ER_NO_DB_ERROR’,
errno: 1046,
sqlMessage: ‘No database selected’,

My code:

const express = require("express");
const mysql = require("mysql");

// Creating Database Connection
const db = mysql.createConnection({
    host:"(WILL NOT SHARE)",
    port:"3306",
    user:"(WILL NOT SHARE)",
    password:"(WILL NOT SHARE)",
    database: ""
})
db.connect(err=>{
    if(err){
        console.log(err.message);
        return;
    }
    console.log("Database connected.");
});//



const app = express();

app.get('/register', (req, res) => {
    let sql = "INSERT INTO users (first_name, last_name, email, password) VALUES ('Peter', 'Green', '[email protected]', '123')";
    let query = db.query(sql);
});

app.listen('3000', () => {
    console.log('Listening on port 3000...');
});

I keep ‘database:’ empty, because I dont have db name in AWS RDS:
Screenshot of empty db name

Full terminal

PS: if I write to ‘database:’ my DB identifier it says: ER_BAD_DB_ERROR: Unknown database ‘db-identifier’

How do I change my jQuery to run on page load instead of event change

I am having difficulty running my jQuery code on page load. I do not know enough about jQuery to find the right option.

The code below works fine for a ‘change’ event, however I want the code to run at the time of loading and use the default values of the input fields to show the relevant divs.

I have tried changing the first line of the jQuery to the following options with no success:

jQuery(document).ready('onload', e => {
window.addEventListener('load', e => {
document.addEventListener('DOMContentLoaded', e => {

Here is a fiddle to play with: JSFIDDLE >

jQuery:

document.addEventListener('change', e => {
  if (e.target.name == 'numberofdaysperchosenfrequency') {
    let parent = e.target.parentNode;
        parent.querySelectorAll('#daycol').forEach(n => n.style.display = 'none');
        
    if (e.target.value) parent.querySelector(`[data-id="${e.target.value}"]`).style.display = 'block';
  }
})

HTML:

<strong>SET 01</strong><br>
<section>
<label>Days (enter value 1 to 6): </label>
<input type="text" name="numberofdaysperchosenfrequency" value="1">
<div data-id="1" id="daycol" name="day1col" class="hide">Day 1</div>
<div data-id="2" id="daycol" name="day2col" class="hide">Day 1 / Day 2</div>
<div data-id="3" id="daycol" name="day3col" class="hide">Day 1 / Day 2 / Day 3</div>
<div data-id="4" id="daycol" name="day4col" class="hide">Day 1 / Day 2 / Day 3 / Day 4</div>
<div data-id="5" id="daycol" name="day5col" class="hide">Day 1 / Day 2 / Day 3 / Day 4 / Day 5</div>
<div data-id="6" id="daycol" name="day6col" class="hide">Day 1 / Day 2 / Day 3 / Day 4 / Day 5 / Day 6</div>
</section>

<br><hr><br>

<strong>SET 02</strong><br>
<section>
<label>Days (enter value 1 to 6): </label>
<input type="text" name="numberofdaysperchosenfrequency" value="6">
<div data-id="1" id="daycol" name="day1col" class="hide">Day 1</div>
<div data-id="2" id="daycol" name="day2col" class="hide">Day 1 / Day 2</div>
<div data-id="3" id="daycol" name="day3col" class="hide">Day 1 / Day 2 / Day 3</div>
<div data-id="4" id="daycol" name="day4col" class="hide">Day 1 / Day 2 / Day 3 / Day 4</div>
<div data-id="5" id="daycol" name="day5col" class="hide">Day 1 / Day 2 / Day 3 / Day 4 / Day 5</div>
<div data-id="6" id="daycol" name="day6col" class="hide">Day 1 / Day 2 / Day 3 / Day 4 / Day 5 / Day 6</div>
</section>

Local server on node js works incorrect

Well, lately I was practicing with streams and http module of node. I was testing my server by postman and also testing by fetch method from browser. Over and over I got incorrect work by server.

That is my code:

const http = require('http');
const fs = require('fs');

const server = new http.Server();

server.on('request', (req, res) => {
  if (req.method === 'POST') {
    const writeStream = fs.createWriteStream(`${__dirname}/text.txt`, { flags: 'wx' });

    req.pipe(writeStream);

    req.on('close', () => {
      console.log('writeStream:', writeStream.destroyed);
    });

    writeStream.on('error', (err) => {
      if (err.code === 'EEXIST') {
        res.statusCode = 409;
        res.end('File is already exist');
        return;
      }
    });
    writeStream.on('finish', () => {
      res.statusCode = 201;
      res.end('Created and written');
    });
    return;
  }
  req.on('close', () => {
    console.log('other close');
  });
  res.statusCode = 501;
  res.end('Not implemented');
});

server.listen(5001, () => console.log('Server is running on 5001 port'));

Ok, when request completes with status code 201, I get event close on req stream. And it is correct. But if request gets an error event you won’t see event close never. One more strange case, look at res.statusCode = 501 and event handler close for req, this event will work only one time, but if you will try to invoke 501 again, you won’t see invocation of close on req

When I testing this code on codesandbox I don’t see these strange behaviours.

What do you think, what is going on?

P.S Node v16.17.0

i can’t execute bootstrap files on localhost xampp

i have downloaded this project from github: https://github.com/DrA1ex/fourier

I am using XAMPP, localhost.

i am new to github, so i wish for detailed help on this one.

i have cloned the project into my htdocs folder, when i try to connect to it won’t work.

When i click on the index.html file located in the src folder, it leads to a blank page.

The project is using bootstrap and i don’t know how to make it work.

Is there any more info needed, to solve this, please let me know.

Best regards

How to change the values of inputs when click?

I want to change the input values according to chosen options. the console.log in the code shows the true values every time I click a different parts but in the input, it shows the first clicking values and it doesn’t change.
How can I fix it?

<div className="detailsPage-panel-right">
                  {
                    this.state.activeFields?.map(field => {
                      const config = this.config.fields.find(fieldConfig =>
                        fieldConfig.key === field.key)
                      const inputConfig = {
                        type: config?.dataType.type,
                        id: config?.key,
                        label: config?.displayName,
                        required: false,
                        autofocus: false,
                        value: field.value
                      };
                      console.log(field.value)
                      const inputBindings: ITextInputBindings = {}
                      return (
                        <div key={field.key}>
                          <TextInput config={inputConfig} bindings={inputBindings}></TextInput>
                        </div>
                      )
                    })
                  }
                </div>

Hwo to debug/console.log in puppeteer

I have these lines of code which I execute with yarn test

import puppeteer from "puppeteer";

describe("App.js", () => {
  let browser;
  let page;

  beforeAll(async () => {
    browser = await puppeteer.launch();
    page = await browser.newPage();
  });

  it("basic functionality", async () => {
    await page.goto("http://localhost:3000");
    setTimeout(async () => {
      const autocomplete = page.$("#foo");
      const input = page.within(autocomplete).getByRole("combox");
      console.log("#######") // does not log anything
      startingAirport.focus();
      page.fireEvent.change(input, { target: { value: "Kitten" } });
      page.fireEvent.keyDown(autocomplete, { key: "ArrowDown" });
      page.keyDown(autocomplete, { key: "Enter" });
      expect(input).toHaveValue("Kitten");
    }, 2000);
  });

  afterAll(() => browser.close());
});

How am I able to debug puppeteer when I cannot console.log() something to the terminal?

Vue. How to pass dynamic modificator in vuejs custom directive

<Button 
  ...
  v-tooltip.bottom="{ value: tooltip, disabled: !tooltip }"
/>

How can I change “bottom” dynamicaly?
I have several modifiers: top, left, bottom, right. In a different situation, it is necessary to create a component with only one other specific modifier. Sculpting the rendering condition depending on the modifier seems not to be the optimal solution.

do you guys know how I can make the timer change every 6 hours, like at 00:00, 06:00, 12:00, and 18:00 in Javascript?

Here I am trying to make a timer that will reset every 6 hours local time. at 00:00, 06:00, 12:00, 18:00.
but I think I miss something to make it work. so this is my logic, please CMIIW.

  • Create the current date and time

  • make a variable for each 6 hours

  • if statement, if the condition is met it will get reset from the start

    Order within the next

//script for the Js logic

// it will repeat again for tomorrow


const today = new Date()
const tomorrow = new Date(today)
tomorrow.setDate(tomorrow.getDate() + 1)
tomorrow.setHours(00)


var myfunc = setInterval(function() {

var now = new Date().getTime();
var timeleft = tomorrow - now;

var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
var hours = Math.floor((timeleft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((timeleft % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((timeleft % (1000 * 60)) / 1000);


document.getElementById("hours").innerHTML = hours + " Hours " 
document.getElementById("mins").innerHTML = minutes + " Minutes " 
document.getElementById("secs").innerHTML = seconds + " Second"
  
if (timeleft < 0) {
        clearInterval(myfunc);
        document.getElementById("days").innerHTML = ""
        document.getElementById("hours").innerHTML = "" 
        document.getElementById("mins").innerHTML = ""
        document.getElementById("secs").innerHTML = ""
        document.getElementById("end").innerHTML = "TIME UP!!";
    }
  
 }, 1000);

// After 6 Hours it will reset again

</script>

How to keep the position of the tag proportional to page width change? When map is scaled, tag retains its position relative to its province

There is a map made using HTML Canvas. There is a tag with the name of the region located using position:absolute.

In the original example, when the page is resized, changes its top* and right position using some script, adjusting to the changed position of the region (as if retaining its position in relation to it).

How can I do that ? Where can I get the initial data to calculate the position that needs to be set for the tag when resizing?

Also in the source there is a canvas element circle which is located where you want to set the appropriate with the name of the region. Perhaps the coordinates for the are taken somehow through it. Can you tell me how this can be done?

Example

enter image description here

Working example on site

https://uk-keepexploring.canada.travel/#wheretogo

Codpen
https://codepen.io/RJDio/pen/NWYRzVj

  <div class="section-map>
       <div class="svgfix__container">

           <canvas class="svgfix__canvas" width="500" height="488"> </canvas>
           <svg id="MAP" data-name="MAP" data-province="MAP" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1100 1072.93">

             <g id="Canada" data-name="Canada">
               <path id="CA-AB" data-name="alberta" d="M747.45,861.7c-33.6-8.9-30-7...." transform="translate(-296.8 -221.07)"></path>
                     ....
              //Map of canada made by canvas
             </g>

             //City/region label made on canvas.

             <g id="City_Labels_Canada" data-name="City Labels Canada">
               <g id="iqaluit" data-name="Iqaluit" data-province="nunavut" class="city nohover">
                 <circle cx="839.32" cy="390.34" r="3.1"></circle>
                 <text x="847" y="394" data-name="Iqaluit" class="en de fr es">Iqaluit</text>
               </g>
               ...
             </g>

       //City/region label.
      <span class="map__labelt" data-name="iqaluit" data-province="nunavut" style="left: 669.796px; right: auto; top: 308.56px;">Iqaluit</span>
  </div>

How to Set Page Pagination Using Ajax JQuery – WordPress

I have pagination using ajax JQuery. And the web I’m using is WordPress.

The pagination is working, but what I want is, when user click the pagination, the page is set up.

I think giving example, will be way more understandable.

For example, I have url:

http://localhost/edupac-id/university/

the page have pagination ajax.
So, when user click the pagination, the url changed to like this:

http://localhost/edupac-id/university/?page=2

But when I enter this url in browser search bar:

http://localhost/edupac-id/university/?page=2

the url come back into this url:

http://localhost/edupac-id/university/

All I want is, when I enter the: http://localhost/edupac-id/university/?page=2 in browser search bar, the result list still the page 2, not go back again (reset).

Here is my display-university.php file:

<?php


class edu003_displayUniversityCPT{

    
    static function displayAllUniversity(){
        global $wpdb;

        $page = (isset($_POST['page'])) ? $_POST['page'] : 1;
        $limit = 5;
        $limit_start = ($page - 1) * $limit;
    
        $table_name = $wpdb->prefix . 'posts';
        $allUniversity = new WP_QUERY(array(
            'post_type' => 'university',
            'post_status' => 'publish',
            'orderby' => 'post_date',
            'order' => 'ASC',
            'posts_per_page' => $limit,
            'offset' => $limit_start
        ));

        $total_records = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) FROM $table_name WHERE post_type = 'university' AND post_status = 'publish'", array() ));

        if($allUniversity->have_posts()){
            ?>
                <table class="u-table">
                    <thead>
                        <tr>
                            <th style="width: 50%">
                                <h2><strong>Nama Universitas</strong></h2>
                            </th>
                            <th>
                                <h2><strong>Lokasi Universitas</strong></h2>
                            </th>
                            <th>
                                <h2><strong>Jurusan Tersedia</strong></h2>
                            </th>
                    
                        </tr>
                    </thead>
                    <?php
                    while($allUniversity->have_posts()){
                        $allUniversity->the_post();
                        ?>
                        <tbody>
                            <tr>
                                <td data-label="Nama Universitas">
                                    <?php 
                                        $university_logo = get_field('university_logo');
                                        $size = 'medium';
                                        if( ! empty ( $university_logo ) ) {
                                            echo wp_get_attachment_image($university_logo, $size, "", array( "class" => "img-responsive" ));
                                        }
                                    ?>
                                    <p style="font-size: x-large;"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3></p>
                                    <details>
                                        <summary>lihat detail &raquo;</summary>
                                        <p><?php echo wp_trim_words(get_the_content(), 15); ?><a href="<?php the_permalink(); ?>"> Baca Selengkapnya &raquo;</a></p>
                                    </details>
                                </td>
                                <td data-label="Lokasi Universitas">
                                    <?php
                                        $university_locations = get_field('university_location');

                                        if(count((array)$university_locations) > 1){
                                            foreach($university_locations as $university_location){
                                                ?>
                                                <ul>
                                                    <li><a href="<?php echo site_url('kuliah-di-' . strtolower($university_location)); ?>"><?php echo $university_location; ?></a></li>
                                                </ul>
                                                <?php
                                            }
                                        }
                                        else{
                                            ?>
                                            <p><a href="<?php echo site_url('kuliah-di-' . strtolower(implode("", $university_locations))); ?>"><?php echo implode("", $university_locations) ?></a></p>
                                            <?php 
                                        }
                                    ?>
                                </td>
                                <td data-label="Jurusan Tersedia">
                                    <?php if(count((array) get_field('university_majors')) > 0): ?>
                                        <p><a href="<?php the_permalink(); ?>"><?php echo count(get_field('university_majors')); ?> Jurusan</a></p>
                                    <?php else: ?>
                                        <p><a href="<?php the_permalink(); ?>">0 Jurusan</a></p>
                                    <?php endif; ?>
                                </td>
                            </tr>
                                                
                        </tbody>
                        <?php 
                    }
                    ?>
                </table>

                <p>Total baris : <?php echo $total_records; ?></p>

                <nav class="mb-5">
                    <ul class="pagination justify-content-end">

                    <?php 
                        $jumlah_page = ceil($total_records / $limit);
                        $jumlah_number = 1;
                        $start_number = ($page > $jumlah_number)? $page - $jumlah_number : 1;
                        $end_number = ($page < ($jumlah_page - $jumlah_number))? $page + $jumlah_number : $jumlah_page;
                        if($page == 1){
                            echo '<li class="page-item disabled"><a class="page-link">First</a></li>';
                            echo '<li class="page-item disabled"><a class="page-link"><span aria-hidden="true">&laquo;</span></a></li>';
                        } else {
                        $link_prev = ($page > 1)? $page - 1 : 1;
                            echo '<li class="page-item halaman" id="1"><a class="page-link">First</a></li>';
                            echo '<li class="page-item halaman" id="'.$link_prev.'"><a class="page-link"><span aria-hidden="true">&laquo;</span></a></li>';
                        }
                        for($i = $start_number; $i <= $end_number; $i++){
                            $link_active = ($page == $i)? ' active' : '';
                            echo '<li class="page-item halaman'.$link_active.'" id="'.$i.'"><a class="page-link" href="' . get_site_url() . '/university/?page='.$i.'">'.$i.'</a></li>';
                        }
                        if($page == $jumlah_page){
                            echo '<li class="page-item disabled"><a class="page-link"><span aria-hidden="true">&raquo;</span></a></li>';
                            echo '<li class="page-item disabled"><a class="page-link">Last</a></li>';
                        } else {
                        $link_next = ($page < $jumlah_page)? $page + 1 : $jumlah_page;
                            echo '<li class="page-item halaman" id="'.$link_next.'"><a class="page-link"><span aria-hidden="true">&raquo;</span></a></li>';
                            echo '<li class="page-item halaman" id="'.$jumlah_page.'"><a class="page-link">Last</a></li>';
                        }

                        ?>

                    </ul>
                </nav>
            <?php
            wp_reset_postdata();
            
        }
       
    }

}

?> 

and here is my ajax-pagination.js file:

import $ from "jquery";

class edu003_ajaxPagination{
    constructor(){
        this.events();
    }

    events(){
        $(document).on('click', '.halaman', function(e){
            e.preventDefault();
            var page = $(this).attr("id");
            $.ajax({
                url: pluginData.ajax_url,
                type: 'POST',
                data:{
                  'action': 'displayAllUniversity',
                  'page': page
                },
                success: function(response) {
                    history.pushState(page, '', '?page='+page);
                    $('html, body').animate({ scrollTop: $('.entry-content').offset().top-70 }, 'fast');
                    response = response.trim();
                    response = response.slice(0, -1);
                    $('.entry-content').empty().html(response);

                }
           })
       
        });

    }


}

export default edu003_ajaxPagination;

Thank you in advance, developers.

Strange behaviour with function in object

I don’t know why but when I delete “name: element.name” in this snippet, element go to undefined, do you have any idea why ?

DisplayMessage

const displayMessage = (allMessages) => {
    for([key, element] of Object.entries(allMessages)){
        if(key != "status") 
        {   
            messageQueue[key] = { name: element.name, message: element.message}
            messageQueue[key].add = () => addMessageInBox('start', element.name, element.message)
            
            if(key > lastKey) lastKey = key
           
        }
    }
    
}

ShowMessages function is launched every 4 seconds

ShowMessages

const showMessages = () => {
    if(Object.keys(messageQueue).length > 0) {
        for([key, element] of Object.entries(messageQueue)){
            if (typeof element.add == "function") element.add()
        }

    }
    messageQueue = {}
}

My theory is a denied access to the reference if it is not passed before

d3.js ticks for axis displayed wrong

I have a problem regarding ticks for the axis label using d3.js

This is my code:

const svg = d3.select('svg').attr('width', 1000).attr('height', 600);
const layer = svg.append('g').attr('transform', `translate(30, 30)`);
const scale = d3.scaleLinear().range([0, 750]).domain([0, 350]);
const axis = d3.axisTop(scale).ticks(14);
layer.call(axis);

So what i want to do is, have 14 labels regarding the data. So by dividing 350/14 a step should be of size 25.

If you take a look at the result, the ticks are rounded somehow to 20, which I do not know why.

Does anyone know what d3 is doing here? What am I doing wrong?

Thanks in advance!

Output