Printing newline characters in ejs

I’d like to print a string with newline characters with ejs.

I have this ejs file:

1.

If the string “names” is “line 1line 2” I get this:

line 1line 2

But I’d like this:

line 1
line 2

What is the best way of getting ejs to correctly interpret newline characters?

How to pass props from autocorrect to parent class

I’ve previously asked a question regarding the passing of state for react through props here: Laggy TextField Updates in React.

I’ve decided to refactor my code using ChrisG’s method, where I store states in the parent FormSection, and pass props into the child CompanyField.

Parent:

class FormSection extends React.Component {

  state = { 
    company: '', 
    jobType: ''
  };

  createHandleChange(name) {
    return (e) => {
      try {
      this.setState({ [name]: e.target.value.toLowerCase() }); //convert to lowercase if text data
      } catch {
        this.setState({ [name]: e.target.value }); 
      }
      console.log(name,  e.target.value);
    };
  }

  render() {
    return (
        <FormContainer>
            <CompanyField  # Working Correctly
                value={this.state.company}
                handleChange={this.createHandleChange("company")}
            />

            <JobTypeField  # Does not work
                value={this.state.jobType}
                handleChange={this.createHandleChange("jobType")}
            />
        </FormContainer>
   )
}

TextFieldStyled is just MUI’s textfield that was styled using styled components.

Child:

    class CompanyField extends React.Component {
    
      render() {
        return (
          <TextFieldStyled
            id = "outlined-basic" 
            label = "Company" 
            variant = "outlined"
            fullWidth
    
            value={this.props.value}
            onChange={this.props.handleChange}
          />
        );
      }
    }

This managed to successfully update the parent components state. However, when doing the same thing to MUI’s autocomplete:

class  JobTypeField extends React.Component {
    
