I’m having trouble removing an item from localStorage for my tasklist app which i’m building using vanilla javascript

Here’s a function i’m having trouble with the foreach loop traverses just fine but i’m having trouble removing item from localStorage.

function removeFromLocalStorage(taskItem) {
  let tasks;
   if (localStorage.getItem("tasks") === null) {
      tasks = [];
   } else {
      tasks = JSON.parse(localStorage.getItem("tasks"));
   }

   tasks.forEach((task, index) => {
      if (task === taskItem) {
      tasks = localStorage.removeItem(task);
      }
  });
  }

How to loop over a field’s value one after another and do aggregation operations on it?

I recently started working with MongoDB and its aggregation pipeline. I need some help with looping over the field called Id and doing aggregation operation on it one after another directly inside pipeline.

Currently I am doing something like this (in Node.js):

let patients = await client.db('MyDB').collection('Patients_MA').find().toArray();

for (int i=0; i<patients.length; i++)
{
    doc = patientColl.aggregate([
      {
        $match: {Id: patients[i].Id}
      }, 
      {
        $project: {
          _id: 0, 
          num: {
            $add: [
              {$multiply: [0.7, 2]},
              {$multiply: [0.2, 2]},
              {$multiply: [0.15, 0]}
            ]
          }
        }
      }
    ]);

    await patientsColl.updateOne(
        { "Id": id },
        { "$set": {'heuristic': num} }
    );
}

For the sake of easy understanding I have condensed the pipeline to just the main thing I want it to do which is to update the heuristic value but in my original pipeline, each Id will have a different heuristic value. Also, I have approximately 8000 patients Ids and in my original pipeline, I am working with 3 different collection.

So my question is, is there a way to loop over each Id‘s, run the the pipeline above, and update the heuristic value directly inside the aggregation pipeline? Or a way to do this more efficiently without having to make O(8000) calls?

How can i see kendo grid column menu actions on console

I have grid with dynamic data and when i change colunms from column menu i want to write column state or selected columns on my console. Is it possible?

Here is example grid

<kendo-grid [data]="gridView" filterable="menu" [columnMenu]="true" 
        (filterChange)="filterChange($event)" [filter]="value" height="600">
     <kendo-grid-column field="pump">
        PUMP
     </kendo-grid-column>
     <kendo-grid-column field="nozzle" filter="number">
        NOZZLE
     </kendo-grid-column>
     <kendo-grid-column field="item">
        ITEM
     </kendo-grid-column>
  </kendo-grid>

Here is how to load data

this.service.getData().pipe(take(1)).subscribe(res => {
      this.loading = false;
        this.gridData = res.result.nozzles

        this.gridView = {
          data: this.gridData,
          total: this.gridData.length,
        };
    })

Thanks

How would I unzip a zip file in node

I would like to unzip a .zip file in node without any libraries. How would i go about doing this?

I have tried using zlib but it returns incorrect header type

let zipfile = fs.readFileSync(fileinfomation.savelocation)   
zlib.gunzipSync(zipfile)

Replacing single quote from a string

I have a string with contain some single quote, I want to replace all the single quote present inside string with double quote excluding the single quote preset inside {} [] () . Any pointer will be really helpful trying to solve this using JAVASCRIPT.

Actual String :

let str =`name:'John' {hobbies:'Playing'} , (age: '45')`;
console.log(str);

Expected Output:

name:”John” {hobbies:’Playing’} , (age: ’45’)

How to find given array is cyclic or not?

Is array is cyclic or not ?

case 1:-

tasks: [“a”,”b”]

dependencies: [“a:b”]

result: Not cyclic

explanation : first “b” executes that “a” executes

case 2:-

tasks: [“a”,”b”,”c”]

dependencies: [“a:b”,”b:c”,”c:a”]

result: cyclic

explanation : a dependent on b , b dependent c again c dependent on a (looping)

case 3:-

tasks: [“a”, “b”, “c”,’d’,’e’]

dependencies: [“a:b”, “c:d”,’d:e’,’e:c’]

result: cyclic

explanation : c->d, d->e, e->c (loop)

Following is my code and it is not working for cyclic . someone please help me in this

 const cyclicOrNot = () => {

    var tasks = ["a", "b", "c",] ,
    dependencies = ["a:b","b:c", "c:a",], result = []
    var found = false

    dependencies.map(i=>{
      var dependentitem = i.split(':')[0];
     var cyclicResult= checkCyclic(i,dependencies,dependentitem,found);
     console.log(cyclicResult)
      if(cyclicResult) {
        return "cyclic"
      }
      else {
        return "not cyclic"
      }

  })
}


  const checkCyclic = (i,dep,item,found) => {

    return  dep.every(d=>{
      if (i.split(':')[1]===d.split(':')[0]) {
        if(item===d.split(':')[0]){
          found = true
          return found
        }
        else {
          checkCyclic(d,dep,item,found);
        }
        return found
      }
    })
  }

