API Call in Cordova App Returns 404 Error

I’ve been using XMLHTTPRequest first, but I have tried using jQuery Ajax. Keeps the same error. Used chrome://inspect to inspect my phone and in the console shows this:

GET https://freecurrencyapi.net/api/v2/latest?apikey=my-key&base_currency=EUR 404 (Not Found)

The code for XMLHTTPRequest:

function getJSON(url) {
var http = new XMLHttpRequest();

http.open("GET", url, false);
http.send(null);

return JSON.parse(http.responseText);

}

The code for jQuery Ajax:

`
$.ajax({
type: “GET”,
url: “https://freecurrencyapi.net/api/v2/latest?apikey=my-key&base_currency=” + from_val

}).done((data) => {
    to_box.value = data.data[to_val] * parseFloat(from_box.value);
});

`

Please tell me what to do. thank you.

webdriver io js parsing

I need to copy links from (h5 a) elements on all pages using pagination.
My code collects links only from the first page, it goes through the rest of the pages but does not collect links. What is the problem here?
Thanks!

const linksCollector = async () => {

  let browser;
    try {
      browser = await remote({
        capabilities: { browserName: "chrome" },
      });

      await browser.navigateTo(link);

      const links = [];
      const pages = await browser.$$(".pagination__item");
      const paginationBtn = await browser.$(".pagination__next-icon");

      for (let i = 0; i < pages.length - 2; i++) {
        const linksArr = await browser.$$("h5 a");
        for (let i = 0; i < linksArr.length; i++) {
          const link = await linksArr[i].getAttribute("href");
          links.push(await link);
        }

        await paginationBtn.click();
      }
      await writeData(links);

      await browser.deleteSession();
    } catch (err) {
      console.error(err);
      return browser.deleteSession();
    }
  }
};

MIME Message, missing fields in mail

I have this function MIME message that I then POST to google draft API. When manually checking in my drafts, the mailContent show’s up properly.

  const mailContent = req.body.content

  .
  .
  .


  var message = 'MIME-Version: 1.0rn' +
  'Content-type: multipart/alternative; boundary=boundaryboundaryrnrn' +
  '--boundaryboundaryrn' +
  'Content-type: text/plain; charset=UTF-8rn' +
  mailContent + "rnrn" +
  '--boundaryboundary--';

Now I’m trying to add the From, To and Subject fields in my MIME message, and after quite some research, I thought that adding them to the ‘body’ like so would do the trick:

  const mailContent = req.body.content
  const from = "[email protected]"
  const to = req.body.to || ""
  const subject = req.body.subject || ""
  .
  .
  .

  var message = 'MIME-Version: 1.0rn' +
  'Content-type: multipart/alternative; boundary=boundaryboundaryrnrn' +
  'From: SomeName ' + '<' + from + '>' + "rn" +
  'To: ' + '<' + to + '>' + "rn" +
  'Subject: ' + subject + "rn" +
  '--boundaryboundaryrn' +
  'Content-type: text/plain; charset=UTF-8rn' +
  mailContent + "rnrn" +
  '--boundaryboundary--';

But it doesn’t… I’ve tried logging the added fields and they are what I expect. The POST still work’s and successfully create’s an other draft with the mailContent. However, the 3 fields I’m trying to add don’t show up. An I doing this wrong ?

Hi everyone, I have this error in the console, which asks me if I have registered the component correctly, [closed]

I have this error in the console”Unknown custom element: – did you register the component correctly? For recursive components, make sure to provide the “name” option.”
which asks me if I have registered the component correctly, and it is correct, because the same repo with the same lines of code to my teammates works, while it gives me this error. Anyone know what the problem might be?

D3.js Wrapping of long labels alignment

I am using a tutorial from Tutorialink Wrapping Text in D3 which along with every other online resource, references Mike Bostock’s “Wrapping Long Labels” example as it seems to be the only way to wrap labels in d3.

This is the result of my wrapping which is not ideal as I want them to be aligned to the centre. Please help as I am a noob in d3, any help would be appreciated!

Label Wrapping

This is my function wrap, and its implementation is found below it:

