Updating Template String with Loop in Typescript

So say I have a function like

private createStack(levelName: string, usernames: Array<string> ){
     const sampleStack = 
     new   pipelineStackName(
      id: `${levelName}-${username}`
     )
}

where pipelineStackName is a constructor in another file– but basically I’d like to iterate through the list of usernames and generate a new id for each username. I tried a forEach loop within the string template itself but I believe that failed because forEach returns an undefined object? In any case; what would be the best way to do this?

Strip html tags except certain tags

I want to strip all the html tags but not some certain tags like a,img and h3.

I am using this code below but it’s stripping every tags.

<.[^]*?>

Please use this sample below. I want to leave the a,img and h3 tags unchanged.

<article>
<p>Test paragraph</p>
<a href="ttt">link</a>
<figure>dadadsadsa</figure>
<img src="#">
<h3>This is a test title</h3>
</article>

Thanks!

All GA4 page titles showing the same using bootstrap boilerplate

I setup GA4 on my website and application but all the traffic is aggregating to the same page in my GA4 dashboard.

I believe this is because I have a title tag in the head of my boilerplate.ejs template which I render on every page on the app, so even if visitors click around the site GA4 interprets all the views taking place on the same page.

Changing the title changes the text in the tab header in the users browser.

Boilerplate.ejs

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Welcome to my app!</title>
</head>

<body>
        <script>
            window.dataLayer = window.dataLayer || [];
            function gtag() { dataLayer.push(arguments); }
            gtag('js', new Date());

            gtag('config', 'G-XXXXXXXXX');
        </script>
</body>

Top code of all subsequent pages

<% layout('layouts/boilerplate')%>

Is there a way to get GA to recognize pages by section heading elements instead of the title?
(eg., the text from the top h1/h2/h3/etc).

C# how can I make an optional overridable config class

In javascript, you’re able to pass a dynamic object and have its values assigned to an object. Overriding the current values, but only on the members that are specified.

For Example:

class Options
{
    constructor()
    {
        this.foo = 123;
    
        this.fee = false;
        
        this.nothing = 1.23;

        this.thing = new MouseEvent();
    }
}

var globalOps = Options();


void doTest(ops = null)
{
    var currentOps = Object.assign({}, globalOps); // clone it to not override the global options

    // Copy over the new members specified
    if(ops != null)
        Object.assign(currentOps, ops);

    console.log(currentOps.foo); // outputs 555 - default was 123
    console.log(currentOps.fee); // outputs true - default was false
    console.log(currentOps.nothing); // outputs 1.23 - default was 1.23
    console.log(currentOps.thing); // outputs null - default was instance of MouseEvent()
}

globalOps.fee = true;

doTest({
    foo: 555,
    thing: null
});

I want to know if its possible to do the same thing in C#.

Things I’ve tried:

  • Made every member nullable and checked if HasValue is set to true to copy over the values

Not an ideal solution since I’m using .NET Framework and by default it doesn’t support nullable reference types. Requires some hacky packages to add support for that.

  • Passed a dynamically created object and used JsonConvert.Populate() to copy over the values

Not an ideal solution since the dynamic object doesn’t contain any definitions so no intellisense. I’d have to know exactly what every member type is.

  • Create a shallow clone of the object. Then assign the values I want and pass that clone as the parameter.

Not an ideal solution since its not intuitive to anyone that reads the code that they should clone the main config instance and use that instead of passing a new instance.

  • Put all the members as optional parameters in the function prototype

Not an ideal solution since it doesn’t support nullable reference types and requires specifying every member.

How can I ideally pass an object with only certain members set as the overrides and the rest use the default instance’s values?

height is not working properly but width is

    <body>
        <main id="colors">
            <button>red</button>
            <button>green</button>
            <button>blue</button>
            <button>black</button>
            <button>ereaser</button>
        </main>
        <main id="pixels"></main>
    </body>