How to loop through an array of objects and compare it with table data values?

My HTML table

            <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Average</th>
                </tr>
            </thead>

            <tbody id="tableBody">

            </tbody>
        </table>

Sample table generation

var arrayofObjects = [{sID: 025, name: John Doe, average: 80}, {sID: 893, name: Jane Smith, average: 82}];

    function loadTable() {
                let table = document.getElementById("tableBody");
                table.innerHTML = "";
                let tr = "";
                vararrayofObjects.forEach(x => {
                    tr += '<tr>';
                    tr += '<td><a data-toggle="modal" data-target="#myModal1" id="sIDNum">' + x.sID + '</a></td>' + '<td>' + x.name + '</td>' + '<td>' + x.average + '</td>';
                    tr += '</tr>'
                })
                table.innerHTML += tr;
            }

What I tried to get value of first column (sID) on click then loop through object array

const tableBody = document.querySelector('#tableBody');
        tableBody.addEventListener('click', (e) => {
            vararrayofObjects.forEach((element) => {
                if(element.sID == $('a').text()) {
                    var personName = element.name;
                    var personID = $('#sIDNum').text();
                    var personAvg = "Average " + element.average;
                }
            });
        });

Problem is that the if statement returns me all values of $('a').text()) instead of the one I clicked on. How do I properly implement it so that clicking on my anchor tag on the first column (sIDNum) will get its value, then use that value to loop through my object array and get the values of the object that matches with it?

How to convert txRaw to txHash in cosmos-sdk?

i am using api Cosmos SDK “https://api.cosmos.network/blocks/9888530” to get 1 block details

i get it txRaw: “CpMBCpABChwvY29zbW9zLmJhbmsudjFiZXRhMS5Nc2dTZW5kEnAKLWNvc21vczF0NXUwamZnM2xqc2pyaDJtOWU0N2Q0bnkyaGVhN2VlaHhyemRnZBItY29zbW9zMTNseWxmbHVzYTRwYXRtbDBsamt1ZzRsNjR4NXlsNDYwMzMwa2FlGhAKBXVhdG9tEgcyMDAwMDAwEmkKUgpGCh8vY29zbW9zLmNyeXB0by5zZWNwMjU2azEuUHViS2V5EiMKIQLqGodLEwWelzPDXpDLKlhlpGtk7ZDSVVR8B8pSOSf8YhIECgIIfxjw3iISEwoNCgV1YXRvbRIEMjUwMBCImAUaQNksf4cmAZodzcIEOwNNlFkK1zxGmE3Rtc2/f3JfIqG9HrbeVJhWjrIWizhmwGCYjhcbjpFpX8vCgGEwAyquwaM=”

How can i convert txRaw to txHash to use api get detail transaction has : https://api.cosmos.network/cosmos/tx/v1beta1/txs/8689064A44E7F2D6131ED15D014938EB772FD4DFD4348A71F525578E2895D612
Thanks for your help!

formData in React, getting null when I send formdata to backend Express

When I send data from the frontend I receive null in the backend. I am sending 2 string data URLs and dates so I don’t think that I need to use extra middleware for receiving the values.

Frontend:

    const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
        e.preventDefault()
        const today = new Date();
        const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
        const formData = new FormData();
        formData.append('url', url);
        formData.append('date', date);
        console.log(url, date);

        fetch('http://localhost:5000/shortUrls', {
        method: 'post',
        body: formData
    })
        .then(response => response.json())
        .then(data => {
            if (data.insertedId) {
                alert('Link Added')
                setLoadings(true)
            }
        })
        .catch(error => {
            console.error('Error:', error);
        });

    }

Backend:

// middleware
const app = express();
app.use(cors())
app.use(express.json())

app.post('/shortUrls', async (req, res) => {
            const uniqueUrl = shortId({ url: req.body.url })
            console.log(req);
            const details = {
                short: uniqueUrl,
                full: req.body.url,
                clicks: 0,
                date: req.body.date,
            }
            const result = await AffiliateLinksCollection.insertOne(details)
            res.json(result)
        })

why won’t express app.post render my view?

I’ve seen the same question posted, but not many helpful answers. I would like to render the welcome page once I’ve done content of the app.post, but nothing happens.

I know it’s valid as it will give me an error if i enter an invalid route, but it just will not do what i would like.

 app.get('/', function (req, res) {
    res.render('Welcome')
  })    
 
app.post('/makepost', function (req, res) {
    //do some things
    res.render('Welcome');
  })

