Using normal classes with vue composition api

how can I use framework-independent JavaScript class instances with reactive state on vue-composition-api.

Given following class:

// CounterService / counter-service.ts
//
// this is a normal javascript class which is independent of vue
export const counterService = new (class CounterService {
  private count: number = 0;

  // should cause all components that use `getCount` to react.
  addOne(): void {
    this.count++;
  }

  // should be reactive
  getCount(): number {
    return this.count;
  }
})()

Kind regards
Rozbeh Chiryai Sharahi

Generate a row with empty cells and a filled select

I need to generate in JavaScript a new row on a table but with empty cell without a select who need to be the same as the other row and i want the function to work no matter where is the input in the row
here’s my function to add empty row and cells

// Insert new row in the table when clicking on the + button
// tableid: Id of the element to update
function AddRows(tableid){
    var table = document.getElementById(tableid);
    var rowCount = table.rows.length;
    var cellCount = table.rows[0].cells.length;
    var row = table.insertRow(rowCount);
     var editContent = !row.isContentEditable;
        row.contentEditable = editContent;
    row.setAttribute('onkeyup', "Disabled();");
    row.setAttribute('onclick', "SetSelectedRow(this)");
    row.setAttribute('id', 'Combo_row'+(row.rowIndex - 1)); //Set the id of the row
    row.setAttribute('class', 'default');


    for(var i =0; i < cellCount; i++){
        var cell = 'cell'+i;
        cell = row.insertCell(i);
        cell.id = 'Combo_cell' + i
    }

}

I also found this function but she copy the rows and keep the content of every cells not only the select

/* function to add row with a select */
    function addSelect(SelectTableId) {
  var T = document.getElementById(SelectTableId);

  var R = document.querySelectorAll('tbody .AddRowClass')[0];

  var C = R.cloneNode(true);

  T.appendChild(C);

    }

Mobile Safari shows keyboard after page is reloaded

I am struggling with the mobile Safari browser. I am showing a page with a search form via Next.js. When I click into input keyboard shows. When the form is submitted I prevent native submit event. Instead of the native event, I have my own function where I grab all existing query parameters and add new query parameter parsed from the input.

Then I reload the page with router.push function. After the page is reloaded input has still its focus so Safari shows the keyboard.

I tried calling blur on input but when input is blurred then it is immediately called focus event by the browser. This implies showing the keyboard.

Thanks in advance for any answer.

Update React MobX store not more often than 1 second

Our frontend React application gets multiple updates per second via web sockets that we then update the MobX store with. This causes multiple component’s rerenders and whole application to perform very poor.

What would be the most elegant solution we can develop in order to make it perform better? Is it somehow possible to gather all the data we collect within one second in some kind of temporary place and then after one second update store with it? Or is there any other better solution that can prevent multiple rerenders?

Function empty object check

I need help this task
You have to implement function that will
Check that object is empty.
Object considered to be empty when it has no properties or all its properties are false (I.e. 0, “”, false …)

Validation form does not work and has a strange behavior

I’m learning to use forms and I have a javascript code that when I click submit the page shows an error but it does it in a microsecond so I cannot read it and the page refresh it self, I have no idea about what is wrong here.
Here is my html

    <body>
    <h3>Formulario</h3>
    <form name="formName" action="#" onsubmit="return validaciones()">       
    <h4>Nombre:</h4>
    <input type="text" onkeypress="validateName(this)" name="campoNombre">
    <br>
    <br>
    <select id="opciones" name="opciones">
    <br>
    <br>
      <option value="1">Primer valor</option>
      <option value="2">Segundo valor</option>
      <option value="3">Tercer valor</option> 
      <option value="4">Cuarto valor</option>
    </select>
    <br>
    <br>
    <input type="radio" value="si" name="pregunta" id="pregunta_si"/> SI 
    <input type="radio" value="no" name="pregunta" id="pregunta_no"/> NO
    <input type="radio" value="nsnc" name="pregunta" id="pregunta_nsnc"/> NS/NC
    <br>
    <br>
    <input type="checkbox" value="condiciones" name="condiciones" id="condiciones"/> He leído 
     y acepto las condiciones
    <input type="checkbox" value="privacidad" name="privacidad" id="privacidad"/> He leído la 
    política de privacidad
    <br>
    <br>
    <textarea id="parrafo"></textarea>
    <br>
    <br>
    <input type="submit" value="submit">
    </form>