function wrap(text, width) {
  text.each(function () {
      var text = d3.select(this),
          words = text.text().split(" ").reverse(),
          word,
          line = [],
          lineNumber = 0,
          lineHeight = 0.7, // ems
          x = text.attr("x"),
          y = text.attr("y"),
          dy = 0, //parseFloat(text.attr("dy")),
          tspan = text.text(null)
                      .append("tspan")
                      .attr("x", x)
                      .attr("y", y)
                      .attr("dy", dy + "em");
      while (word = words.pop()) {
          line.push(word);
          tspan.text(line.join(" "));
          if (tspan.node().getComputedTextLength() > width) {
              line.pop();
              tspan.text(line.join(" "));
              line = [word];
              tspan = text.append("tspan")
                          .attr("x", x)
                          .attr("y", y)
                          .attr("dy", ++lineNumber * lineHeight + dy + "em")
                          .text(word);
          }
      }
  });
}

Implementation of the node label on the 5th last line:

let nodeLabel = svg
        .selectAll(".nodeLabel")
        .data(nodes)
        .enter()
        .append("text")
        .text((d) => {
          if (d.label === "Company" && d.properties.name.length > 10)
            return d.properties.name.substring(0, 10) + "...";
          else if (d.label === "Story" && d.properties.name.length > 20)
            return d.properties.name.substring(0, 20) + "...";
          else return d.properties.name.substring(0, 10) + "...";
        })
        .attr("dx", 0)
        .attr("dy", "1.8em")
        .attr("class", () => "label")
        .attr("text-anchor", "middle")
        .attr("fill", (f) => {
          if (f.label === "Company" || f.label === "Story") return "white";
          else return "black";
        })
        .call(wrap, 30) // wrap the text in <= 30 pixels
        .style("font-size", "10px")
        .on("mouseover", (d) => {
          handleMouseover(d);
        });

That search term that once killed us

I’m an internet troll and i came accross this term Erratas,so i Googled it and found this youtube video instead:Erratas… by Marty Bread.

watched it and seems like paranormal activities are present.

Well,i know that this stuff might be an internet taboo,but do you think its some sort of cam software glitch triggered by “Erratas” ,a Prof edit or,sth more?
Please advise,thanks sure will help.
I Tried replicating it at Home using my iPad and stuff but results seem to differ.

Not to discredit Marty or anything,but any opinions on the subject Will matter.

Thanks All.

How to return a string with Angular’s http client?

I try to call a server which returns a csv as text. When I use Angular’s HttpClient I want it to avoid trying to cast it to JSON. Setting the responseType to text in the httpOptions work, but it raises a TypeScript error which I ignore via @ts-ignore.

This is my code:

const httpOptions = {
  headers: new HttpHeaders({
    Accept: "text/plain",
    "Content-Type": "application/json",
  }),
  responseType: "text",
};

return this.httpClient.post<string>(
  `/api/csv`,
  {
    id: "1111",
    // more data
  },

  httpOptions
);

The error message is to big for me to see what the exact issue is. I got this solution somewhere here on SO, but I guess it is not up-to-date. But I am unable to see what the issue here is.

This is the error:

 Overload 1 of 15, '(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; observe: "events"; context?: HttpContext | undefined; params?: HttpParams | ... 1 more ... | unde
fined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }): Observable<...>', gave the following error.
    Argument of type '{ headers: HttpHeaders; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; observe: "events"; context?: HttpContext
| undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.
      Property 'observe' is missing in type '{ headers: HttpHeaders; responseType: string; }' but required in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; observe: "events"; context?: HttpCon
text | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.
  Overload 2 of 15, '(url: string, body: any, options: { headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; observe: "response"; context?: HttpContext | undefined; params?: HttpParams | ... 1 more ... | un
defined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }): Observable<...>', gave the following error.
    Argument of type '{ headers: HttpHeaders; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; observe: "response"; context?: HttpContex
t | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.
      Property 'observe' is missing in type '{ headers: HttpHeaders; responseType: string; }' but required in type '{ headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; observe: "response"; context?: HttpC
ontext | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.
  Overload 3 of 15, '(url: string, body: any, options?: { headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; context?: HttpContext | undefined; observe?: "body" | undefined; params?: HttpParams | ... 1 mor
e ... | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; } | undefined): Observable<...>', gave the following error.
    Argument of type '{ headers: HttpHeaders; responseType: string; }' is not assignable to parameter of type '{ headers?: HttpHeaders | { [header: string]: string | string[]; } | undefined; context?: HttpContext | undefined; observ
e?: "body" | undefined; params?: HttpParams | { ...; } | undefined; reportProgress?: boolean | undefined; responseType?: "json" | undefined; withCredentials?: boolean | undefined; }'.
      Types of property 'responseType' are incompatible.
        Type 'string' is not assignable to type '"json" | undefined'.

What am I missing?

