Angular – Create composed type of value, function or Observable and accessing it in Component template

I would like to create a type that can be a either value (string, bool, number, …), function or observable and then be able to access it’s value in the component template.

Motivation is to create flexible API for component input properties, where user can provide input as type that suits them the best (value, function or observable) and component should be “smart” enough to render the value according to it’s type.

Having a common type for value and function would look like this:

// age.component.ts
type ValOrFunc<T> = T | ((...args: unknown[]) => T); 

@Component({
    selector: 'app-age',
    ...
})
class AgeComponent {

    @Input()
    age: ValOrFunc<number>

    constructor() { }

    getValue<T>(val: ValOrFunc<T>): T {
        if (val instanceof Function) {
            return val();
        }
    
        return val;
    }
}

// age.component.html
<p>
    Age is {{ getVal(age) }}
</p>

Now anyone using AgeComponent can provide age as either number or function and the value will be update in the age component template.

Problem is when I want to add Observable into the equation.

// age.component.ts

type ValFuncOrObs<T> = T | ((...args: unknown[]) => T) | Observable<T>;

@Component({
    selector: 'app-age',
    ...
})
class AgeComponent {

    @Input()
    age: ValFuncOrObs<number>

    constructor() { }

    getValue<T>(val: ValFuncOrObs<T>): T {
        ???
    }
}

Now how should the getValue implementation look like?

I was thinking also about checking the type in the template and using AsyncPipe when the value is observable, but that feels tedious and would add a lot of repeating code for component with many input properties.

// age.component.html
<p>
    Age is {{ isObservable(age) ? age | async : getVal(age) }}
</p>

curious double var case in javascript

Curious case in JavaScript where you get not exactly the most people would expect

function test() {
  var v = 2;
  var v = v++;
  console.log(v);
}
test();

Should the ++ operation precede attribution = or the creation of the new “v”?

why the order of loop changes by parsing data in sqlite database

an xml document is edited using a function. First, all duplicate files are removed. Then the content is entered into a sql database. For this I run a loop that corresponds to the length of the xml elements (here already converted to json). When I look at the content of the table in the database, I see that the order of the entries does not correspond to the order of the array. So within the database query of my server I printed the run variable i and saw that it starts at 0 but 2,3,1 are appended to the end in this order.
Unfortunately I don’t understand at all why this happens and hope that someone can help me here.

function extractquestions(filename){
    let questions = [];
    let sql_insert = 'INSERT INTO Fragen (Titel, Frage) values (?,?)';
     
    fs.readFile('./files/'+filename, function(err, data){
        if(err){
            throw err;
        }
        
        const xmlDataStr = data;
        const options = {
            ignoreAttributes: false,
            attributeNamePrefix : "attr_"
        };
        const parser = new XMLParser(options);
        const output = parser.parse(xmlDataStr);
        for(let i = 0; i<output.quiz.question.length; i++){
     
            //Here the needed Questions are filtered out of the xml (Json) data
            if(output.quiz.question[i].attr_type == "coderunner"){
                questions.push(output.quiz.question[i]);
            }
        }


        //Delete Duplicates from array
         const filteredQuestions = questions.reduce((acc, current) => {
            const x = acc.find(item => item.name.text === current.name.text);
            if (!x) {
                return acc.concat([current]);
            } else {
                return acc;
            }
        }, []);
        
        for(let i = 0; i<filteredQuestions.length; i++){
            db.run(sql_insert, filteredQuestions[i].name.text, filteredQuestions[i], (err, result)=>{
                console.log(i);
                if(err){
                    throw err;
                }
            });
        }
    });
}

Avoid rerendering when doing button.click() inside useeffect()

I’m trying to set the data from child component to parent component’s state in turn that data will be assigned to input text field. And then I want to automatically click the button to submit the data from input text field to handleBtnSubmit() function.

But when I did this child component is rendering indefinitely. Can someone please help resolving this kind of situation?

  //Parent 