Javascript code

    function validaciones() {
      let valorNombre = document.forms["formName"]["campoNombre"].value;
      if (valorNombre == "") {
      alert("Name must be filled out");
      console.log('Ingresaste tu nombre: ' + valorNombre)
      }

      var elementos = document.getElementsByName("pregunta");
      for(var i=0; i<elementos.length; i++) {
      console.log(" Elemento: " + elementos[i].value + "n Seleccionado: " + 
      elementos[i].checked)
      }
      return false
      };    

      function validateName(item){
      value = item.value;
      console.log(value)
      };

How to return the difference between two Objects having array and return the difference value dynamically

Let’s say I have two objects of arrays:

const newObj = {
      description: "abcd",
      type: "anything",
      list: [
        { id: 1, name: "Peter" },
        { id: 2, name: "Cathenna" },
        { id: 3, name: "Chiyo" }
      ]
    }

   const oldObj = {
      description: "wwew",
      type: "anything",
      list: [
        { id: 1, name: "Amara" },
        { id: 2, name: "shinzo" },
        { id: 3, name: "Chiyo" }
      ]
    }

I want to find all the updated data in newObj objects. Ex, description of oldObj is updated to “abcd” in newObj and in list name of two objects has been updated. So, my expected output is:

const extractObjDiff = {
      description: "abcd",
      list: [
        { id: 1, name: "Peter" },
        { id: 2, name: "Cathenna" }
      ]
    }

I have tried below code but it’s not working for array list.

function extractObjDiff(newObj, oldObj) {
  var r = {};
  for (var prop in newObj) {
    if (!oldObj.hasOwnProperty(prop)) {
      if (Array.isArray(newObj)) {
        r = newObj;
      } else {
        r[prop] = newObj[prop];
      }
    } else if (newObj[prop] === Object(newObj[prop])) {
      var difference = newObj[prop].length !== oldObj[prop].length ? newObj[prop] : extractObjDiff(newObj[prop], oldObj[prop], []);
      if (Object.keys(difference).length > 0) r[prop] = difference;
    } else if (newObj[prop] !== oldObj[prop]) {
      if (newObj[prop] === undefined)
        r[prop] = 'undefined';
      if (newObj[prop] === null)
        r[prop] = null;
      else if (typeof newObj[prop] === 'function')
        r[prop] = 'function';
      else if (typeof newObj[prop] === 'object')
        r[prop] = 'object'
      else if (Array.isArray(newObj))
        r = newObj;
      else
        r[prop] = newObj[prop];
    }
  }
  return r;
}

How to create an image file from Firebird blob data?

I have a Firebird DB table, which contains fields with image data (as blob sybtype -5). I need to get this data and convert it to an image file. Code example below creates a file (but size is very large, and while trying to open it – it is said, that file is not right BMP file). What am I missing here?

result[0].OBJ_IMAGE1((err, name, eventEmitter) => {
    if(err) throw err;

    let chunks = [];
    eventEmitter.on('data', chunk => {
        chunks.push(chunk);                
    });
    eventEmitter.once('end', () => {
        let buffer = Buffer.concat(chunks);         

        fs.writeFile('test.png',  buffer, err => {
            if(err) throw err;
            console.log('image file written');
        });            
    });
});

enter image description here

How do I catch ENOTFOUND/getaddrinfo (non-existent host) Error in Node.js Net?

I am writing a small status query library for Minecraft servers using a Net socket on nodejs.