React.js Object.entries().map() not rendering list contents [duplicate]

In a full stack application, I wrote a backend that returns JSON. The JSON Structure is similar to:

{
    "2022-03-04T09:56:33.525Z": [
        "https://amazon-s3-bucket-presigned-key-for-audio-data",
        "https://amazon-s3-bucket-presigned-key-for-animation-data"
    ],
    "2022-03-04T10:05:01.909Z": [
        "https://amazon-s3-bucket-presigned-key-for-audio-data",
        "https://amazon-s3-bucket-presigned-key-for-animation-data"
    ],
    {...}
}

There’s x amount of audio sources, which will each have y amount of recordings collected from that source. Each recording from a given audio source is guaranteed to be unique to a timestamp, and will always have matching animation data. I have verified this to be the case, and the backend output is definitely not the problem here.

In the React.js frontend, I render a list of accordion components from inside an accordianList component. Each accordion element will have the name of the audio source that it’s been collected from, and a conditionally displayed dropdown chevron, dependent on whether or not recordings collected from that source exist. When the dropdown chevron is clicked, a list of custom audio players is rendered, each specific to an individual recording entry collected from that source.

AccordianList > Accordian * x > AudioEntry * y

The issue

I had this system working, but made some drastic changes to the data transfer format. I previously transmitted everything in one go- all recordings from all sources. This was quite large, and caused some issues.

Now, after these changes, when I render the AudioEntry component the data inside the list does not render. The animation to change the dropdown chevron switches, as too does the dropdown state… However, the AudioEntry component does not get rendered at all. I know this for a fact, as when I replace everything inside that element with a <li> or <h1> tag, it is not displayed. I have console logged the data received, and can confirm it exists and is in the right format.

I tried these two methods for iterating the JSON object:-

<div className={classes.accordian_content} aria-expanded={!thisSensorSelected}> 
<ul>
    { Object.entries(dataList).map(([k, v])=> {
        {console.log({k, v})}
        <AudioEntry 
            key={k}
            date={new Date(k).toLocaleString('gb')}
            audioFile={v[0]}
            animFile={v[1]}
            dropdownClicked={thisSensorSelected}
            filePlaying={filePlaying}
            setFilePlaying={setFilePlaying}
        />
    })}
</ul>
</div>

Where the console.log outputs exactly what is expected, but the list is not rendered. There are no errors in the developer tools.

The other method I tried was this:

{Object.keys(dataList).map(timestamp => {
    <AudioEntry
        key={timestamp}
        date={new Date(timestamp).toLocaleString('en-gb')}
        audioFile={dataList[timestamp][0]}
        animFile={dataList[timestamp][1]}
        dropdownClicked={thisSensorSelected}
        filePlaying={filePlaying}
        setFilePlaying={setFilePlaying}
    />
})}

Again, console.log displays exactly what I expected- but the element is not rendered (which is just a <li> at this point).

For sake of clarity, I retrieve the data using an Axios wrapper, called inside an async useEffect function.

Things I have tried:

  • Checking whether the dataList is empty first (using ternary)
  • Object.values
  • Placing the Object.values/Object.keys/Object.entries inside of a fragment.
  • Placing the entire <ul> inside a fragment
  • Changing the thisSensorSelected state prop to not include !
  • Banging my head off of the keyboard

I can’t replace a variable state in reactjs function , javascript

I can’t put a keyword in filter function between row. and .toLowerCase().

function customer (){
  const [keyword, setKeyword] = React.useState("name")

  const handleChange= (e) => {
    setKeyword(e.target.value)
  } 

 
 //row is a data fetch from api 

 function Search(rows) {
    return (rows.filter(row => row.***keyword***.toLowerCase().indexOf() > -1))
  }

  return {
    <select defaultValue={'name'}  onChange={handleChange} name="type" >
      <option value="name" >name</option>
      <option value="customer_no">customer number</option>
      <option value="email">email</option>
    </select>
  }
}

How to calcualte await method time and shows PROGRESS BAR [duplicate]

I am uploading a file to Azure when the user clicks on the confirm dialog box. The content can be imagery, videos, or Excel and other file types.

It takes time while upload so during this time I want to show a progress bar. After successfully uploading I want to hide the progress bar. Can you please help me with it?

<div class="progress">
  <div id="progress" class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">
    <div id="label" class="control-label">0%</div>
  </div>