const submitAction = () => {
    setResponses((responses) => [...responses, message]);
    handleMessageSubmit(message.text);
    setCurrentMessage('');
  };



  const handleBtnSubmit = () => {
    submitAction();
  };
  
       
     <Messages
        messages={responses}
        setCurrentMessage={{ currentMessage, setCurrentMessage, btnRef, handleBtnSubmit }}
      />
      
      <div className='typing-area'>
        <div className='input-field'>
          <input
            type='text'
            placeholder='Type something here'
            required
            value={currentMessage}
            onChange={handleMessageChange}
            onKeyDown={handleSubmit}
          />
        </div>
        <button onClick={handleBtnSubmit} ref={btnRef}>
          <img src={sendButton} alt='Send Button' />
        </button>
      </div>
      
      
    //Child
    
      const setMessage = (option) => {
      setCurrentMessage.setCurrentMessage(option);
      // setCurrentMessage.btnRef.current.click();
      // console.log(setCurrentMessage.currentMessage);
      };

      useEffect(() => {
        console.log(setCurrentMessage.currentMessage);
        // setCurrentMessage.btnRef.current.click(); //tried this
        // setCurrentMessage.handleBtnSubmit(); //also also tried directly calling handleBtnSubmit();
        //both are causing indefinite rerender
      }, []);
      
      
       <li className='option' key={i} onClick={() => setMessage(option)}>
                {option}
        </li>

I am getting Request failed with status code 403 error when I wanted to get data in my mongodb

when I wanted to get something in the database it’s giving me this error, I can’t catch the error.
I wanted to get data in my database. My all keys are okay, there is no problem. in my http://localhost:5000/my this gives me this error {“message”: “Unauthorized Access”}

//server side

const express = require("express");
const app = express();
const port = process.env.PORT || 5000;
app.use(express.json());
var jwt = require("jsonwebtoken");
var cors = require("cors");
app.use(cors());
app.get("/", (req, res) => {
  res.send("Hello World!");
});

const { MongoClient, ServerApiVersion, ObjectId } = require("mongodb");
const uri =
  "mongodb+srv://laptop:[email protected]/myFirstDatabase?retryWrites=true&w=majority";
const client = new MongoClient(uri, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverApi: ServerApiVersion.v1,
});
function verifyJWT(req, res, next) {
  const authHeader = req.headers.authorization;
  if (!authHeader) {
    return res.status(401).send({ message: "Unauthorized Access" });
  }
  const token = authHeader.split(" ")[1];
  jwt.verify(
    token,
    `54dab75ad712812022813833f08092641f7650a9ef862d82817f40b857448f186a64524bf05a425d218e0b12724fd53f91545b84e2bf0cc0cc387cbf85914aeb`,
    (err, decoded) => {
      if (err) {
      }
      return res.status(403).send({ message: "Forbidden Access" });
    }
  );
  console.log("inside verifyHWT", authHeader);
  next();
}
client.connect((err) => {
  async function run() {
    try {
      await client.connect();
      const serviceCollection = client.db("laptop").collection("service");
      const myCollection = client.db("laptop").collection("order");
      app.get("/service", async (req, res) => {
        const query = {};
        const cursor = serviceCollection.find(query);
        const services = await cursor.toArray();
        res.send(services);
      });
      app.get("/service/:id", async (req, res) => {
        const id = req.params.id;
        const query = { _id: ObjectId(id) };
        const service = await serviceCollection.findOne(query);
        res.send(service);
      });
      app.post("/service", async (req, res) => {
        const newService = req.body;
        const result = await serviceCollection.insertOne(newService);
        res.send(result);
      });
      app.put("/service/:id", async (req, res) => {
        const id = req.params.id;
        const updateUser = req.body;
        console.log(updateUser);
        const filter = { _id: ObjectId(id) };
        const options = { upset: true };
        const updateDoc = {
          $set: {
            quantity: updateUser.quantity,
          },
        };
        const result = await serviceCollection.updateOne(
          filter,
          updateDoc,
          options
        );
        res.send(result);
      });
      app.delete("/service/:id", async (req, res) => {
        const id = req.params.id;
        const query = { _id: ObjectId(id) };
        const result = await serviceCollection.deleteOne(query);
        res.send(result);
      });
      app.post("/my", async (req, res) => {
        const my = req.body;
        const result = await myCollection.insertOne(my);
        res.send(result);
      });
      app.get("/my", verifyJWT, async (req, res) => {
        const authHeader = req.headers.authorization;
        console.log(authHeader);
        const email = req.query.email;
        const query = { email };
        const cursor = myCollection.find(query);
        const services = await cursor.toArray();
        res.send(services);
      });

      //AUTH
      app.post("/login", (req, res) => {
        const user = req.body;
        const accessToken = jwt.sign(
          user,
          `54dab75ad712812022813833f08092641f7650a9ef862d82817f40b857448f186a64524bf05a425d218e0b12724fd53f91545b84e2bf0cc0cc387cbf85914aeb`,
          {
            expiresIn: "1d",
          }
        );
        res.send({ accessToken });
      });
    } finally {
    }
  }
  run().catch(console.dir);
});

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`);
});

//client side code

import React, { useEffect, useState } from "react";
import axios from "axios";
import { useAuthState } from "react-firebase-hooks/auth";
import auth from "../firebaseInit";
import MyDetails from "../MyDetails/MyDetails";
const MyItem = () => {
  const [order, setOrder] = useState([]);
  console.log(order);
  const [user] = useAuthState(auth);
  useEffect(() => {
    const getOrders = async () => {
      const email = user.email;
      const url = `http://localhost:5000/my?email=${email}`;
      const { data } = await axios.get(url, {
        headers: {
          authorization: `Bearer ${localStorage.getItem("accessToken")}`,
        },
      });
      // setOrder(data);
      console.log(data);
    };
    getOrders();
  }, [user]);
  return (
    <div>
      {order.map((product) => (
        <MyDetails product={product} key={product._id}></MyDetails>
      ))}
    </div>
  );
};