According to the JSDoc and Node documentation, the error listener (socket.on('error', () => ...) should catch errors thrown and it does catch other errors such as when the server unexpectedly closes the connection. However I can not seem to catch host resolve errors which I have to.

client.connect(host.port, host.host, () => {
    //sending some
});

client.on('data', (chunk) => {
    //receiving some chunks
});

client.on('error', (err) => {
    client.end(() => reject(err));
});

here client is a new Net.Socket(); and the function is async returning a promise that either resolves to the final response or rejects errors.

However whenever I try to connect to a non-existent host my whole program crashes with an uncaught exception:

node:internal/process/promises:246
      triggerUncaughtException(err, true /* fromPromise */);
      ^

Error: getaddrinfo ENOTFOUND testhostmustfail12444.com
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'testhostmustfail12444.com'
}

Ideally I want to catch this specific error and be able to return it to the caller function in order to use the information that the host is not resolvable!

Pdf Viewer download button not working as expected

I am trying to show pdf in iframe using dynamic form submit, that is working fine we see the pdf properly but now when any user wants to download it via clicking download but it is showing “.htm” file. Also when I do it outside iframe every thing working fine.

<iframe id="report" name="showreport" style="width: 100%;height: 100vh;border: 0;"></iframe>

to dynamically provide pdf to iframe we are creating dynamic form as below:

const mapForm = document.createElement('form');
mapForm.target = "showreport";
mapForm.method = 'POST';
mapForm.action = url;

const mapInput = document.createElement('input');
mapInput.type = 'text';
mapInput.name = 'user';
mapInput.value = 'Admin';

mapForm.appendChild(mapInput);
document.body.appendChild(mapForm);

// Just submit
mapForm.submit();

But when we hit download button it is shows “html” instead of “pdf”.

enter image description here

Problem with the music player on the website – odd clicks

Good Morning,

I’m creating a music player for a website that will contain 14 playlists by default, but in the process of writing the site I’ve come across one problem – the selected playlist is only triggered by odd clicks on the page, any even clicks cause problems.

In a nutshell:

  1. I click on playlist A with a single click – it works perfectly
  2. Then I select playlist B with a single click – it does not work
  3. Single click back to playlist A – works fine
  4. Then I select playlist B with a double click – it works flawlessly

So every click #1, #3, #5, #7 etc works flawlessly, however clicks #2, #4, #6, #8 don’t work, they don’t play music and there is no way to pause or unpause the playlist either.

Code:

<!DOCTYPE html>
<html lang="pl">
<head>
    <meta charset="UTF-8">
    <title>RADIO</title>
    <link rel="stylesheet" href="style2.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Roboto&display=swap">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.10.2/css/all.min.css">