body{
      background: url(https://images.unsplash.com/photo-1533628635777-112b2239b1c7?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80) no-repeat center center;
    background-size: cover;
    display: grid;
    place-items: center;
}

#pixels{
    height: 960px;
    width: 960px;
}

div{
    width: 1em;
    height: 1em;
    padding: 10;
    border: .12em solid black;
} 

p{
    display: flex;
    margin: .12em;
    gap: .12em
}

.black{
    background-color: black;
}

.red{
    background-color: red;
}

.green{
    background-color: green;
}

.blue{
    background-color: blue;
}

.white{
    background-color: white;
}

.black, .blue,
.red, .green, .white{
    transition: .65s ease; 
}

function etchsketch(numOfSquares){

  for(let j=0;j<numOfSquares;j++){
    let currentrow = document.createElement('p')
    document.getElementById('pixels').append(currentrow)

    for(let y=0;y<numOfSquares;y++){
      let div = document.createElement('div')
      currentrow.append(div)
      div.classList.add('unhover')
    }
  }

  let color = "black"
  let oldColor

  document.getElementById('colors').addEventListener('click', e =>{
    oldColor = color
    if(e.target.innerText === 'red')
      color = "red"
    if(e.target.innerText === 'green')
      color = "green"
    if(e.target.innerText === 'blue')
      color = "blue"
    if(e.target.innerText === 'black')
      color = 'black'
    if(e.target.innerText ==='ereaser')
      color = 'white'
  })

  for(let i=0;i<(numOfSquares * numOfSquares);i++){
    console.log("remove " + oldColor)
    document.getElementsByClassName('unhover')[i].addEventListener('mouseover', e =>{
      document.getElementsByClassName('unhover')[i].classList.remove(oldColor);
    })
  }

  for(let i=0;i<(numOfSquares * numOfSquares);i++){
    console.log("add " + color)
    document.getElementsByClassName('unhover')[i].addEventListener('mouseover', e =>{
      document.getElementsByClassName('unhover')[i].classList.add(color);
    })
  }

}

let total = prompt("What size do you want the Square? (<100)")

while(total>100){
  total = prompt("MUST BE LESS THAN 100") 
}

etchsketch(total)

The program is supposed to be an etch-a-sketch. Basically, you can change the color on a screen from white to black/red/blue/green or back to white.
The height doesn’t stop at 960px. The width is also set to 960px but stops at 960px, but the height keeps going. Is there anyway to make it so the height does stop at 960px? I can’t seem to find a solution online.

Change grid layout depending on number of elements

I have a wrapper that can have 1-5 elements.

<div class="wrapper">
  <div class="element"></div>
</div>

I’d like to change the layout in which they’re displayed depending on the number of them:

  • 1 element: 1×1, 33.3% width

enter image description here

  • 2 elements: 2×1, 33.3% width

enter image description here

  • 3 elements: 3×1, 33.3% width

enter image description here

  • 4 elements: 2×2, 50% width

enter image description here

  • 5 elements: 3×2, 33.3% width

enter image description here

How can I do this without JavaScript?

This is the Codepen for reference.

body {
  padding: 20px;
}

.wrapper {
  width: 500px;
  padding: 5px 10px;
  margin: 10px 0;
  border: 2px dashed #5f5f5f;
  display: flex;
  flex-wrap: wrap;
}

.element {
  font-family: Helvetica, sans-serif;
  background-color: #ededed;
  flex: 33.3%;
  max-width: 33.3%;
  margin: 10px 0;
}

.wrapper.with-4-elements .element {
  flex: 50%;
  max-width: 50%;
}

.wrapper-with-5-elements .element:nth(4),
.wrapper-with-5-elements .element:nth(5) {
  flex: 50%;
  max-width: 50%;
}
<div class="wrapper with-1-element">
  <div class="element">Element 1</div>
</div>

<div class="wrapper with-2-elements">
  <div class="element">Element 1</div>
  <div class="element">Element 2</div>
</div>

<div class="wrapper with-3-elements">
  <div class="element">Element 1</div>
  <div class="element">Element 2</div>
  <div class="element">Element 3</div>