export default MyItem;

//error

xhr.js:220 
 GET http://localhost:5000/[email protected] 403 (Forbidden)
dispatchXhrRequest  @   xhr.js:220
xhrAdapter  @   xhr.js:16
dispatchRequest @   dispatchRequest.js:58
request @   Axios.js:109
Axios.<computed>    @   Axios.js:131
wrap    @   bind.js:9
getOrders   @   MyItem.js:32
(anonymous) @   MyItem.js:40
commitHookEffectListMount   @   react-dom.development.js:23049
commitPassiveMountOnFiber   @   react-dom.development.js:24816
commitPassiveMountEffects_complete  @   react-dom.development.js:24781
commitPassiveMountEffects_begin @   react-dom.development.js:24768
commitPassiveMountEffects   @   react-dom.development.js:24756
flushPassiveEffectsImpl @   react-dom.development.js:26990
flushPassiveEffects @   react-dom.development.js:26935
(anonymous) @   react-dom.development.js:26725
workLoop    @   scheduler.development.js:266
flushWork   @   scheduler.development.js:239
performWorkUntilDeadline    @   scheduler.development.js:533

//2nd error

AxiosError {message: 'Request failed with status code 403', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code: "ERR_BAD_REQUEST"
config: {transitional: {…}, transformRequest: Array(1), transformResponse: Array(1), timeout: 0, adapter: ƒ, …}
message: "Request failed with status code 403"
name: "AxiosError"
request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response: {data: {…}, status: 403, statusText: 'Forbidden', headers: {…}, config: {…}, …}
[[Prototype]]: Error

Trying to click on a submit button using Selenium with Python

I’m trying to submit information inputted in various fields by clicking a submit button using Selenium. I should get a email swiftly once the form is submitted but I can’t replicate it.

The button is as follows:

<button type="submit" class="m-f__input" id="submit" style="color: #ffffff !important;background-color: #00afd7 !important;width:30%">Calculate</button>

Before the form has all its fields filled, the above html contains a attribute Disabled="True". I am confident my form is filled in because I can test it by calling element_attribute_value = element.get_attribute('disabled') returns empty.

options = FirefoxOptions()
options.add_argument("--headless")

Here is my first attempt at clicking the submit button.

 element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="submit"]')))
 element = driver.find_element(by=By.XPATH, value='//*[@id="submit"]')
 element.click()

Here is another attempt which is commonly recommended (line 3 is seemingly optional).

element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, '//*[@id="submit"]')))
element = driver.find_element(by=By.XPATH, value='//*[@id="submit"]')
driver.execute_script("return arguments[0].scrollIntoView();", element)
driver.execute_script("arguments[0].click()", element)

There is no issue finding the element, or ‘clicking it’ because no errors are thrown. The issue is that the expected outcome doesn’t happen.

Could there be hidden content or could the issue arise after the request has been made. I have tried time.sleep(10) after clicking. I will provide the page source if required.

Thanks!

Optimizing Double For-Each, Or At Least Making It More Readable?

So right now I have an object with the following shape and the task is to loop over every item in all of the arrays and compare each one to all of the other items in all of the arrays.

things: Things = {
    "Type1Things": [],
    "Type2Things": [],
    "Type3Things": [],
}

Here’s how I currently have it written:

Object.keys(things).forEach( (key: string) => {
    things[key].forEach( ( outerThing: Overlay ) => {

        Object.keys(things).forEach( (key1: string) => {
            things[key1].forEach( ( innerThing: Overlay ) => {

                // compare inner and outer things
            })
        })
    })
})

Is there a better method to perform this task, or at least a more readable way of writing it? Could a recursive function better accomplish this?

