Filtering an Observable (with no duplicates)

I’m filtering an Observable but want to remove any duplicates and undefineds, so I’m hoping to use a Set and some null checks. I’m hoping to only return the dept value.

My first Observable looks like this:

[
    {code: 1, dept: 2, height: 3},
    {code: 1, height: 3}
]

Sometimes there is no dept value so I want to make sure I only return it when it’s there.

Also, I only want to return the departments (with no duplicates) so here’s my code:

myObjects$ = this.myDummyService.getMyObjects() // returns a mock object like above
myDepts$ = this.myObjects$.pipe(map((myObjects) => {
    allObjects.filter((myObject:any) => {
        if(myObject.dept!== undefined) {
            return myObject.dept;
        }
    }
});

So this works for undefineds (even though there’s probably a more elegant way). But how can I test for dupes? I tried this code but am getting syntax errors:

myDepts$ = this.myObjects$.pipe(map((myObjects) => {
    const allMyObjects = allObjects.filter((myObject:any) => {
        if(myObject.dept!== undefined) {
            return myObject.dept;
        }
    }
    const noDupesDepts = new Set(allMyObjects); 
});

How to call init function of Dropzone after every time I click a button using jQuery?

I have a list of similar divs created with the for loop. For each of these divs I have a button to edit information. Every time this edit button is clicked, a pop-up will open that contains a Dropzone box (Dropzone lib). Now, to load images related to div, every time after clicking the edit button, I change the input value related to the image ID with jQuery.
Now I need to read that changed ID from input and use it in dropzone’s init function. But because the dropzone was created before changing the input value and at the initial page load, it has an empty value. I want to run the dropzone init function with the same configuration as the previous one after each click on the edit button.
I will post the written codes below.

html file

@foreach($steps as $step)
    <div class="row card p-3 mb-3 d-flex justify-content-center">
        <div class="col-12 row justify-content-between align-self-center mb-2">
            
            <div class="col-6 p-0">

                <button type="button" class="btn update_step" title="update"
                        data-toggle="modal" data-target="#update_step_modal"
                        step_number="{{$step->number}}"
                        route="{{route('panel.contents.clusters.steps.update', [$content->id, 
                        $cluster->id, $step->id])}}">

                    <span class="mdi mdi-18px mdi-square-edit-outline"></span>
                </button>
              </div>
         </div>

         <div class="col-12 row justify-content-center align-self-center mb-2">
             <p class="col-12 step_description_p">{{$step->description}}</p>

             <div class="col-6 justify-content-center pt-4">
                 <input class="step_cover_id" value="{{$step->cover_id}}" hidden>
                 <img src="{{$step->cover_image}}">
              </div>

         </div>
    </div>      
@endforeach

modal html

<div class="modal fade" id="update_step_modal" tabindex="-1" role="dialog" aria- 
      labelledby="update_step_modal" aria-hidden="true" data-keyboard="false" data- 
      backdrop="static">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>

            <div class="modal-body">
                <div class="col-12 row justify-content-center align-self-center">
                    <form action="" method="POST" id="update_step_form">
                        @method('PATCH')
                        @csrf

                        <textarea name="description" id="update_step_description"></textarea>
                        <input name="cover_id" id="update_step_cover_id" hidden>
                        <input name="video_id" id="update_step_video_id" hidden>

                    </form>
                </div>

                <div class="col-12 row justify-content-center align-self-center mb-2">

                    <div class="col-6" id="update_step_cover_div">
                        <form action="{{url('panel/upload')}}" method="POST" 
                               class="dropzone" id="update_step_cover_form">
                            @csrf
                            <input name="type" value="step_cover" hidden />
                            <input name="content_id" value="{{$content->id}}" hidden />
                            <input name="cluster_id" value="{{$cluster->id}}" hidden />
                            <div class="dz-message" data-dz-message>
                                <span class="m-dropzone__msg-desc">some messages</span>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="d-flex justify-content-center">
                    <button type="button" class="btn" id="step_update_button">
                        <span class="ladda-label">update</span>
                        <span class="ladda-spinner"></span>
                    </button>
                </div>

            </div>
        </div>
    </div>
</div>

js file

$('.update_step').on('click', function () {
   let step_number = $(this).attr('step_number')
   let route = $(this).attr('route')

   $('#edited_step_number').text(step_number)
   $('#update_step_form').attr('action', route)

   let parent = $(this).parent().parent().parent();
   let description = parent.find('.step_description_p').text();
   let cover_id = parent.find('.step_cover_id').val();
   let video_id = parent.find('.step_video_id').val();

   $('#update_step_description').val(description).change();
   $('#update_step_cover_id').val(cover_id).change();
   $('#update_step_video_id').val(video_id).change();
});