</head>
<body>
    <div id="menu">
        <div id="buttons">
            <div class="button-L" onclick="document.body.style.backgroundImage = 'url(img/1.jpg)';"><button value="W" onclick="gra(this)">Playlista 1</button></div>
            <div class="button-S" onclick="document.body.style.backgroundImage = 'url(img/2.jpg)';"><button value="W1" onclick="gra(this)">Playlista 2</button></div>
            <div class="button-S" onclick="document.body.style.backgroundImage = 'url(img/3.jpg)';"><button value="W2" onclick="gra(this)">Playlista 3</button></div>
            <div class="button-S" onclick="document.body.style.backgroundImage = 'url(img/4.jpg)';"><button value="W3" onclick="gra(this)">Playlista 4</button></div>
        </div>
    </div>
 
    <div class="music-container" id="music-container">
        <div class="music-info">
          <h4 id="title"></h4>
          <div class="progress-container" id="progress-container">
            <div class="progress" id="progress"></div>
          </div>
        </div>
   
        <audio src="music/sport.mp3" id="audio"></audio>
   
        <div class="img-container">
          <img src="img/cd-w3.jpg" alt="music-cover" id="cover">
        </div>
 
        <div class="navigation">
          <button id="prev" class="action-btn">
            <i class="fas fa-backward"></i>
          </button>
 
          <button id="play" class="action-btn action-btn-big">
            <i class="fas fa-play"></i>
          </button>
 
          <button id="next" class="action-btn">
            <i class="fas fa-forward"></i>
          </button>
        </div>
      </div>
 
    <script type="text/javascript">
        function gra(tytul) {
            var tytulGry = tytul.value;
            var songs = [];
             
            // Song titles
            if(tytulGry === "W") songs = ['The Trail', 'Kaer Morhen'];
            else if(tytulGry === "W1") songs = ['After The Storm', 'Spikeroog'];
            else if(tytulGry === "W2") songs = ['Trauma', 'Foxkids'];
            else if(tytulGry === "W3") songs = ['Myspace', 'Sport'];
         
            const musicContainer = document.getElementById('music-container');
            const playBtn = document.getElementById('play');
            const prevBtn = document.getElementById('prev');
            const nextBtn = document.getElementById('next');
 
            const audio = document.getElementById('audio');
            const progress = document.getElementById('progress');
            const progressContainer = document.getElementById('progress-container');
            const title = document.getElementById('title');
            const cover = document.getElementById('cover');
            const currTime = document.querySelector('#currTime');
            const durTime = document.querySelector('#durTime')
             
            // Keep track of song
            let songIndex = 1;
 
            // Initially load song details into DOM
            loadSong(songs[songIndex]);
 
            // Update song details
            function loadSong(song) {
            title.innerText = song;
            audio.src = `music/`+song+`.mp3`;
            cover.src = `img/`+tytulGry+`.jpg`;
            }
 
            // Play song
            function playSong() {
            musicContainer.classList.add('play');
            playBtn.querySelector('i.fas').classList.remove('fa-play');
            playBtn.querySelector('i.fas').classList.add('fa-pause');
 
            audio.play();
            }
 
            // Pause song
            function pauseSong() {
            musicContainer.classList.remove('play');
            playBtn.querySelector('i.fas').classList.add('fa-play');
            playBtn.querySelector('i.fas').classList.remove('fa-pause');
 
            audio.pause();
            }
 
            // Previous song
            function prevSong() {
            songIndex--;
 
            if (songIndex < 0) {
                songIndex = songs.length - 1;
            }
 
            loadSong(songs[songIndex]);
 
            playSong();
            }
 
            // Next song
            function nextSong() {
            songIndex++;
 
            if (songIndex > songs.length - 1) {
                songIndex = 0;
            }
 
            loadSong(songs[songIndex]);
 
            playSong();
            }
 
            // Update progress bar
            function updateProgress(e) {
            const { duration, currentTime } = e.srcElement;
            const progressPercent = (currentTime / duration) * 100;
            progress.style.width = `${progressPercent}%`;
            }
 
            // Set progress bar
            function setProgress(e) {
            const width = this.clientWidth;
            const clickX = e.offsetX;
            const duration = audio.duration;
 
            audio.currentTime = (clickX / width) * duration;
            }
 
            //get duration & currentTime for Time of song
            function DurTime (e) {
                const {duration,currentTime} = e.srcElement;
                var sec;
                var sec_d;
 
                // define minutes currentTime
                let min = (currentTime==null)? 0:
                Math.floor(currentTime/60);
                min = min <10 ? '0'+min:min;
 
                // define seconds currentTime
                function get_sec (x) {
                    if(Math.floor(x) >= 60){
                         
                        for (var i = 1; i<=60; i++){
                            if(Math.floor(x)>=(60*i) && Math.floor(x)<(60*(i+1))) {
                                sec = Math.floor(x) - (60*i);
                                sec = sec <10 ? '0'+sec:sec;
                            }
                        }
                    }else{
                        sec = Math.floor(x);
                        sec = sec <10 ? '0'+sec:sec;
                    }
                } 
 
                get_sec (currentTime,sec);
 
                // change currentTime DOM
                currTime.innerHTML = min +':'+ sec;
 
                // define minutes duration
                let min_d = (isNaN(duration) === true)? '0':
                    Math.floor(duration/60);
                min_d = min_d <10 ? '0'+min_d:min_d;
 
 
                function get_sec_d (x) {
                    if(Math.floor(x) >= 60){
                         
                        for (var i = 1; i<=60; i++){
                            if(Math.floor(x)>=(60*i) && Math.floor(x)<(60*(i+1))) {
                                sec_d = Math.floor(x) - (60*i);
                                sec_d = sec_d <10 ? '0'+sec_d:sec_d;
                            }
                        }
                    }else{
                        sec_d = (isNaN(duration) === true)? '0':
                        Math.floor(x);
                        sec_d = sec_d <10 ? '0'+sec_d:sec_d;
                    }
                } 
 
                // define seconds duration
                 
                get_sec_d (duration);
 
                // change duration DOM
                durTime.innerHTML = min_d +':'+ sec_d;
                     
            };
 
            // Event listeners
            playBtn.addEventListener('click', () => {
            const isPlaying = musicContainer.classList.contains('play');
 
            if (isPlaying) {
                pauseSong();
            } else {
                playSong();
            }
            });
 
            // Change song
            prevBtn.addEventListener('click', prevSong);
            nextBtn.addEventListener('click', nextSong);
 
            // Time/song update
            audio.addEventListener('timeupdate', updateProgress);
 
            // Click on progress bar
            progressContainer.addEventListener('click', setProgress);
 
            // Song ends
            audio.addEventListener('ended', nextSong);
 
            // Time of song
            audio.addEventListener('timeupdate',DurTime);
        }
    </script>
