Flow JS Union types and callbacks

I have a flow curiosity regarding union types and callbacks, where it seems logically to me that the error cannot happen given the circumstances. I’m wondering if I’m having a brainfart, if flow just doesn’t pick up such things, or it’s something else

I’ve boiled the usecase down to it’s core with the following Try Flow Link, but I’ll add it below for posterity. The case is when I have a function that takes in a union type as well as a callback that takes in the same union type.

If I have a separate function that restricts the type to just one of the types in the union, flow still complains that the callback could have either. It seems to me that, technically, Flow should have enough information statically to understand this can’t happen, but again, maybe I’m brainfarting.

type A = {
  id: number,
  aOnly: boolean,
} 

type B = {
  id: number,
  bOnly: boolean
}

type AorB = A | B;

/**
  Main fn that takes in union type, as well as a callback that accepts
  the union type
 */
function main(ab: AorB, callback: (AorB) => boolean): void {
  callback(ab);
}


/**
  ONLY allows type A, therefore the callback should only be receiving type A
  in this scenario, yet flow thinks it could have either type
 */
function processA(a: A): void {
  main(a, (a) => {
    /* Cannot get `a.aOnly` because property `aOnly` is missing in `B` */
    return a.aOnly;
  });
}

/**
  Running the following gets:
  Cannot get `a.aOnly` because property `aOnly` is missing in `B`
 */
processA({
  id: 123,
  aOnly: true
});

What exactly is happening here? Is there a solution to this that doesn’t involve adding in conditionals or disjoint unions?

How to filter an array by numbers in strings?

I have an array:

[
  'B3', 'B4', 'B5',
 
  'B6', 'C3', 'C4',
 
  'C5', 'C6', 'D3',
 
  'D4', 'D5', 'D6'
]

I need to filter it by the number in each string (in ascending order). The number can be one/double-digit/triple-digit.

Here’s what the final array should look like:

[
  'B3', 'C3', 'D3',
 
  'B4', 'C4', 'D4',
 
  'B5', 'C5', 'D5',
 
  'B6', 'C6', 'D6'
]

How can I do it?

when the page loads, the opacity of a div is appearing, then disappearing and wont come back when sidebar is opened

Im trying to create a pop-out sidebar with a small list of items in it and ive set the opacity to 0 to begin with then when it opens, the opacity is set to 1. Its currently loading, fading in the item, then fading out because of a transition. but im not sure why its fading in to begin with even though i have the opacity set to 0.

.inputItem {
  opacity: 0;
  margin: 2vh, 0;
  position: relative;
  height: 40px;
  width: 100%;
  -webkit-transform: translateY(-20px);
  -moz-transform: translateY(-20px);
  -ms-transform: translateY(-20px);
  -o-transform: translateY(-20px);
  transform: translateY(-20px);
}
function menuOpen() {
  if(!toggled){
    document.getElementsByClassName('inputItem').style = 'opacity: 1;'
    toggled = true
  } else {
    document.getElementsByClassName('inputItem').style = ''
    toggled = false
  }
}
<div id='sideMenu' class='sideMenu'>
   <form id='inputWrapper' class=inputWrapper>
      <div id='inputItem' class='inputItem'>
         <input id='x1' type='text' name=''>
         <label class='plntPropInptTxt'>X</label>
         <span></span>
      </div>
   </form>
</div>

the full code here: https://orbiting-simulator.erodecode.repl.co

How to use request callback with node.js in google actions?

Right now I’m using the Google Actions console to create a simple action that fetches the summary of a random Wikipedia article.

Here’s the node.js:

const { conversation } = require('@assistant/conversation');
const functions = require('firebase-functions');
const request = require('request');
const app = conversation();
var http = require('http');

function getWiki(callback) {
  request('https://en.wikipedia.org/api/rest_v1/page/random/summary', function (error, response, body) {
    if (!error && response.statusCode == 200) {
      dataObj = JSON.parse(body);
      title = dataObj.title;
      summary = dataObj.extract;
      speech = `${title}. ${summary}`;
      return callback(result, false);
    } else {
      return callback(null, error);
    }
  });
}

app.handle('wiki_random', conv => {
  getWiki();
  conv.add(speech);
});

exports.ActionsOnGoogleFulfillment = functions.https.onRequest(app);

Under the app.handle fucntion I’m having trouble getting it to wait for the getWiki function to complete before executing the conv.add(speech). How do I go about implementing my callback into the app.handle function?

Can’t use return from promise globally

I wrote a promise function in a firebase.js to return access key which I wanted to use everywhere after I start the server. But for some reason when I export the module and use it in app.js, I can’t print the returned access_token Or a better question would be , how to use the access_token everywhere globally after the server is started.