Dropzone.options.updateStepCoverForm = {
    paramName: "file", 
    uploadMultiple: false,
    acceptedFiles: "image/*,",
    maxFiles: 1,
    headers: {
        'X-CSRF-Token': $('input[name="_token"]').val(),
        'Accept': 'application/json'
    },
    addRemoveLinks: true,
    init: function() {
        let coverDropzone = this;
        let id = $('#update_step_cover_id').val()

        if(id !== ''){
            $.ajax({
                url: '/panel/fetch_file/' + id,
                type: 'get',
                dataType: 'json',
                success: function (response) {
                    var mockFile = {name: response.data.file_name, size: response.data.size};

                    coverDropzone.emit("addedfile", mockFile);
                    coverDropzone.emit("thumbnail", mockFile, response.data.file_path);
                    coverDropzone.emit("complete", mockFile);
                    coverDropzone.options.maxFiles = 0;
                }
            });
        }

        this.on("removedfile", file => {
            let id = $('#update_step_cover_id').val()
            remove_file_function(id, "update_cover")
        });
    },
    accept: function(file, done) {
        done();
    },
    success: function (file, response) {
        $('#update_step_cover_id').val(response.data.id).change();
    },
    error: function (file, response) {
        error_function(file, response)
    }
};

Does Javascript ever garbage collect functions or constants?

Let’s say there is a file in my app that consists of nothing but hundreds of exported functions, but only one rarely used part of my app uses them. A file like this:

export function a() {
  ..
}

export function b() {
  ..
}

export function c() {
  ..
}

export function d() {
  ..
}

When that section of the app is navigated to, these functions are called (by being imported and then executed), but if users never go there again, are the functions still occupying memory, or are they eventually released?

Would it be more efficient to instead have those be function be defined in a class? And then to instantiate the class when that section of the app is navigated to? Because then when the user leaves that portion of the app, because the reference would go out of scope, then the functions inside would be de-allocated?

Similarly, if you have numbers, or objects, in that same portion of the app, like this:

export const NUM_A = 55;
export const NUM_B = 66;
export const NUM_C = 77;
export const NUM_D = 88;

I assume that numbers are simply inlined, but what if they are complex objects, like this?

export const OBJ_1 = {
  a: 3,
  b: 4,
  c: 5
}; 

export const OBJ_2 = {
  a: 55,
  b: 66,
  c: 77
}; 

Do these just “live forever” after being imported somewhere? Or are they eventually garbage collected? How does this all work?

How can I pass data to a chart and make the chart adapt dynamically?

how can I pass data to a chart and make the chart adapt dynamically? This is my code now (like the documentation, I use vue-google-chars)

import { defineComponent, h } from 'vue';
import { GChart } from 'vue-google-charts';

export const type = 'PieChart';

export const data = [
  ['Task', 'Hours per Day'],
  ['Work', 11],
  ['Eat', 2],
  ['Commute', 2],
  ['Watch TV', 2],
  ['Sleep', 7],
];

export const options = {
  title: 'My Daily Activities',
  width: 450,
  height: 250,
};

export default defineComponent({
  name: 'GoogleChart',
  components: {
    GChart,
  },
  setup() {
    return () =>
      h(GChart, {
        data,
        options,
        type,
      });
  },
});

And this is how I put the label in my .vue file

<PieChart />

How can I pass data so that the chart takes it and displays it automatically, allowing me to reuse this component? (chart-data only, chart-options will be the same for all charts)

ReactJS App sends OPTIONS request before POST request

I am recently struggling a lot with my first website, which i deployed: https://bidimdepru.de/login.
Basically, my problem is, that my website is sending a OPTIONS request before a POST request. I read a bit about it and it seems like it is happening because i add CORS to my backend server.

My Frontend Code:

    const  handleLoginRequest = () => {
    var requestData = {
        username: username, 
        password: password
      }
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(requestData)
    };
    fetch("https://emptychat-backend.onrender.com/login", requestOptions)
    .then(response => {
      if (response.ok) {
        response.json()
        .then(data => {
          auth.signin(data);
          navigate("/home")
      });
      } else {
        response.text()
        .then(data => {
          setToastProps({header: "Oops. Etwas ist schiefgelaufen!", body: data})
          setShowToast(true);
        })
      }     
  })};