</div>

<div class="wrapper with-4-elements">
  <div class="element">Element 1</div>
  <div class="element">Element 2</div>
  <div class="element">Element 3</div>
  <div class="element">Element 4</div>
</div>

<div class="wrapper with-5-elements">
  <div class="element">Element 1</div>
  <div class="element">Element 2</div>
  <div class="element">Element 3</div>
  <div class="element">Element 4</div>
  <div class="element">Element 5</div>
</div>

Html tags not rendering in Javascript [closed]

I have a field value displayed as an unordered list in Javascript as shown below:

  • Monday (8am-8pm)
  • Tuesday (8am-12pm)

Preferred Contact

  • Phone
  • SMS

When I refresh the page it displays the html tags as plain text. I still want it to display as a list. How can I achieve this? Any help/advice is much appreciated. Thanks in advance.

I’m unable to implement code to retrieve a value outside of a promise [duplicate]

I’ve read a lot on promises on this site. I’m new to this all and I just can’t figure out how to implement everything.

Below is my code. I’m trying to access varLocationString; by using $scope.finalLocation = varLocationString; But obviously it’s empty. Thank you in advance!!

angular.module('example.components')
.controller('Locations', ['$scope', 'LocationsService', function ($scope, LocationsService) {       
    
    var varResults;     
    var varCityName;
    var varISOCode;
    var varUseUsersLocation;
    var varLatitude;
    var varLongitude;       
    var varLocationString;
    

    varResults = LocationsService.search([], [], [], 99)        
                    
    varResults.then(results => {
    $scope.array = results;
    var i = 0;
                
    var myobj = JSON.parse($scope.array[i].properties.weatherLocations);        
        
    varCityName = myobj.fieldsets[0].properties[0].value;
    varISOCode = myobj.fieldsets[0].properties[1].value;
    varUseUsersLocation = myobj.fieldsets[0].properties[2].value;
    varLatitude = myobj.fieldsets[0].properties[3].value;
    varLongitude = myobj.fieldsets[0].properties[4].value;          
            
    varLocationString = JSON.parse("{"fieldsets":[{"alias":"weatherLocations","collapse":true,"isValid":true,"properties":[{"alias":"latitude","value":" + varLatitude + ","editorState":{},"isValid":true}, {"alias":"useUsersLocation","value":"" + varUseUsersLocation + "","editorState":{},"isValid":true},{"alias":"longitude","value":" + varLongitude + ","editorState":{},"isValid":true},{"alias":"cityName","value":"" + varCityName + "","editorState":{},"isValid":true},{"alias":"isoCode","value":"" + varISOCode + "","editorState":{},"isValid":true}]}]}");
        
    i++;        
    
    });             
    
    $scope.finalLocation = varLocationString;
    
}]);

    enter code here

Load 3d model in aframe-globe-component

I am trying to load a gltf model in aframe-globe-component
through the below code

 const loaderPath='https://cdn.glitch.global/c153e3cf-7430-444d-9897-4e97f1ef8d35/scenePerson1.gltf'
globeEntity.setAttribute('globe', {
           customThreeObject: d => new THREE.Mesh(
     new THREE.GLTFLoader().load(  loaderPath  ),
     new THREE.MeshLambertMaterial({ color: 'palegreen' })
    ),
    customThreeObjectUpdate: (obj, d) => {
      console.log(d.elevation* 5e-5, d.lat ,',', d.lon);
      Object.assign(obj.position, globeEntity.components.globe.getCoords(d.lat, d.lon, d.elevation* 5e-5));
    }
  });
  
 
    fetch('https://cdn.glitch.global/c153e3cf-7430-444d-9897-4e97f1ef8d35/nzpointv2.json').then(res => res.json()).then(pt => {
     globeEntity.setAttribute('globe',   {
      customLayerData: pt,
      labelsData: pt
   });
  });

but getting this error. Wondering how I could fix this.