Firebase.js is below

var {google} = require('googleapis');
var MESSAGING_SCOPE = 'https://www.googleapis.com/auth/firebase.messaging';
var SCOPES = [MESSAGING_SCOPE];
var http = require('http');

function getAccessToken() {
    return new Promise(function(resolve, reject) {
        var key = require('./serviceAccountKey.json');
        var jwtClient = new google.auth.JWT(
            key.client_email,
            null,
            key.private_key,
            SCOPES,
            null
        );
        jwtClient.authorize(function(err, tokens) {
            if (err) {
                reject(err);
                return;
            }
            resolve(tokens.access_token);
        });
   });
}

getAccessToken().then(function(access_token){

    //console.log(access_token);
    return access_token;
})

module.exports.getAccessToken = getAccessToken

Below is app.js

const express = require("express");
const ac = require('./firebase.js');
const app = express();

console.log(ac.getAccessToken);

const port = process.env.PORT || 1111 ;

app.listen(port, () => {
  //console.log(`server up and running on ${process.env.PORT}`);
  console.log(`server up and running on ` + port);
});

I start the server by nodemon index.js

How to open a downloaded PDF using Ajax in a new window from Android webview

I have a android application which contains a webview. I have added a ajax script which downloads a pdf from my php server.

Like so:

        $.ajax({
            type: 'post',
            url: 'url',
            data: {token: token},
            xhrFields: {
                responseType: 'blob'
            },
            success: function (res) {
                var blob = new Blob([res]);
                var link = document.createElement('a');
                link.href = window.URL.createObjectURL(blob);
                link.target = 'blank';
                link.download = "report.pdf";
                link.click();
            }
        });

this works directly from a browser but from the android app the download does not happene. Ideally I want the link to open up into a new browser window outside the app.

Wondering if anyone can help with this.

Thanks in advance

react state get spesific object from array with state to another componente

i am new to react and i need to learn a few things
i need to know if my way to get spesific movie is correct (its working but i think its not the right way)
i have a state of data
i need to get spesific object inside the array and this object will display in the componente “spesificMovie” so to get the right object i create function that run with filter on the state with data and then search if the name eqeual to the name i give to the func as argument i will return the object to another state that will be the spesificMovie
and this state i move to the componente spesificMoive

import { useState } from "react";

import Movie from "./componente/Movie";
import SpesificMovie from "./componente/SpesificMovie";


function App() {
  const [spesificMovie, setSpesificMovie] = useState();
  const getMovieFunc = (name) => {
    movies.filter((movie) => {
      if (movie.movieName == name) return setSpesificMovie(movie);
    });
  };
  const [movies, setMovies] = useState([
    {
      movieName: "godfather",
      info: "the rise of  corelone family  all mater is respect,money,woman but the youngest son michal has a diffrent plans...",
      picture: "pictures/godfather.jpg",
      rating: [10, 5, 1],
    },
    {
      movieName: "scarface",
      info: "the rise of  tony montata the badass man of miami want to control miami and be the number 1 of the cocaine provider ...",
      picture: "pictures/scarface.jpg",
      rating: [10, 9, 2],
    },
    {
      movieName: "the-dark-knight",
      info: "you all knew that he will come the batman! come to fight with his popular rival the joker...",
      picture: "pictures/the-dark-knight-poster.jpg",
      rating: [10, 10, 9],
    },
  ]);
  return (
    <div className="App">
    
      
      
         <SpesificMovie spesificMovie={spesificMovie}/>
       <Movie movies={movies} getMovieFunc={getMovieFunc}/>
    
    </div>
  );
}

export default App;

About inkscape usage of H and V path command

I’m trying to do generate sketchy svg file by vectorizing pics. Thenafter, I rework the svg with some node script.

To achieve my goal, I have to determine if a point is over a given path. To do that I use
https://github.com/rubenv/point-in-svg-polygon

When I call isInside(point, path), I encounter an error: Uncaught Error Error: Unknown operator: for polygon

After debugging, I can see that my SVG contains V and H commands with 2 parameters, and the lib restricts to one.

Exemple

<path d="M 0,512 V 0 H 512 1024 V 512 1024 H 719.62244 C 450.28457,1024 ... Z" id="path2785"/>

The documentation tends to agree with the lib according to https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths, but I can’t imagine Inskape doing this for no reason.

Could you tell me why inkscape is doing this (can’t find it with google) ?
Is this an issue of the library or with inkscape?

React.useState, will not update. How do I perform a instant update of React useState?

So I’m setting up a react useContext to share user’s data such as the user’s name and the login status etc… I make a request to the server every time a user refreshes the app to verify that if they have a valid token, the user can then be logged in. Great, but one problem I keep on running into with react is knowing how to get an instant update of useState, as this is needing to be updated as soon as the user is verified.