Backend server code:

app.use(express.json())
app.use(cookieParser())
app.use(cors({
   origin: 'https://bidimdepru.de',
   credentials: true
   }));

// Login
app.post(`/login`, async (req, res) => {
  try {
    // Eingaben extrahieren
    const { username, password } = req.body;
    // Eingaben validieren
    if (!(username && password)) {
      return res.status(400).send("Alle Eingaben werden benötigt!");
    }
    // Validieren, ob User existiert
    const user = await User.findOne({ username });
    if (user && (await bcrypt.compare(password, user.password))) {
      // Token erstellen
      const token = jwt.sign(
        { user },
        "my_secret_key",
        {
          expiresIn: "2h",
        }
      );
      res.cookie("token", token, {
        httpOnly: true,
        sameSite: none,
        secure: true,
      })
      const parseUser = {
        _id: user._id,
        name: user.name,
        email: user.email,
        username: user.username,
        isAdmin: false,
      };

      return res.status(200).json({auth: true, user: parseUser});
    } else return res.status(400).send("Username/Passwort-Kombination stimmt nicht überein.");
  } catch (err) {
    console.log(err);
  }
});

So basically i could solve my problem, by changing the requestOptions of my fetch() to

const requestOptions = {
    method: 'POST',
    headers: { 'Content-Type': 'text/plain' },
    body: JSON.stringify(requestData)
};

When i change the Content-Type to “text/plain” i am only sending one POST Request, but then i cant access the username, password from my req.body. Could i solve this, without changing the content-type? How can i get username and password out of req.body, when i stay with text/plain

Dos selectores en un formulario [closed]

Ocupo que al poner el selector del primer formulario se autocomplete el del segundo. Solo que en el primer selector tengo muchos registros, como le puedo hacer para que al seleccionar un registro del primer campo el segundo se complete en relacion con el primero

Lo intente con la funcion change pero no funciona

Firebase Dynamic Links Ignore Additional Query Parameters

I’m working on a project that requires generating short URLs for links with numerous query parameters. I’ve attempted to achieve this using Firebase Dynamic Links, but I’ve encountered some issues. I’m seeking your expertise to help resolve these problems.

I have a lengthy URL with several query parameters, like this:

https://example.com/p/h2b883?params1=value&params2=value&params3=225555

I want to replace this long URL with a shorter one using Firebase Dynamic Links.

Here’s the code I’ve used:

httpService
.post(process.env.DYNAMIC_LINK_API, {
    longDynamicLink:
        'https://domain.page.link/?link=' +
        'https://example.com/p/h2b883?params1=value&params2=value&params3=225555',
})
.toPromise()
.then((res) => {
    return res.data.shortLink;
})

The code provided returned the following result:

{
  shortLink: 'https://domain.page.link/vyLMGdsqdsqrjruVGA87',
  warning: [
    {
      warningCode: 'UNRECOGNIZED_PARAM',
      warningMessage: "Unrecognized param 'params2'. [https://firebase.google.com/docs/dynamic-links/create-manually#ddl_parameters]"
    },
    {
      warningCode: 'UNRECOGNIZED_PARAM',
      warningMessage: "Unrecognized param 'params3'. [https://firebase.google.com/docs/dynamic-links/create-manually#ddl_parameters]"
    }
  ],
  previewLink: 'https://domain.page.link/vyLMG2hdsqdqVGA87?d=1'
}

The issue is that it generates a URL perfectly, but only with one query parameter, specifically the first one. It disregards the others that are displayed in the warning message.

Thank you in advance for your assistance!

How do I manage Google Maps API asynchronous functions?

I developed a website for a private transfer service company which operates in Venice, Italy. I realized a transfer calculator where you can input “from” and “to”, some other factors like type of vehicle and passengers, and get your quote. Whenever a user fires the calculator, the Google Maps API are used to display the route on the map and to get how many km is the drive in order to multiply that value for the rate per kilometre.

Now the problem is that Venice is full of water-surrounded destinations and I want the calculator to recognize if either the starting point or the destination cannot be reached just via car and if the user needs a boat. And that’s where things get complicated.

At the moment, I can successfully find out if an address cannot be reached via car:

  1. Convert the address taken from the form into a LatLng object using geocoding,
  2. Check if the new LatLng is inside a polygon I previously created with google.maps.Polygon (the polygon includes the Venice area that I want to be included as non-reachable),
  3. If true then change the address inside the request variable that will be used as parameter into the directionsService.route() to a specific address where the customer will find a boat.