In the View I use this to call the app.post.

fetch('/makepost', {
                    method: 'POST', 
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: body,
                }

Should I keep learning Flask or start with JavaScript? [closed]

I have a general knowledge about Python, that is the reason why I started to learn flask, but I don’t know why I keep thinking I am losing time in this when I could be learning JavaScript because I could do front and backend with js. Sometimes I get stuck with flask, and trying to figure out I waste a lot of time, maybe that time I could be learning JavaScript instead.

How properly round a numbers… Which method is a best in my case?

I need to round or fix it somehow, so the numbers comes out properly in the form.
I have tried to use toPrecision(), but I`ve newer done before and cant find a good understandable way to use it. Maybe some of u have an idea about this matter. Thanks. On the screenshot is my issue.

this is a problem I got

javascript file

const priceSmall = 4.00;
const priceMedium = 5.00;
const priceLarge = 7.00;
const priceToppings = 0.50; 
const pst = .07;
const gst = .07
let subtotal = 0;

////////////////Pizza size calculation///////////////
function calculateSize(element) {
  if (element == null) {
    return;
  }
  switch(element.value) {
    case "10":
      subtotal = priceSmall;
      break;
    case "12":
      subtotal = priceMedium;
      break;
    case "15":
      subtotal = priceLarge;
      break;
  }
    recalculateTotal();
}
/////////////Topping calculation////////////
function toppingOptionPrice(element) {
  if (element.checked) {
      subtotal += priceToppings;
  } else {
      subtotal -= priceToppings;
  }
    recalculateTotal();
}
  ////////////Total//////////////
function recalculateTotal() {
  let pstToPay = subtotal * pst;
  let gstToPay = subtotal * gst;
  let total = subtotal + pstToPay + gstToPay;

  document.getElementById("subtotal").value = subtotal.toFixed(2);
  document.getElementById("pstToPay").value = pstToPay.toFixed(2);
  document.getElementById("gstToPay").value = gstToPay.toFixed(2);
  document.getElementById("total").value = total.toFixed(2);
}

HTML in case need it

<!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>Pizza Order Form</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="scripts/script.js"></script>
<body>
    <header>
        <img src="media/pizza-served.jpg" width="600" height="277" alt="Pizza Logo"/>
        <h1>Pizza Order Form</h1>
    </header>
        <form id="myForm" name="myForm" method="post" action="http://lavalamp.dyndns.org/~mult114/pizzaorder_olympic.php" onsubmit="return validateForm();" target="_blank">

            <input type="hidden" name="difficulty" value="1" />
            <fieldset id="contactinfo">
                <legend style="font-size: larger;"><strong>Contact Information</strong></legend>
                    <label for="firstnameinput">First Name</label>
                    <input type="text" id="firstnameinput" name="FirstName_tf" /><br>
                    <label for="lastnameinput">Last Name</label>
                    <input type="text" id="lastnameinput" name="LastName_tf" /><br>
                    <label for="addrinput">Address</label>
                    <input type="text" id="addrinput" name="Address_tf" /><br>
                    <label for="phoneinput">Phone</label>
                    <input type="text" id="phoneinput" name="Phone_tf" /><br>
                    <label for="emailinput">Email Address</label>
                    <input type="email" id="emailinput" name="Email_tf" />
            </fieldset>
            <fieldset id="orderinfo">
                <legend style="font-size: larger;"><strong>Order</strong></legend>
                <fieldset id="pizzasize">
                    <legend>Pizza Size</legend>
                        <input type="radio" id="smallsize" name="Size_rg" value="10" onclick="calculateSize(this);">
                        <label for="smallsize">Small 10"</label><br>
                        <input type="radio" id="mediumsize" name="Size_rg" value="12" onclick="calculateSize(this);">  
                        <label for="mediumsize">Medium 12"</label><br>
                        <input type="radio" id="largesize" name="Size_rg" value="15" onclick="calculateSize(this);"> 
                        <label for="largesize">Large 15"</label>
                </fieldset>
                <fieldset id="toppingbox">
                    <legend>Topping(s)</legend>
                        <input type="checkbox" id="anchovies" name="Anchovies_cb" value="yes" onclick="toppingOptionPrice(this);">
                        <label for="anchovies">Anchovies</label><br>

                        <input type="checkbox" id="doublecheese" name="DoubleCheese_cb" value="yes" onclick="toppingOptionPrice(this);">
                        <label for="doublecheese">Double Cheese</label><br>

                        <input type="checkbox" id="pepperoni" name="Pepperoni_cb" value="yes" onclick="toppingOptionPrice(this);">
                        <label for="pepperoni">Pepperoni</label><br>

                        <input type="checkbox" id="mushrooms" name="Mushroom_cb" value="yes" onclick="toppingOptionPrice(this);">
                        <label for="mushrooms">Mushrooms</label><br>
                </fieldset>
                <fieldset id="instructions">
                    <legend>Special Instructions</legend>
                        <textarea id="textarea" name="instructions" rows="5" cols="50" placeholder="Enter your message here!(special requests, delivery details, etc.)"></textarea>
                </fieldset>
            </fieldset>
            <fieldset id="payments">
                <legend style="font-size: larger;"><strong>Payment</strong></legend>
                <label>Select Payment Method:</label>
                    <select id="paymethods" name="Payment_menu" required="required">
                        <option value="select">- Select One -</option>
                        <option value="cash">Cash</option>
                        <option value="debit">Debit</option>
                        <option value="credit">Credit Card</option>
                     </select>
            </fieldset>
            
            <fieldset id="calcprice">
                <legend style="font-size: larger;"><strong>Order Total</strong></legend>

                    <label for="subtotal">SubTotal $:</label>
                    <input type="text" id="subtotal" name="SubTotal_tb" readonly><br>
                    <label for="pstToPay">PST $:</label>
                    <input type="text" id="pstToPay" name="PST_tb" readonly><br>
                    <label for="gstToPay">GST $:</label>
                    <input type="text" id="gstToPay" name="GST_tb" readonly><br>
                    <label for="total">Total $:</label>
                    <input type="text" id="total" name="Total_tb" readonly><br>

            </fieldset>
            <input type="submit" name="Submit_but">
        </form>
        
</body>
</html>

Upload avatar into premade graphic and export div as png or jpeg

I would like to know if this is possible, i’ve been trying endlessly for the past few days and the HTML 2 Canvas library will save the div as png but the image thats uploaded never renders. if someone can help me.

Having a bit of trouble, I just want to create a div that has the premade graphic, where a user can upload their picture / avatar into and export the div as png or jpg after clicking a “screenshot / save button”

enter image description here

Please help

Libraries

https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js
https://superal.github.io/canvas2image/canvas2image.js
https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.min.js

HTML

    <div class="capturecontainer">
    <div class="container">
    <div class="avatar-upload">
        <div class="avatar-edit">
            <input type='file' id="imageUpload" accept=".png, .jpg, .jpeg" />
            <label for="imageUpload"></label>
        </div>
        <div class="avatar-preview">
            <div id="imagePreview" style="background-image: url(http://i.pravatar.cc/500?img=7);">
            </div>
        </div>
    </div>
</div>
  
  
        <button type="button" class="btn btn-default">Take a Screenshot!</button>
  
    </div>

CSS

 .avatar-upload {
     position: relative;
     max-width: 205px;
     margin: 50px auto;
}
 .avatar-upload .avatar-edit {
     position: absolute;
     right: 12px;
     z-index: 1;
     top: 10px;
}
 .avatar-upload .avatar-edit input {
     display: none;
}
 .avatar-upload .avatar-edit input + label {
     display: inline-block;
     width: 34px;
     height: 34px;
     margin-bottom: 0;
     border-radius: 100%;
     background: #FFFFFF;
     border: 1px solid transparent;
     box-shadow: 0px 2px 4px 0px rgba(0,0,0,0.12);
     cursor: pointer;
     font-weight: normal;
     transition: all .2s ease-in-out;
}
 .avatar-upload .avatar-edit input + label:hover {
     background: #f1f1f1;
     border-color: #d6d6d6;
}
 .avatar-upload .avatar-edit input + label:after {
     content: "f040";
     font-family: 'FontAwesome';
     color: #757575;
     position: absolute;
     top: 10px;
     left: 0;
     right: 0;
     text-align: center;
     margin: auto;
}
 .avatar-upload .avatar-preview {
     width: 192px;
     height: 192px;
     position: relative;
     border-radius: 100%;
     border: 6px solid #F8F8F8;
}
 .avatar-upload .avatar-preview > div {
     width: 100%;
     height: 100%;
     border-radius: 100%;
     background-size: cover;
     background-repeat: no-repeat;
     background-position: center;
}
 

JS

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function(e) {
            $('#imagePreview').css('background-image', 'url('+e.target.result +')');
            $('#imagePreview').hide();
            $('#imagePreview').fadeIn(650);
        }
        reader.readAsDataURL(input.files[0]);
    }
}
$("#imageUpload").on('click', function() {
    readURL(this);
     $('.avatar-edit').hide();
});


document.querySelector('button').addEventListener('click', function() {
        html2canvas(document.querySelector('.capturecontainer'), {
            onrendered: function(canvas) {
                // document.body.appendChild(canvas);
              return Canvas2Image.saveAsPNG(canvas);
            }
        });
    });