I’ve read that you have to create a new object so that React knows it’s a new object and then it’ll trigger a re-render… Just about every combination I can think of I’ve tried. Can someone please clarify for me how it’s done?

Option 1:

   setUser(prev => {
    return { ...prev, ...newObj }
   })

Option 2:

   setUser({ ...newObj })

Can someone please give me the proper way to get a instant update to the React useState.

Thanks

javascript calendar block dates that are from the db

I’m trying to create a calendar inside of an text input with javascript and mysqli. this calendar has booked dates in it that are based on the start date and the end date in the db.
I have a db with 2 collums
one is start_datum (start_date)
and the other one is eind_datum (end_date)

what I want is that the user is able to click on the input date and that it shows this mini calendar where the user is able to pick out dates to make a reservation

however certain dates are blocked because they have been put inside of the db and ate between the start and end date.

the problems I have with this is that a) I can’t create the disabled dates
and b) the end_date input doesn’t want to show the same calendar

my knowledge of javascript is very limited so idk what to do now. how do I fix this? (note I’m very bad at english so sorry for mistakes)

$(function() {
    $( "#datepicker" ).datepicker({
    numberOfMonths: 1,
    minDate:0,
    showButtonPanel: true,
    
   
    });
});
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>jQuery UI Datepicker - Display multiple months</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <?php
 $huis_ID = "1";

 $sql = "SELECT * FROM reserveringen WHERE huis_ID = ?";
 $stmt = $conn->prepare($sql);
 $stmt->bind_param("i", $huis_ID);
 $stmt->execute();
 $result = $stmt->get_result();
 $data = $result->fetch_all(MYSQLI_ASSOC);
 if ($data):
   ?> 
        <?php foreach($data as $row): ?>
            <?php 
            $start_datum = date('d-m-Y', strtotime($row['start_datum']));
            echo $start_datum , "<br>"; 
            $eind_datum = date('d-m-Y', strtotime($row['eind_datum']));
            echo $eind_datum , "<br>"; 
            ?>
        <?php endforeach ?>
    <?php else: ?>
        No data found
    <?php endif ?>

  </head>
<body>
<p>start_date: <input type="text" id="datepicker" name ="datepicker"></p>

<p>end_date: <input type="text" id="datepicker" name ="datepicker"></p>

</body>
</html>

pics of what it looks like right now
start_date

end_date (the one thast doesn't work for some reason

Find a file back in folder structure in multiple situations (Apps Script)

I need to find with Apps Script a specific Sheet back in folder structure of my actual Sheet (found filtered by title fragment for example). But sometimes is in the direct parent and another two or three folders behind, so I want the most versatile solution to work in different situations. Which will be the best and clean way?

[ FILE TO FIND ] [ FOLDER 1 ] [ ACTUAL FILE ]
                 [ FOLDER 2 ] [ ]

[ FILE TO FIND ] [ ACTUAL FILE ]

Thanks!

.find() method for lua or array search

is there a way to filter the array by its lua elements?
as in the javascript example:

const array = [{
element:"a",
element2:{
example:false
}
},
{
element:"b",
element2:{
example:true
}
}]

let filtered = array.find(itemInArray => itemInArray.element2.example == true) //to get the element
//or 
let filtered = array.filter(itemInArray => itemInArray.element2.example == true) // to filter the element

but in lua!
like:

local array = {{
["element"] = "a",
["element2"] = {
["example"] = false
}
},
{
["element"] = "b",
["element2"] = {
["example"] = true
}
}}

--in that case, how do I filter the desired result or find it?

in short, is there a lua version of javascript’s .find() or .filter() functions?

How to capture one particular instance of a string only if it occurs twice in regex?

I have a regex expression: /diff\left((...*?\right){0,1})\right)/gm and the string I want to match is diffleft(5x^2right) + diffleft(5x^2+tanleft(xright)right).