This is working great, problem is that I cannot get the two funtions that performs this kind of check (one for the departure and one for the destination) to return the corrected address before the directions services are fired.

I also tried with javascript callback and promises but with no luck.
About promises, I wrote all the functions in order to be concatenated to the main Promise and control their execution order but seems like the directionsServices.route() will be fired first no matter what.

Here is the code I am using now:

var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();

function calcRoute() {
    directionsDisplay.setOptions({
        polylineOptions: {
            strokeColor: '#1267ff'
        }
    });
    
    directionsDisplay.setMap(theMap);
    
    function checkingDeparture(startingPoint) {
        console.log('1. checkingDeparture called');
        var newDeparture = startingPoint;
        var geocoder = new google.maps.Geocoder();
        
        geocoder.geocode({'address': newDeparture}, (results, status) => {
            console.log('2. checkingDeparture geocoder called');
            if(status == google.maps.GeocoderStatus.OK) {
                coordPoint = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                
                if(google.maps.geometry.poly.containsLocation(coordPoint, window.venicePolygon)) {
                    console.log('3. checkingDeparture containsLocation called');
                    newDeparture = 'Piazzale Roma, Venezia, VE, Italia';
                    console.log('first var check: ' + newDeparture);
                    
                    return newDeparture;
                } else {
                    return newDeparture;
                }
                
                console.log('second var check: ' + newDeparture);
            }
        });
    }
    
    function checkingDestination(endingPoint) {
        console.log('1. checkingDestination called');
        var newDestination = endingPoint;
        var geocoder = new google.maps.Geocoder();
        
        geocoder.geocode({'address': newDestination}, (results, status) => {
            console.log('2. checkingDestination geocoder called');
            if(status == google.maps.GeocoderStatus.OK) {
                coordPoint = new google.maps.LatLng(results[0].geometry.location.lat(), results[0].geometry.location.lng());
                
                if(google.maps.geometry.poly.containsLocation(coordPoint, window.venicePolygon)) {
                    console.log('3. checkingDestination containsLocation called');
                    newDestination = 'Piazzale Roma, Venezia, VE, Italia';
                    return newDestination;
                } else {
                    return newDestination;
                }
            }
        });
    }
    
    var request = {
        origin: checkingDeparture($('#startTransfer').val()),
        destination: checkingDestination($('#endTransfer').val()),
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC
    };
    
    directionsService.route(request, (result, status) => {
        console.log('4. checking value of origin: ' + request.origin);
        console.log('5. checking value of destination:' + request.destination);
        console.log('6. directionsService called');
        if(status == google.maps.DirectionsStatus.OK) {
            //do things
        }
        
        else {
            directionsDisplay.setDirections({routes: []});
            theMap.setCenter(window.globalCenter);
        }
    });
}

new version serialport 10.x not doing what was easy in 9.x

for years i use node serialport with node on a raspberry pi 3 b plus for redirecting incoming hex data from domotica serial usb sticks to an other usb seral port on the pi connected to digi serial server. but now programming this with the newest serialport and node versions it doesn’t work , the latency is much to long so communication is to slow.

this works with old code quite simple

'use strict';



const util = require("util")
const buffer = require('buffer');
let serialport = require('serialport');
//let SerialPort = serialport.S


   let bRate = 115200;

    // list serial ports:
    serialport.list(function (err, ports) {
        ports.forEach(function (port) {
            util.log(port.comName);
        });
    });



let portStick = new serialport('/dev/ttyUSB0', {
    encoding: 'hex', baudRate: bRate , dataBits: 8, stopBits: 1, parity: 'none',
});
let portSource = new serialport('/dev/ttyUSB1', {
    encoding: 'hex', baudRate: bRate , dataBits: 8, stopBits: 1, parity: 'none',
});



portStick.on('open', function () {

    util.log('portStick opening');

});

portSource.on('open', function () {

    util.log('portSource opening');

});


//port.open(function (err) {
//    if (err) {
//        return util.log('Error opening port: ', err.message);
//    }

//    // write errors will be emitted on the port since there is no callback to write 
//    // port.write('main screen turn on');
//});





portStick.on('data', function (data) {
   // util.log('Data: ' + data);

    util.log('data from Stick ' );
    //let myString = JSON.stringify(data)
    //util.log('second Data Stick: ' + myString);

    //portStick.pipe(socket)
    if (portSource) { portSource.write(data) }

    //util.log('string hex Stick ', data.toString('hex'));
});