    render() {
        return (
            <DropDownStyled>
                <Autocomplete
                    disablePortal
                    id="combo-box-demo"
                    options={jobType}

                    value={this.props.value}
                    onChange={this.props.handleChange}
                    renderInput={(params) => <TextField {...params} label="Job Type" />}
                />
            </DropDownStyled>
        );
    }
}

const jobType = [
  { label: 'Full-Time' },
  { label: 'Part-Time' },
  { label: 'Internship' },
  { label: 'Contract' },
  { label: 'Freelance' },
];

This error occurs:
The value provided to Autocomplete is invalid.
None of the options match with 0.
You can use the isOptionEqualToValue prop to customize the equality test.

After clicking an option, it defaults to 0.

The dropdown menu

After clicking an option

Additionally, the state is not updated.

Thanks!

Why am I not being redirected when I should

I’m coding an app where there is a timer coded in Javascript. Here is my Javascript :

var time=5;
var display = document.getElementById("display");
display.innerHTML=time;

function timing() {
    if (time>0) {
        time--;
        display.innerHTML=time;
        $.ajax({
            url:"/c_cesar",
            type:"POST",
            contentType: "application/json",
            data: JSON.stringify(time)});
    }
    else clearInterval(timer);
}

var timer=setInterval(timing, 1000);

I’m sending the time variable through ajax to be able to collect the data in Flask :

@app.route('/c_cesar', methods=['GET','POST'])
def c_cesar():
    time=request.get_json()
    print(time)
    if time==0:
        print("time is up")
        return redirect(url_for('index'))
    return render_template('c_cesar.html')

The problem is that when time is 0, I would like to redirect the user to the index page. That is why I’m using an if statement. When time is 0, the message “time is up” is printed on the console, but the user is not redirected. This is what my console displays :

4
127.0.0.1 - - [06/Apr/2022 10:52:45] "POST /c_cesar HTTP/1.1" 200 -
3
127.0.0.1 - - [06/Apr/2022 10:52:46] "POST /c_cesar HTTP/1.1" 200 -
2
127.0.0.1 - - [06/Apr/2022 10:52:47] "POST /c_cesar HTTP/1.1" 200 -
1
127.0.0.1 - - [06/Apr/2022 10:52:48] "POST /c_cesar HTTP/1.1" 200 -
0
127.0.0.1 - - [06/Apr/2022 10:52:49] "POST /c_cesar HTTP/1.1" 302 -
127.0.0.1 - - [06/Apr/2022 10:52:49] "GET / HTTP/1.1" 200 -

How can I redirect the user ?

How can I add multiple javascript objects to localStorage?

I have been trying to create a function on my website that allows a user to click on a specific row
of a table and the then the information on that row is saved to localstorage where it is then subsequently taken from the localstorage and printed to another table on another page so that they can save it. The issue is, I have created it so that the user clicks a table row, the information is saved in the localstorage and then it is printed to the other pages table. However, if the user wants to click on and save multiple table rows, the function is not allowing multiple objects to be saved the to the local storage. It only saves one object at a time and its the most recently clicked one.

Below is the html

<table class="table">
            <tr>
              <th>Trails</th>
              <th>Province</th>
              <th>Country</th>
            </tr>
            <tr>
              <td class="tableRow">Lion's Head</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Pipe Track</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Skeleton Gorge</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Table Mountain</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">King Fisher Trail</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Robberg Peninsula</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
            <tr>
              <td class="tableRow">Diep Walle Forest Walk</td>
              <td class="tableRow">Western Cape</td>
              <td class="tableRow">South Africa<button class="save">Save</button><i onclick="myFunction(this)" class="fa fa-thumbs-up"></i></td>
            </tr>
          </table>
        </div>

Secondly here is the html page the clicked information is being sent to

<body onload="addData()">

<table id="newTable" class="saved">
      <tr>
        <td class="saved">Trail</td>
        <td class="saved">Province</td>
        <td class="saved">Country</td>
      </tr>
    </table>

And finally, here is the javascript functions that are taking info from the first table and printing them to the second one.

let buttons = document.querySelectorAll(".save");
// console.log(buttons);

buttons.forEach((button) => {
  button.addEventListener("click", (event) => {
    const row = event.target.closest("tr");

    let newRow = row.innerText;
    let td1 = row.children[0].innerText;
    let td2 = row.children[1].innerText;
    let td3 = row.children[2].innerText;

    let td4 = td3.slice(0, -4);

    let myArray = [];
    let myObject = {
      trail: td1,
      province: td2,
      Country: td4,
    };

    myArray.push(td1, td2, td4);

    let newObj = JSON.stringify(myArray);

    localStorage.setItem("myObject", newObj);

    addData();
  });
});

//Adding the data to the new table on the saved page.
function addData() {
  let data = JSON.parse(localStorage.getItem("myObject"));
  console.log(data);
  console.log(data[0]);
  console.log(data[1]);
  console.log(data[2]);

  let table = document.getElementById("newTable");
  console.log(table);

  var row = table.insertRow(1);

  
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  var cell3 = row.insertCell(2);

  
  cell1.innerHTML = data[0];
  cell2.innerHTML = data[1];
  cell3.innerHTML = data[2];
}

To summarise, as it stands the javascript functions are taking the text information from the clicked table row, saving it in localstorage and then creating a new table row with that information in the new table. The issue is, if the user clicks a second table row, the information in the second page is changed to the most recently clicked information, I would like it to be added to the new table instead, so that the user can save multiple trails.

Any advice is appreciated.
Thanks in advance!

I have tried adding a click event listener to extract the text from a specific table row that has been clicked, then the information from that table row is added to a javascript object and saved to the local storage, I expected every time a save button was clicked the new information would be saved to the local storage as well as the old information that was clicked previously.

I thought that each time a table row would be clicked information would be added to the array in local storage, but it seems to be overwriting it each time a new row is clicked.

Thanks!

How to bind the imge in hedder in html-pdf

I am using node 12 when i am generating the pdf the image is not shown in the header my sample code mentioned below

var path = require('path'); 
let hedderstr='<div id="pageHeader"><img src="./img/logo.png"  width="25" height="25"></div>'
let html="<p>welcome</p>"
var options = { format: 'A4',
"header": {
    "height": "250px",
    "contents":hedderstr 
  },
  localUrlAccess: true, 
 };
pdf.create(html, options).toFile('./sample.pdf', function(err, res) {
  if (err) return console.log(err);
  console.log(res); // { filename: '/app/businesscard.pdf' }
});```



 

SQLITE_RANGE: column out of range error on UPDATE query

Apologies for a potentially very simple question, I am very new to javascript and SQLite.
I am building a webpage and on the server-side I have a database that stores all the users, their hashed passwords, sessionid, etc.

The table “Writers” consists of four columns: username, password (this is hashed, using bcrypt), sessionid, and socketid.

When a new user is registered I insert into the database, using this:

async registerNewWriter(username, password) {
console.log("IN REG NEW WRITER", username, password);
const saltRounds = 10; // default
bcrypt.hash(password, saltRounds, async (err, hash) => {
  if (err) {
    throw new Error(err);
  }
  await this.database.get(
     "INSERT INTO Writers (username, password, sessionid) VALUES (?,?,?)",
     `${username}`,
     `${hash}`,
     `null`,
 );
  // return hash;
});

}

After this, a session is created for the user. I update the database using this:

async createSession(id, socketID, username) {
console.log('create session', id, socketID, username);
await this.database.get(
      "UPDATE Writers SET sessionid = ?, socketid = ? WHERE username = ?",
      `${id}`,
      `${socketID}`,
      `${username}`, (err) => {
        if (err) {
          throw new Error(err);
        }
    }
);

}

Here is where I get the error: [Error: SQLITE_RANGE: column index out of range].

I have checked many similar questions online, but have not found the solution to this issue in particular. I have also made sure to check that sessionid, socketID and username all come into createSession with the correct values, but I do not understand why the database isn’t being updated correctly.

If you know what could be wrong or have any suggestions, I will be very grateful! Thank you 🙂

save axios api response data into a local file as .csv

it is possible to save the axios api response into a local file ?
I have this piece of code:

axios.get(
        "http://url-to-provide-data.com",
        {headers}
      )
      .then((response) => {
        console.log(response.data);
        responseData(response.data);
      })
      .catch((error) => {
        console.log(error.response.data);
      });
  }

I am trying to use json2csv in ordwer to save the api response into a local file as csv but not really working or better said, I’m not really sure how to use’it, any help is much appreciated !

Why should I use ‘underbar(_)’ for getting my function done?

I was studying inheritance of javascript and made a function to test it.
Here is the code:


function subClass(obj) {
    const parent = (this === window) ? Function : this;
    const F = function() {};

    const child = function() {
        const _parent = child.parent;
        
        if(_parent && _parent !== Function) {
            _parent.apply(this, arguments);
        }

        if(child.prototype._init) {
            child.prototype._init.apply(this, arguments);
        }
    };

    F.prototype = parent.prototype;
    child.prototype = new F();
    child.prototype.constructor = child;
    child.parent = parent;
    child.subClass = arguments.callee;

    for (let i in obj) {
        if (obj.hasOwnProperty(i)) {
            child.prototype[i] = obj[i];
        }
    }

    return child;
}

Then I made a sample object to adapt the function subClass. :

const person_obj = {
    _init: function() {
        console.log("person init");
    },
    getName: function() {
        return this.name;
    },
    setName: function(name) {
        this.name = name;
    }
};

Finally, here is the output code. :

const Person = subClass(person_obj);
const person = new Person();
person.setName("dorae");
console.log(person.getName());

Here is the question.
What I want as a result for console.log(person.getName()); is dorae,

but instead empty space comes out as a result.

However, when I change two ‘this.name‘s in person_obj to ‘this._name‘,
the exact result ‘dorae‘ comes out.

Even though I came up to the result what I wanted,
I couldn’t get the reason why I got the result.

I would appreciate if you let me know the reason why I get the answer only
when I use the underbar in front of the variable.

Thank you.

Javascript – sort an array of multiple objects of objects

I tried whith no success to sort an array of multiple objects of objects.

Here my database :

var jsonDatas = [
    {
        "type": "Voiture",
        "items": [
            {
                "name": "Fiat Punto",
                "description": "Je suis une voiture",
                "price": 10000,
                "quantity": 2,
            }, 
            {
                "name": "Porsche 911",
                "description": "Je suis une belle voiture",
                "price": 80000,
                "quantity": 0,
            }, 
        ],
    },
    {
        "type": "Maison",
        "items": [
            {
                "name": "Villa sur la plage",
                "description": "Quelle belle vue",
                "price": 870000,
                "quantity": 1,
            }, {
                "name": "Maison à la campagne",
                "description": "Vive le calme",
                "price": 170000,
                "quantity": 3,
            }
        ],
    }

I want to sort items by name (obtain Fiat, Maison, Porsche, Villa) , problem is the type, because each time, it sort first the type then the products by type.

I tried this for example :

function sortDatasASC(){
  database.forEach(element =>
     element.items.sort((a, b) => (a.name > b.name) ? 1 : -1)),
  catalogFiltered();

If you have any ideas!?

Thanks in advance.

How can I realize a sildeshow which can be controlled by two buttons

I don’t know how to control my sildeshow by buttons, I use timer to make it come true now

    var index1 = 0, len1, timer;
    var hisBox = document.getElementsByClassName("history");

    var count = document.getElementsByClassName("left-arrow");
    len1 = hisBox.length;
    hisBox[index1].style.display = 'block';
    for(var i=1; i<len1; i++) {
        hisBox[i].style.display = 'none';
    }

    function hisSlideShow() {
        index1 ++;
       
        if(index1 >= len1) index1 = 0;
        for(var i=0; i<len1; i++) {
            hisBox[i].style.display = 'none';
        }

        hisBox[index1].style.display = 'block';
    }

    timer = setInterval(hisSlideShow, 5000);

How to properly format bytes32 in javascript to send to contract?

I am trying to use the keccak256 function to recover a signed address (basically implementing a whitelisting functionaltiy for an NFT project).

The problem that I am having is that I can not figure out what the proper format of bytes32 for the hash is.

Here is what I am doing so far:

const signerPrivateKey = "someprivatekey"
const signer = new ethers.Wallet(signerPrivateKey);
const hashedAddress = ethers.utils.id(potentialWhiteListAddress);
const hashedAddressBytes = ethers.utils.arrayify(hashedAddress);
const signedAddress = await signer.signMessage(hashedAddressBytes);

return { signedAddress, hashedAddressBytes };

Then when interacting with my contract, the function that I am trying to use is:

function recoverSigner(bytes32 hash, bytes memory signature) public pure returns (address) {
  bytes32 messageDigest = keccak256(abi.encodePacked("x19Ethereum Signed Message:n32", hash));

  return ECDSA.recover(messageDigest, signature);
}

Calling the contract function from the frontend:

await myContract.recoverSigner(hashedAddressBytes, signedAddress);

However, I keep getting the error:

Error: invalid arrayify value (argument="value", value={"0":219,"1":46,"2":197,"3":32,"4":105,
"5":203,"6":166,"7":93, ... "31":52}, 
code=INVALID_ARGUMENT, version=bytes/5.6.1)

I have also tried formating each of these integer values, with ethers.utils.formatBytes32String(...), which resulted in the same error, just with the formatted values:

Error: invalid arrayify value (argument="value", value= 
{"0":"0x3231390000000000000000000000000000000000000000000000000000000000",
"1":"0x3436000000000000000000000000000000000000000000000000000000000000",
"2":"0x3139370000000000000000000000000000000000000000000000000000000000",
"3":"0x3332000000000000000000000000000000000000000000000000000000000000", 
..."31":"0x3532000000000000000000000000000000000000000000000000000000000000"}, 
code=INVALID_ARGUMENT, version=bytes/5.6.1)

If I skip choosing the checkbox, the alert box didn’t show up and having Uncaught TypeError: Cannot read properties of null (reading ‘checked’)

If I skip choosing in the checkbox, the alert must be shown. But it didn’t work and showing Uncaught TypeError: Cannot read properties of null (reading ‘checked’) in Javascript. Error got in checked==true.

var alist = '';
      var list = document.getElementsByName('chkApprover[]');

      for (i = 0; i < list.length; i++) {
        if (document.getElementById('chkApprover' + i).checked == true) {
          alist = alist + list[i].value + '|';
        }
      }

      if (alist == "") {
        alert("Please choose at least one Approver for your request!");
        
    }

I’ve tried adding window.onload but it skipped the whole approver checkbox and I’ve no idea why it’s not working. I will provide screenshot and codes in the below. I will insert half of the names in the Approver list.
If I add window.onload in JS and if I didn;t select the checkboxes, it shows Are you want to submit. Instead of showing that, it must show "Please Choose at least one approver from your request."

<?php  
include("_dbconn.php");

$area = isset($_GET["area"])? $_GET["area"] : "";

// $area = str_replace("1", "Production Floor Access", $area);
// $area = str_replace("2", "Office Floor Access", $area);
// $area = str_replace("3", "Specific Access Doors", $area);

if(substr($area,-1) == "|"){
    $area = substr($area,0,-1);
}
$area_list = explode("|",$area);

// print_r($area_list);
$area_clause = " area_no in ('" . implode("','", $area_list) . "')";

$ary_approver = array(
  "Albert Chin"       => "[email protected]",
  "Alberto Leotti"    => "[email protected]",
  "Alex Koh"          => "[email protected]",
  "Bala Subbu"        => "[email protected]",
  "Bertrand Seow"     => "[email protected]",
  "Calvin Goh Chin Boon"     => "[email protected]",
  "Chan Boon Hock"           => "[email protected]",
  "Cheng Kear Yong"   => "[email protected]"
);


$sql = "Select distinct(approver_name) from access_request.tbl_access_area where ".$area_clause."";
$result = mysqli_query($conn,$sql);
//echo $result;

$cnt = 0;

echo "<table align="center" border="0" width="95%" bordercolor="#DADADA" cellpadding="3" cellspacing="1">n";
echo  "<tr bgcolor="#F5F5F5"><td align="left" colspan="5">n";
    echo  "<font face="arial" size="2" color="#3C5F84">  Approver  </font>";
    echo "       ";
    echo "<tr bgcolor="#F5F5F5"><td align="left" colspan="5" style="
    display: grid;
    grid-template-columns: max-content max-content max-content max-content max-content max-content max-content max-content;
    grid-gap: 10px;
    margin-left:138px;
    margin-top:-23px;">";

    while($row = mysqli_fetch_array($result)){
        foreach($ary_approver as $k => $v){


            if($k == $row["approver_name"]){
                echo "<input type="checkbox" id="chkApprover" . $cnt . "" name="chkApprover[]" value="$v"><font face="arial" size="2" color="#3C5F84">". $k . "</font>";
                //echo "<br>           ";
            }
        }
        $cnt++;
    }

Error that’s happening.

How to find javascript file where function is coded in file structure in chrome browser

I have filters in wordpress, I am applying range slider for price filter along with theme inputs, I applies every method to call the input value to send the filter input data, but I don’t what method is theme using to send data for search by ajax.

jQuery(document).ready(function(){
var range_filter = '<div class="price-filter-range slider-range" name="rangeInput"> 
</div>';
jQuery('.vehica-results__field--number').append(range_filter);
jQuery(".slider-range").slider({
range: true,
orientation: "horizontal",
min: 1920,
max: 3000,
values: [1920, 3000],
step: 10,
slide: function (event, ui) {
if (ui.values[0] == ui.values[1]) {
return false;
}
var prev_ele = jQuery(this).prev();
var min_input_cont = jQuery(this).prev().find(".vehica-number-range__1of2--left");
var max_input_cont = jQuery(this).prev().find(".vehica-number-range__1of2--right");
var min_input = jQuery(this).prev().find(".vehica-number-range__1of2--left").children();
var max_input = jQuery(this).prev().find(".vehica-number-range__1of2--right").children();
min_input.attr("value", ui.values[0]);
max_input.attr("value", ui.values[1]);
min_input_cont.addClass("vehica-active-number");
max_input_cont.addClass("vehica-active-number");
min_input.on('keyup', function() {
min_input.attr("value", ui.values[0]);
min_input.val(ui.values[0]);
});
max_input.on('keyup', function() {
max_input.attr("value", ui.values[0]);
max_input.val(ui.values[0]);
});

And live link is

filter input page link