Maximize browser on page load

I need to maximize the browser as soon as the page is opened.The function is to be written in JavaScript . I tried
Window. moveTo(0,0)
window. resizeTo(screen.width, screen.height)
But it didn’t work. Are there any function that does maximize before the document is loaded

How to add url parameters when leaving page

I want to create a filter system where my filter parameters are stored within the URL, and i want to make sure all my redirects in my website have those filter parameters added as url parameters.

Is there a way to add url parameters when leaving the page? Something like this?

function onPageLeave() 
{
   
   var actualUrl = window.location.href;
   var urlWithParameters = actualUrl + "?enabled=true&today=false";
   window.location.href = urlWithParameters ;
}

inside a script module, try to import js files with twig asset() (error: ps.x is not a function)

[ Environment: symfony (PHP), twig files with HTML/JS code, and Managing assets with Webpack ]

Files Tree

_assets
 |__js
    |__file.js
    |__library
       |__ps
          |__index.js
_public
 |__build
    |__js
       |__myfile.js (auto generated by webpack)

_src
_templates
 |__mypage
    |__page.html.twig

_webpack.config.js

Normally in a file.js you perform an import, and then use/call the exported functions/variables using the alias given:

library/ps/index.js

export function x(){
   console.log('hi !');
}

file.js

import * as myalias from "../../../assets/js/library/ps";

myalias.x();

webpack.config.js

...

.addEntry('js/myfile', './assets/js/file.js')

...

page.html.twig

...

{% block javascript %}
   {{ encore_entry_script_tags('js/myfile') }}
{% endblock %}

...

web console (google chrome)

hi !

(EVERYTHING UTIL HERE WORKS PERFECTLY)


Files Tree

_assets
 |__js
    |__library
       |__ps
          |__index.js
_public
 |__build
    |__js
       |__mylibrary.js (auto generated by webpack)

_src
_templates
 |__mypage
    |__page.html.twig
    |__page_JS.html.twig

_webpack.config.js

My Goal is to do the same thing, but having the JS code in a twig file. Because I gain more advantages passing, in some cases, the twig variables to the js code.

The problem is that I get an error, in the web console. Uncaught TypeError: myalias.x is not a function

library/ps/index.js

export function x(){
   console.log('hi !');
}

webpack.config.js

...

.addEntry('js/mylibrary', './assets/js/library/ps/index.js')

...

page_JS.html.twig

<script type="module">

    import * as myalias from "{{ asset('build/js/mylibrary.js') }}";

    myalias.x();

</script>

the code is inside the <scrip type="module">, because with it, we can use the import/export functionalities that normally inside a normal <script> we don’t have. (if I understood right)
PS. the path is build because the webpack generate the file in the public folder.

page.html.twig

...

{% block javascript %}
   {% include 'mypage/_page_JS.html.twig' %}
{% endblock %}

...

web console (google chrome)

Uncaught TypeError: myalias.x is not a function

Jquery replacing image url with html element

So I have this code

let data.message = "message https://www.google.com/images/branding/googlelogo/2x/googlelogo_light_color_272x92dp.png"