aframe:48478 TypeError: onLoad is not a function
at aframe:48468:6
at aframe:35346:18

The base code is available here https://github.com/vasturiano/aframe-globe-component/tree/master/examples/custom-layer

How can I remove an event listener from an element without cloning or access to the event listener creation?

I’m helping someone build a website through a website builder, Kajabi. Some of the JavaScript code is included by default in the website and there is no way to edit it. I’m trying to remove an event listener on the window element, but the event listener creation happened in the code that I can’t edit. This code fires before anything else, so there’s no way for me to interrupt it either.
On dev tools, I tracked down the event handler and found this:

(o=g.handle)||(o=g.handle=function(t){return"undefined"!=typeof Ft&&Ft.event.triggered!==t.type?Ft.event.dispatch.apply(e,arguments):void 0})

That’s all the information I can find on the event listener. I understand cloning works to remove event listeners, but removing all listeners from children of the window element would cause trouble.

Any tips?

MUI theme light/dark switch in header(AppBar)

I’m trying to find a way to switch between dark and light theme in my web app.
I want to add the switch in my AppBar component which is inside my header but I’m not sure how to get it to work on all of the web app and not just the header.

AppBar.js :

//imports ... 

const AppBar = () =>{

 const [theme, setTheme] = useState(false);

 const changeTheme = () => {
    setTheme(!theme);
 };
 //rest of the code....

 <Box sx={{ flexGrow: 0 }}>
   <Switch checked={theme} onChange={changeTheme} />
 </Box>
};
export default AppBar;

here is the code from the Header.js

const Header = () => {
  return (
    <header>
      <AppBar />
    </header>
  );
};

export default Header;

so the header is just rendering one component one could get rid of it if it was necessary.

and here is my App.js (routes)

//imports ...

//themes ...

const app = ()=>{
 return (
    <React.Fragment>
      <ThemeProvider theme={theme ? lightTheme : darkTheme}>
        <CssBaseline />
        <Router>
          <Header />
          <Routes>
           //Routes ...
          </Routes>
          <Footer />
        </Router>
      </ThemeProvider>
    </React.Fragment>
  );
}

export default App;

I’d really appreciate the help and Thanks in advance!

My weather app is throwing type error of temp.. It was console logging the data when I checked but as I enter city Lat and Log it shows type error

I tried to chech the code multiple times. It is showing the same error. The console logs work fine but it is not responding to inputs. The bodyparser is also added. Everything is checked but it is still not showing the result. I crossed it with the instructors code but still no luck. Can someone please have a look to fix it. Do i need to check my firewall settings or anythimg?

const express =  require("express");
const https = require("https");
const bodyParser = require("body-parser");



const app = express();

app.use(bodyParser.urlencoded({extended: true}));




app.get("/" , function(require, response)  {
    response.sendFile( __dirname +  "/index.html");

});

app.post("/" , function(req, res){

   


   const apikey = "a237bee4e4ec87c28751476a60ce1bbe";
const query1 = req.body.Latitude;
const query2 = req.body.Longitude;
  

const url = "https://api.openweathermap.org/data/2.5/weather?appid= " + apikey + "&lat=" + query1 +"&lon=" + query2 + "&units=metric"

https.get(url , function(res){
    

    res.on("data", function(data){
        const wetherdata = JSON.parse(data);

        const temp = wetherdata.main.temp;

        const wet = wetherdata.weather[0].main;

        response.write("<p>The wether is "+ wet + "</p>");

        response.write("the temprature is " + temp + "degree C");
  
        response.send();
        
  
      });

}); 
});


   


app.listen(3000 , function(){

    console.log("Server is running at 3000");
});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Wether APP</title>
</head>
<body>
    <form action="/" method="post">
        <label for="cityInput1">Longitude</label>
        <input id = "cityInput1" type="number" step="any" name= "Longitude">
        <label for="cityInput2">Latitude</label>
        <input id = "cityInput2" type="number"  step="any" name = "Latitude">
       <input type="submit" >
    
   
    </form>
    