</body>
</html>

The songs are .mp3 files whose names are stored in the variable songs[]; Where is the source of the problem? I am kindly asking for an answer.

Regards.

How to publish continuous without blocking main NodeJS app with MQTT.JS

I have the following problem:
I have a Node JS application which should be controlled via Mqtt. It should use the callback function to evaluate messages as to whether the application should start or stop. This already works very well.
However, this application should publish its status every second. However, this should not block the main application. I have already implemented an application that does exactly this in Python. This uses a thread to send the status and does not block the main thread. I need a way to outsource a send state function to a background process.

Since JavaScript only knows single threads, is there a way to enable this?
I’ve already dealt with workers but don’t want to outsource the code to an external file.

thank you

How to integrate google map in react js

I’m using google-maps-react library for maps in my react application, and I’m adding search address functionality in my application and facing CORS error.

error:
enter image description here

Autocomplete.js

import React, { Component } from 'react';
import styled from 'styled-components';

const Wrapper = styled.div`
  position: relative;
  align-items: center;
  justify-content: center;
  width: 100%;
  padding: 20px;
  text-align:center;
`;

class AutoComplete extends Component {
    constructor(props) {
        super(props);
        this.clearSearchBox = this.clearSearchBox.bind(this);
    }

    componentDidMount({ map, mapApi } = this.props) {
        const options = {
            // restrict your search to a specific type of result
            types: ['address'],
            // restrict your search to a specific country, or an array of countries
            // componentRestrictions: { country: ['gb', 'us'] },
        };
        this.autoComplete = new mapApi.places.Autocomplete(
            this.searchInput,
            options,
        );
        this.autoComplete.addListener('place_changed', this.onPlaceChanged);
        this.autoComplete.bindTo('bounds', map);
    }

    componentWillUnmount({ mapApi } = this.props) {
        mapApi.event.clearInstanceListeners(this.searchInput);
    }

    onPlaceChanged = ({ map, addplace } = this.props) => {
        const place = this.autoComplete.getPlace();

        if (!place.geometry) return;
        if (place.geometry.viewport) {
            map.fitBounds(place.geometry.viewport);
        } else {
            map.setCenter(place.geometry.location);
            map.setZoom(17);
        }

        addplace(place);
        this.searchInput.blur();
    };