</div>
document.getElementById("dialogBtn").onclick = function() {
  ej.popups.DialogUtility.confirm({
    title: ' Confirmation Dialog',
    content: "Are you sure you want to upload images into Azure and Update DB",
    okButton: {
      text: 'OK',
      click: function() {
        okClickInsert();
        this.hide();
      }
    },
    cancelButton: {
      text: 'Cancel',
      click: ClickTest
    },
    showCloseIcon: true,
    closeOnEscape: true,
    animationSettings: {
      effect: 'Zoom'
    }
  });
};

function okClickInsert() {
  // Other Code

  $.ajax({
    url: "@Url.Action("UploadFilesinAzure", "UploadFiles")",
    data: JSON.stringify(UPLOADToAzure),
    type: "POST",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    beforeSend: onProgress,
    complete: onComplete,
    success: function(data) {
      location.reload();
    },
    error: function(data) {}
  });
}

function onProgress(args) {
  document.querySelector("body").style.visibility = "hidden";
  document.querySelector("#progress").style.visibility = "visible";
}

function onComplete(args) {
  document.querySelector("#progress").style.display = "none";
  document.querySelector("body").style.visibility = "visible";
};
[HttpPost]
public async Task<bool> UploadFilesinAzure([Frombody]...) {
  // Other validation  code
  await DoUploadFileOnlyAsync(FILE Details);
}

search dropdown close when outside click

When I type something in the search box the dropdown list shows but I want that when I click outside the rest of the search box, the search list will be closed.

function myFunction(e) {
  // find all `li` > a elements
  let col=document.querySelectorAll('ul#myUL li a');
      // iterate through all elements; re-hide & remove className from each.
      col.forEach(n=>{
      
        n.parentNode.style.display='none';
        n.classList.remove('bold');
        
        // if the typed value matches the beginning of a list item; display the text & assign Bold className
        if( this.value.length > 0 && this.value.trim()!='' && n.textContent.toLowerCase().includes( this.value.toLowerCase() ) ){
        
          n.parentNode.style.display='block';
          // make the whole word bold
          //n.classList.add('bold');
          
          // make the matched portion bold
          n.innerHTML = n.textContent.substr(0,n.textContent.toLowerCase().indexOf(this.value.toLowerCase()))+`<span class="bold">${this.value}</span>` + n.textContent.substr(n.textContent.toLowerCase().indexOf(this.value.toLowerCase())+this.value.length)
        }
      });
}



document.querySelector('input[name="search"]').addEventListener('keyup',myFunction);
* {
  box-sizing: border-box;
}

#myInput {
  background-image: url('/css/searchicon.png');
  background-position: 10px 12px;
  background-repeat: no-repeat;
  width: 100%;
  font-size: 16px;
  padding: 12px 20px 12px 40px;
  border: 1px solid #ddd;
  margin-bottom: 12px;
}

#myUL {
  list-style-type: none;
  padding: 0;
  margin: 0;
}
#myUL li{
  display:none;
}

#myUL li a {
  border: 1px solid #ddd;
  margin-top: -1px; /* Prevent double borders */
  background-color: #f6f6f6;
  padding: 12px;
  text-decoration: none;
  font-size: 18px;
  color: black;
  display: block
}

#myUL li a:hover:not(.header) {
  background-color: #eee;
}

.bold{font-weight:bold;color:red}
<input name='search' type="text" placeholder="Search for names.." title="Type in a name" />
<ul id="myUL">
  <li><a href="#">Adele</a></li>
  <li><a href="#">Agnes</a></li>
  <li><a href="#">Billy</a></li>
  <li><a href="#">Bob</a></li>
  <li><a href="#">Calvin</a></li>
  <li><a href="#">Christina</a></li>
  <li><a href="#">Cindy</a></li>
</ul>

LeafletJS map not working properly. Shows zoomed out world map

I am fetching certain data from the geolocation API and displaying information about a particular IP address entered by the user. I’m also displaying the location using leaflet.js but the map doesn’t work properly. I am fetching the coordinates from the API and updating the center of the map with them. Here’s a screenshot

The JS code looks like this:

map = L.map('map').setView([lat, long], 13);

L.tileLayer('https://api.mapbox.com/styles/v1/mapbox/streets-v11/tiles/0/0/0?access_token='+ACCESS_TOKEN, {
attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
maxZoom: 18,
id: 'mapbox/streets-v11',
tileSize: 1024,
zoomOffset: -1,
accessToken: ACCESS_TOKEN
}).addTo(map);

L.marker([lat, long]).addTo(map)
.bindPopup("popup")
.openPopup();

What might be wrong?