I want to match in such a way that there are two matches diffleft(5x^2+right) and diffleft(5x^2+tanleft(xright)right) each having captured groups 5x^2 and 5x^2+tanleft(xright). I want to add right) inside a captured group once only if it occurs twice. However, I’m only getting a single match with the entire 5x^2right)+diffleft(5x^2+tanleft(xright) inside a captured group. Here are two images to better understanding. Blue parts represent matches and green parts represent captured groups
Here is the output I’m getting

Desired output

The first image is a screenshot from regex101 and the second one is an edited image

Please help me with this I’m trying to build a symbolic calculator app. Thanks

React Native setInterval Works Slowly

I am trying to create stopwatch application. I’m using setInterval function to increase time. But my app to stay behind windows clock app.

windows clock app:
windows clock app

my app:
my app

I launched both at same time.

App.js

export default function App() {
const [time, setTime] = useState({ running: false, time: 0 });
const [count, setCount] = useState(time.time);

useEffect(() => {
    console.log(count);
    let id;
    if (time.running)
      id = setInterval(() => setCount(count => count + 100), 100);

    return () => { 
      if (time.running) 
        clearInterval(id);
    };
  }, [time.running]);

  const counter = () => {
    if (time.running) {
      setTime({
        running: false,
        time: time.time
      });
    } else {
      setTime({
        running: true,
        time: time.time
      });
    }
  };
}


return (
    <TimeContext.Provider value={{ time, setTime }}>
      <SafeAreaView style={[styles.container, { backgroundColor: theme.background }]}>
        <View style={styles.stopwatch}>
          <Stopwatch time={count} />
        </View>
      </SafeAreaView>
    </TimeContext.Provider>
  );

Stopwatch.js

export default function Stopwatch({ time }) {
  return (
    <Text style={[styles.text, { color: theme.text }]}>{msToTime(time)}</Text>
  );
}

ms-to-time.js

export default function msToTime(duration) {
  var milliseconds = Math.floor((duration % 1000) / 100),
    seconds = Math.floor((duration / 1000) % 60),
    minutes = Math.floor((duration / (1000 * 60)) % 60),
    hours = Math.floor((duration / (1000 * 60 * 60)) % 24);

  hours = (hours < 10) ? "0" + hours : hours;
  minutes = (minutes < 10) ? "0" + minutes : minutes;
  seconds = (seconds < 10) ? "0" + seconds : seconds;

  return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}

When click start button counter function triggers.
I’m increasing count variable instead of time.time cuz other components using time so i blocking render others this way.

Javascript – localStorage issues

In the script below, I want to be able to display on the main html page lists of paragraphs saved in the localstorage, add, remove or delete them all.

In the script below the function “displaylocalstorage” does not allow me to display the values that have been saved in the localstorage with the function “storedparagraphs”. Can you please give me some guidelines to correct the “displaylocalstorage” function?
Can you also give me guidelines to correct the “removedlastparastored” function?

Here is the html and js script below:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="static/style.css">

</head>
<body>
<div>
    <h1 id ="title">Items List</h1>
    <br>
    <br>

    <div id ="content" class="content">

    </div>
    <br>
    <br>
    <input type="text" value = "Enter an Item" onfocus = 'this.value =""' id="mytext">
    <br>
    <br>
    <input type="button" value="Add item" id="addbutton" class="addbutton">
    <br>
    <br>
    <input type="button" value="Remove Last Item" id="buttonremove" class="buttonremove">
    <br>
    <br>
    <input type="button" value="Clear All" id="buttonclearall" class="buttonclearall">

</div>
<script src="static/script.js"></script>

Javascript:

const mybutton = document.getElementById ("addbutton");
const mytext = document.getElementById("mytext");
const content = document.getElementById("content");
const buttonremove = document.getElementById("buttonremove");
const buttonclearall = document.getElementById("buttonclearall");

function storedparagraphs() {
    let n = 0;
    while (localStorage.getItem("content" + n)) {
        n++;
    }
    localStorage.setItem("content" + n, mytext.value);
}   


function displaylocalstorage() {
    const n = 0;
    const items = [];
    while (localStorage.getItem("content" + n)) {
        items.push(localStorage.getItem("content" + n++));
    }
    return items;

}

function addparagraphs () {
    const newparagraph = document.createElement("p");
    newparagraph.innerText = mytext.value;
    content.appendChild(newparagraph);
} 

function removedlastpara(){
    const paragraphs = document.getElementsByClassName("beautiful");
    if(paragraphs.length > 0){
        const lastposition = paragraphs.length -1;
        content.removeChild(paragraphs[lastposition]);
    }
}

function removedlastparastored(){
    const n = 0;
    while (localStorage.getItem("content" + n)) {
        n++;
    }
    localStorage.setItem("content" + n, mytext.value);
    if(n.length >0){
        let lastposition = n.length -1;
        localStorage.removeItem("content", lastposition)
    }
}

function clearall(){
    const paragraphs = document.getElementsByClassName("beautiful");
    while(paragraphs.length > 0){
        paragraphs[0].parentNode.removeChild(paragraphs[0]);
    }

}

function clearallstored(){
    localStorage.clear();
    return false;
    }

mybutton.addEventListener("click",addparagraphs);
mybutton.addEventListener("click",storedparagraphs);
buttonremove.addEventListener("click", removedlastpara);
buttonremove.addEventListener("click", removedlastparastored);
buttonclearall.addEventListener("click", clearall);
buttonclearall.addEventListener("click", clearallstored);