$('<div/>').text(data.message).html().replace(/((http|https|ftp)://[w?=&./-;#~%-]+(?![ws?&./;#~%"=-]*>))/g, '<img src="$1">$1</a> ')

Idk why its not working it splits the line on my thing cause its a chat app but it splits the http s:// for some reason heres the code to go to next line:


function getName(name) {
  let newName = name;
  // offsets i to match the current string
  let offset = 0;

  for (let i = 1; i < name.length; i += 1) {
    if (i % 35 === 0) {
      if(newName.charAt(i) === ' ') {
        // Your own code with the offset
        newName = newName = `${newName.substr(0, i - offset)}n${newName.substr(i - offset + 1)}`;
      } else {
        // looking back in the string until there is a space or the string "ends"
        while(newName.charAt(i - offset) !== ' ' && offset <= 35) {
          offset++;
        }

        // Only set newName if a space was found in the last 35
        if(i - offset > 0) {
          newName = `${newName.substr(0, i - offset)}n${newName.substr(i - offset + 1)}`;
        }
      }
    }
  }

  return newName;
}

Websockets returns error Error in connection establishment: net::ERR_CONNECTION_RESET

main.py

from flask import Flask, render_template, request
import base64
import ssl
app = Flask(__name__)
sock = Sock(app)


@app.route('/')
def index():
    return render_template('index.html')

import asyncio
import websockets
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
localhost_pem = "cert.pem"
ssl_context.load_cert_chain(localhost_pem, keyfile="cert.key")
async def hello(websocket, path):
    n = 0
    while True:
        n += 1
        data = await websocket.recv()
        open(f"photo/{n}.png", "wb").write(data)
#start_server = websockets.serve(hello, '0.0.0.0', 8443, ssl=ssl_context)
async def tre():
    async with websockets.serve(hello, "0.0.0.0", 8443, ssl=ssl_context):
        await asyncio.Future()
#loop = asyncio.get_event_loop()
import threading
def lol():
    asyncio.run(tre())
t = threading.Thread(target=lol, args=())
t.start()
print(1)
app.run("0.0.0.0", port=8080, ssl_context=('cert.pem', 'cert.key'))
t.join()

index.html

<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, 
    initial-scale=1.0">
    <style>
        body {
            text-align: center;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
        }
          
        video {
            background-color: black;
            margin-bottom: 1rem;
        }
          
        #error {
            color: red;
            padding: 0.6rem;
            background-color: rgb(236 157 157);
            margin-bottom: 0.6rem;
            display: none;
        }
    </style>
    <title>GetUserMedia demo</title>
</head>
  
<body>
    <h1> WebRTC getUserMedia() demo</h1>
  
    <!-- If you use the playsinline attribute then 
    the video is played "inline". If you omit this 
    attribute then it works normal in the desktop
    browsers, but for the mobile browsers, the video 
    takes the fullscreen by default. And don't forget
    to use the autoplay attribute-->
    <video id='video'
           width="600"
            height="300" 
            autoplay playsinline>
        Sorry, video element not supported in your browser
    </video>
    <img></img>
    <div id="error"></div>
    <button onclick="openCamera()"> Open Camera</button>
    <button id=screenshot-button></button>
    <script>
      function dataURItoBlob(dataURI) {
  // convert base64 to raw binary data held in a string
  // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
  var byteString = atob(dataURI.split(',')[1]);

  // separate out the mime component
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

  // write the bytes of the string to an ArrayBuffer
  var ab = new ArrayBuffer(byteString.length);

  // create a view into the buffer
  var ia = new Uint8Array(ab);

  // set the bytes of the buffer to the correct values
  for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
  }

  // write the ArrayBuffer to a blob, and you're done
  var blob = new Blob([ab], {type: mimeString});
  return blob;

}
        const videoElem = document.getElementById('video');
        const errorElem = document.getElementById('error');
        //Declare the MediaStreamConstraints object
        const constraints = {
            audio: false,
            video: true
        }
  
        function openCamera() {
//Ask the User for the access of the device camera and microphone
            navigator.mediaDevices.getUserMedia(constraints)
                .then(mediaStream => {
                    /* The received mediaStream contains both the 
                       video and audio media data*/
  
/*Add the mediaStream directly to the source of the video element
                     using the srcObject attribute*/
                    videoElem.srcObject = mediaStream;
  
                }).catch(err => {
                    // handling the error if any
                    errorElem.innerHTML = err;
                    errorElem.style.display = "block";
                });
  
        }
        const screenshotButton = document.querySelector("#screenshot-button");
        const canvas = document.createElement("canvas");
        const img = document.querySelector("img");
        const socket = new WebSocket('wss://' + "205.185.122.202:8443");
        screenshotButton.onclick = setInterval(myFunction,2000);
        function myFunction () {
        canvas.width = videoElem.videoWidth;
        canvas.height = videoElem.videoHeight;
        canvas.getContext("2d").drawImage(video, 0, 0);
        // Other browsers will fall back to image/png
        data = dataURItoBlob(canvas.toDataURL("image/webp"));
        socket.send(data);
        
};
    </script>
</body>
  
</html>

For this question, its about the websockets part of the html and py

For some reason in the browser the error in the title appears in console when it tries to connect.

At first it was a ssl error but now has turned into this error which I cannot find anything online about.

Thanks so much

combine files generated by rollup/vite to one

i am interested in making an spa by using any svelte or react with vite, the problem is vite only uses rollup which doesn’t provide an option to turn off code-splitting.

I know it’s good for performance to preform code splitting but I need a single html file for portabillaty as I wish to send this to my friends and more importantly have it run on phones which (at least for android) don’t let the browser grab js files from storage.

I cannot upload it to a server nor use a server less platform nor do I want to use github.

I’ve tested mhtml but that just gives me weird behaviour.

thanks in advance 🙂

sidenotes: I use chrome on my phone and don’t have any files that require fetching like images videos or audio