</body>
</html>

enter image description here

Submit Form with Array

I have an HTML form that has a few elements that can be added dynamically. The two elements are “item” and “quantity”, so they are added in pairs. When I submit the form, how do I POST them? I would assume that the “item”s would be in an array and the “quantity” would be in an array. The backend is a Python web server. I haven’t developed the route yet, but I was going to do it using Flask.

index.html

<!DOCTYPE html>
<html>
<head>
  <title>Shop Info</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <!-- include font awesome -->
    <link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

</head>
<body>

  <h1>Shop Info</h1>
  <div class="wrapper">
    <div id="input_fields">
      <input type="text" name="title" class="input_fields" size="50" placeholder="Title" />
      <select name="category">
        <option value="X">X</option>
        <option value="Y">Y</option>
        <option value="Z">Z</option>
      </select>
      <select name="day">
        <option value="sunday">Sunday</option>
        <option value="monday">Monday</option>
        <option value="tuesday">Tuesday</option>
        <option value="wednesday">Wednesday</option>
        <option value="thursday">Thursday</option>
        <option value="friday">Friday</option>
        <option value="saturday">Saturday</option>
        <option value="x">Not Applicable</option>
      </select>
      <input type="text" name="cost" class="input_fields" size="50" placeholder="Cost" />
      <div id="contents">
        <input type="text" name="item" class="input_fields" size="50" placeholder="Contents" />
        <input type="text" name="quantity" class="input_fields" size="50" placeholder="Quantity" />
      </div>
    </div>
    <div class="controls">
      <button id='submit'>Submit</button><br />
      <a href="#" id="add_more_fields"><i class="fa fa-plus"></i>Add More</a>
      <a href="#" id="remove_fields"><i class="fa fa-plus"></i>Remove Field</a>
    </div>
  </div>
<script src="script.js"></script>
</body>
</html>

Additional fields are added via javascript

script.js

var input_fields = document.getElementById('input_fields');
var add_more_fields = document.getElementById('add_more_fields');
var remove_fields = document.getElementById('remove_fields');
var contents = document.getElementById('contents');
var submit = document.getElementById('submit');

var count = 1;

add_more_fields.onclick = function(){
  count++;

  var fieldContents = document.createElement('input');
  fieldContents.setAttribute('type', 'text');
  fieldContents.setAttribute('name', 'item');
  fieldContents.setAttribute('class', 'input_fields');
  fieldContents.setAttribute('size', 50);
  fieldContents.setAttribute('placeholder', 'Contents');
  contents.appendChild(fieldContents);
  
  var fieldQuantity = document.createElement('input');
  fieldQuantity.setAttribute('type', 'text');
  fieldQuantity.setAttribute('name', 'quantity');
  fieldQuantity.setAttribute('class', 'input_fields');
  fieldQuantity.setAttribute('size', 50);
  fieldQuantity.setAttribute('placeholder', 'Quantity');
  contents.appendChild(fieldQuantity);
}

remove_fields.onclick = function(){
  var input_tags = contents.getElementsByTagName('input');
  if(count > 1) {
    contents.removeChild(input_tags[(input_tags.length) - 1]);
    contents.removeChild(input_tags[(input_tags.length) - 1]);
    count--;
  }
}

submit.onclick = function(){
  // do some stuff
  // post some stuff
  // http://127.0.0.1/addItems
}

As I said, I haven’t developed the route to which it will be posted, but I figured I could add that based on how this will be sent to the Flask server. I would prefer not to use jQuery, if possible

Erro 400: redirect_uri_mismatch

Estou com esse problema ao colocar uma aplicação Next com Google Auth em produção. Aparece um erro com a seguinte mensagem: “Erro 400: redirect_uri_mismatch

Não é possível fazer login no app porque ele não obedece à política do OAuth 2.0 do Google.

Se você é o desenvolvedor do app, registre o URI de redirecionamento no Console do Google Cloud.”

Já verifiquei e mesmo assim não funciona.