portStick.on('error', err => {

    util.log('error portStick', err)

})

portSource.on('data', function (data) {

    //util.log('Data: ' + data);
    util.log('data from Source ');
    //let myString = JSON.stringify(data)
    //util.log('second Data Source: ' + myString);

    //portSource01.pipe(socket)
    if (portStick) { portStick.write(data) }

   // util.log('string hex Stick', data.toString('hex'));
});

portSource.on('error', err => {

    util.log('error portSource', err)

})


this is the nwe code for to slow

  

<!-- begin snippet: js hide: false console: true babel: false -->
const buffer  =require('buffer');
//let serialport = require('serialport');
const sp = require('serialport')
//let SerialPort = serialport.S
const util = require("util")


const bRate =  115200;
const bR = 9600;
 

// list serial ports:
sp.SerialPort.list()
    .then((data) => console.log('data ports',data))
    .catch(err => console.log(err));

const portStick = new sp.SerialPort({ path: '/dev/ttyUSB0', baudRate: bRate, dataBits: 8, stopBits: 1, parity: 'none' });
const portSource = new sp.SerialPort({ path: '/dev/ttyUSB1', baudRate: bRate, dataBits: 8, stopBits: 1, parity: 'none' });

console.dir(portStick, { depth: null }); 

portStick.setEncoding('hex')
portSource.setEncoding('hex')

portStick.on('open', () => {

    console.log(new Date().toString() ,'      portStick opening');

});

portSource.on('open', () => {

    util.log('portSource opening');

});

//  portSource.read() = Buffer

//port.open(function (err) {
//    if (err) {
//        return util.log('Error opening port: ', err.message);
//    }

//    // write errors will be emitted on the port since there is no callback to write
//    // port.write('main screen turn on');
//});











portStick.on('data',  (data) => {
    // util.log('Data: ' + data);

    util.log('data from Stick ',data);
    //let myString = JSON.stringify(data)
    //util.log('second Data Stick: ' + myString);

   // portStick.pipe(portSource)
    if (portSource) { portSource.write(data); util.log('portSource true') }

    //util.log('string hex Stick ', data.toString('hex'));
});

portStick.on('error', err => {

    util.log('error portStick', err)

})

portSource.on('data',  (data) => {

    //util.log('Data: ' + data);
    util.log('data from Source ', data);
    //let myString = JSON.stringify(data)
   // util.log('second Data Source: ' + myString);

  // portSource.pipe(portStick)
    if (portStick) { portStick.write(data); util.log('portStick true') }

   //  util.log('string hex source ', data.toString('hex'));
});

portSource.on('error', err => {

    util.log('error portSource', err)

})

How to modify values of a scoped slot in VueJS 2

I am attempting to modify the calendar component from vutify (https://v2.vuetifyjs.com/en/components/calendars/) I want to change the week view so that the days only show the day and do not have the times.

I have tried to modify the slot based on the API described here (https://v2.vuetifyjs.com/en/api/v-calendar/#slots) Here is the code so far

<v-calendar
          ref="calendar"
          v-model="focus"
          color="primary"
          :events="events"
          :event-color="getEventColor"
          :type="type"
          @click:event="showEvent"
          @click:more="viewDay"
          @click:date="viewDay"
          @mousedown:event="startDrag"
          @mousedown:time="startTime"
          @mousemove:time="mouseMove"
          @mouseup:time="endDrag"
          @mouseleave.native="cancelDrag"
        >

          <template v-slot:day-body="{ hasTime }">
            {{ (hasTime = false) }}
          </template>

</v-calendar>

But this changes nothing.

Api call using Js [duplicate]

I’m using an API that gives stock prices. Now I want to call it after every minute according to the real clock. Like if it’s 11:23 in the system then it should be called at 11:24 and so on.
My confusion in using setInterval({},6000) is that if our component is rendered at 11:23:30 then it will be again called at 11:24:30 but I want to call it at 11:24:00 then 11:25:00, and so on. No matter when it was rendered.

Is there any library or tutorial that can do this type of transition? or if anyone know how to do this? [closed]

This transition like in https://www.buildinamsterdam.com, 2 div translateY to the bottom at the same time regardless of the height. If you start scrolling the transition is stopped, and when you let go the scroll the transition continue. I’m trying to recreate this transition.

I try to auto scroll the parent div but result wasn’t like the original one.