    clearSearchBox() {
        this.searchInput.value = '';
    }

    render() {
        return (
            <Wrapper>
                <input
                    className="search-input"
                    ref={(ref) => {
                        this.searchInput = ref;
                    }}
                    type="text"
                    onFocus={this.clearSearchBox}
                    placeholder="Enter a location"
                />
            </Wrapper>
        );
    }
}

export default AutoComplete;

MyGoogleMap.js

const MyGoogleMap = () => {
    const [apiReady, setApiReady] = useState(false);
    const [map, setMap] = useState(null);
    const [mapApi, setMapApi] = useState(null);
    const [address, setAddress] = useState();
    const [zoom, setZoom] = useState();
    const [center, setCenter] = useState([]);
    const [lat, setLat] = useState();
    const [lng, setLng] = useState();
    const [places, setPlaces] = useState();
    const [draggable, setDraggable] = useState();

    const setCurrentLocation = () => {
        if ('geolocation' in navigator) {
            navigator.geolocation.getCurrentPosition(position => {
                console.log('position.coords: ', position.coords.longitude);
                console.log("[position.coords.latitude, position.coords.longitude]: ", [position.coords.latitude, position.coords.longitude])
                setCenter([position.coords.latitude, position.coords.longitude]);
                setLat(position.coords.latitude);
                setLng(position.coords.longitude);
            });
        }
    };

    useEffect(() => {
        setCurrentLocation();
    }, []);

    const handleApiLoaded = (map, maps) => {
        console.log('map, maps: ', map, maps);
        // use map and maps objects
        if (map && maps) {
            setApiReady(true);
            setMap(map);
            setMapApi(maps);
        }
    };
    const _generateAddress = () => {
        const geocoder = new mapApi.Geocoder();

        geocoder.geocode({ location: { lat: lat, lng: lng } }, (results, status) => {
            console.log(results);
            console.log(status);
            if (status === 'OK') {
                if (results[0]) {
                    setZoom(12);
                    setAddress(results[0].formatted_address);
                } else {
                    window.alert('No results found');
                }
            } else {
                window.alert('Geocoder failed due to: ' + status);
            }
        });
    };

    const onMarkerInteraction = (childKey, childProps, mouse) => {
        setDraggable(true);
        setLat(mouse.lat);
        setLng(mouse.lng);
    };

    const onMarkerInteractionMouseUp = (childKey, childProps, mouse) => {
        setDraggable(true);
        _generateAddress();
    };

    const _onChange = ({ center, zoom }) => {
        setZoom(zoom);
        setCenter(center);
    };

    const _onClick = value => {
        setLat(value.lat);
        setLng(value.lng);
    };

    const addPlace = place => {
        setPlaces([place]);
        setLat(place.geometry.location.lat());
        setLng(place.geometry.location.lng());
        _generateAddress();
    };

    return (
        <div style={{ height: '442px', width: '100%' }}>
            {apiReady && <Autocomplete map={map} mapApi={mapApi} addplace={addPlace} />}
            <GoogleMapReact
                zoom={4}
                center={center}
                bootstrapURLKeys={{
                    key: 'API_KEY',
                    libraries: ['places', 'geometry'],
                }}
                yesIWantToUseGoogleMapApiInternals
                onGoogleApiLoaded={({ map, maps }) =>
                    handleApiLoaded(map, maps)
                }
            ></GoogleMapReact>
        </div>
    );
}

I’m following this article to integrate Google Maps with search

How to pass datetime from client(browser) to server

I want to pass datetime from client to server. I prefer to pass in ISO format using .toISOString() method. The challenge is while passing datetime(Javascript) to server, if I used C# DateTime then it tries to convert datetime in local datetime. So to get it as in UTC I am using DateTimeOffset. But by this I am not able to get exactly what was client’s offset.

In format I should pass datetime to server so I can retain offset of client or should I pass it separately?