How to change every specific value in an array to another value? (Javascript)

How can I change every specific value within an array to another specific value? My function splits a string into an array, and if a specific index == “T” it’s supposed to change that value to “U”, join the values in the array, and return the result. But the value “T” isn’t changing within the array as I loop through it. What am I doing wrong?

function DNAtoRNA(dna) {

let array = dna.split();
let rna = "";

for(var i = 0; i < array.length; i++) {
  if(array[i] == 'T') {
    a[i] = 'U';
  }
  }
rna = array.join();
return rna;
}

Example input = “ATFT”, output = “AUFU”

convert string property from api to JSON object

i’m making a call to an api which returns data to the front end in this format

{ name: 'Fred', 
data: [{'name': '"10\" x 45\" Nice Shirts (2-pack)"', 'price': '$30.25'}]
}

the data property is return as a string and i’m trying to use JSON.parse(response.data) to get it as as array so i can use *ngFor to do iteration but i’m always getting an error

Unexpected token ' in JSON at position 2
SyntaxError: Unexpected token ' in JSON at position 2 (at zone.js:1262:1)
    at JSON.parse

Javascript AJAX How to Fetch Data from API by ID

I’m trying to create a program that allows a user to input a number and fetches the movie data from an API by accessing the id index, so for example if I wanted to access the 3rd ID of the API, it would fetch all the elements from “https://my-json-server.typicode.com/daijonbereola/restful-api-react/movies/3”. So far, no movie has been found and am not sure what is wrong with my Javascript. Here it is pasted below:

<form>
    <input type="number" id="inputId" placeholder="Enter a number"/>
    <input type="button" id="fetchId" value="Fetch Movie" class="btn btn-primary"/>
</form>
    <script>
        let id = document.getElementById("inputId").value;
        
        let fetchId = document.getElementById("fetchId");
        fetchId.addEventListener("click", selectHandler);
        
        
        function selectHandler() {

            // Instantiate an new XHR Object
            const xhr = new XMLHttpRequest();

            // Open an obejct (GET/POST, PATH,
            // ASYN-TRUE/FALSE)
            xhr.open("GET",
`https://my-json-server.typicode.com/daijonbereola/restful-api-react/movies/${id}`, true);

            // When response is ready
            xhr.onload = function () {
                if (this.status === 200) {

                    // Changing string data into JSON Object
                    obj = JSON.parse(this.responseText);

                    // Getting the element
                    let list = document.getElementById("list");
                    id = obj.id;
                    console.log(id);
                    if(id){
                    str = ""
                        str +=
                            `
                            <div style="padding: 5px 5px;">
                                <a href=${obj.url}>${obj.title}</a>
                                <image style="max-width: 60%;"src=${obj.image} alt = "movie poster"/>
                            </div>
                            `;
                        list.innerHTML = str;
                    } else{
                        str = ""
                        str += `<p>Movie not found...Please try again</p>`;
                        list.innerHTML = str;
                    }
                }
                else {
                    console.log("File not found");
                }
            }
            xhr.send();
        }
    </script>

move a circle from one point to another

I’m new to leaflets and am trying to circle the map when clicked. I want conditions like the following:

  • Circle moves from one point to another when clicked on the map (If the circle already exists and there is only one circle)
  • Directly Zoom on where the circle is made

However I have the following problem:

  1. Circle increases
  2. When pressing another point, the circle disappears first and after that it will appear at the previous point and at the most recent point
  3. Don’t zoom in where the circle is made

Is there a solution to this problem?

<!DOCTYPE html>
<html>
   <head>
      <title>Leaflet Polygons</title>
      <link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
      <script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
   </head>
   
   <body>
      <div id = "map" style = "width: 900px; height: 580px"></div>
      <script>
         // Creating map options
         var mapOptions = {
            center: [16.506174, 80.648015],
            zoom: 11
         }
         var groupCircle = L.featureGroup();

         var map = new L.map('map', mapOptions);    // Creating a map object
         
         // Creating a Layer object
         var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
         map.addLayer(layer); // Adding layer to the map
         
         map.on("click", function(e){
            if(map.hasLayer(groupCircle)){
                map.removeLayer(groupCircle)
            }else{
                new L.Circle([e.latlng.lat, e.latlng.lng], 5000).addTo(groupCircle);
                map.addLayer(groupCircle)
            }
            
         })
      </script>
   </body>
   
</html>

WooCommerce checkout doesn’t display correctly in local copy of WordPress site using DevKinsta

Aim

To create a local copy of a WordPress site using DevKinsta.

Issue

Everything is working currently in the local site copy except for the checkout page. Something can be added to the basket without problems, then the checkout page shows the heading for ‘Enter billing details’ and nothing else. No payment options or input fields.

When I right click Inspect -> Console in the browser, I get:

  • GET 500 error for the checkout URL
  • Uncaught TypeError: Cannot read properties of undefined (reading ‘setDefaults’)
  • Uncaught TypeError: Cannot read properties of undefined (reading ‘addMethod’)

This link suggests themes and plugins can be common causes of JavaScript errors with WooCommerce, however, since the site is working in production with the same plugins/theme and doesn’t show the same errors it would suggest an issue with the local copy set up.

Have tried:

  • Checking the SSL/HTTPS, DevKinsta has an SSL/HTTPS option which registers fine in the browser.
  • Replacing all the URL references in the database and in the WordPress files

Running on:

macOS, Chrome/Safari

How to truncate an hex address?

So im writing an exploit and im getting an address such as 0x00708001e9ab0b10 which is obviously a 64 bit hex address. The address I need is 0x1e9ab0b10 to my calculations this is the upper 28 bits but some told me this is 48 bits and up so i dont know but i basically need to remove 0x0070800 the first 7 numbers of the hex string/number and give me something like 0x00000001e9ab0b10 which i would prefer!!! or something like 0x1e9ab0b10 mind you as well i need this done in JavaScript which is what my exploit is for

Positioning image insert in Google Chrome extension

I was writing a Google Chrome extension to insert an image into the body of a website. It currently does that, but the image is centered all the way at the bottom, after the text of the website. I was wondering how to put it in the top left instead, or to use coordinates for the location. This is my code currently in JavaScript, as I can’t use CSS for it.

  function imageappend() {
    const img = document.createElement("img");
    img.src = chrome.runtime.getURL("imageedit_1_3932659157.png");
    img.style.top = "0";
    img.style.left = "0";
    img.style.padding = "0";
    img.style.margin = "0";
    document.body.appendChild(img);
  }

  let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });

  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    function: imageappend
  });
})(); ```

A way to insert a # in front of a variable of the html attribute value data-bs-target (HTML, JS, Bootstrap, Vue)

So basically, I have a vue web app and created a container with multiple bootstrap cards. The cards have a button, which collapses a form I’ve made for guests to apply. However, when I press the button of a card, it collapses the apply form of all cards at once. To fix that, I have to give each individual card a specific id which matches the data-bs-target and aria-controls of the button. So far, so good.

I’ve made a variable card_id and inserted it into the attribute values with v-bind, but it’s not working. The reason is, that the attribute data-bs-target needs a hashtag before the actual variable name, but I can’t figure out a way to do that.

Code sample:

    <button class="btn btn-primary" type="button" data-bs-toggle="collapse" :data-bs-target="card_id" aria-expanded="false" :aria-controls="card_id">Apply now!</button>
<div class="collapse" :id="card_id">
    <div class="card card-body">
      <GuestForm></GuestForm>
    </div>
</div>

I obviously can’t just put a hashtag in front of the variable, so what is my next best solution for this?
Thank you in advance.

React Multiselect to checkbox

I’ve recently tried to switch from Multiselect dropdown to checkboxes instead in react and replicate a similar behavior to the previous Multiselect dropdown that I used.

But I’m struggling to get the checkbox value (error: Uncaught TypeError: Cannot read properties of undefined (reading ‘value’)) and store the checked values. Please advise what I could be missing?

Here is how my multiselect was setup before and the checkbox component and functions I currently have:

import { Multiselect } from 'multiselect-react-dropdown';

// Get Alert Filters
const [alertTypeFilter, setAlertTypeFilter] = useState([]);
const [isSelectedList, setIsSelectedList] = useState([]);

alertTypes = alertTypes.map((alertType) => ({
  value: alertType.id,
  name: alertType.description,
}));

//Old Multiselect replaced by checkbox component below it:
<Multiselect
   options={alertTypes}
   displayValue="name"
   selectedValues={alertTypeFilter}
   closeOnSelect={false}
   avoidHighlightFirstOption
   placeholder="Select Alert Subtype"
   onSelect={(selectedList) => {
      alertTypeFilterChangeFunc(selectedList);
   }}
   onRemove={(selectedList) => {
      alertTypeFilterChangeFunc(selectedList);
   }}
/>

My checkbox component:

const Checkbox = ({
  checboxText, textBold, onClickFunc, checked, labelStyle, testID,
  disabled,
}) => {
  const checkboxInputRef = useRef();

  if (checked === 'indeterminate' && checkboxInputRef.current) {
    checkboxInputRef.current.indeterminate = true;
    checkboxInputRef.current.checked = false;
  } else if (checkboxInputRef.current) {
    checkboxInputRef.current.indeterminate = false;
    checkboxInputRef.current.checked = checked;
  }

  return (
    <label
      className={`checkbox-container ${textBold ? 'bold' : ''} row`}
      style={labelStyle}
    >
      <input
        data-test={testID}
        checked={checked}
        type="checkbox"
        onChange={(event) => {
          onClickFunc(event.currentTarget.checked);
        }}
        ref={checkboxInputRef}
        disabled={disabled}
      />
      <div
        className="checkbox-custom"
        style={{ marginRight: checboxText ? '10px' : '0' }}
      />
      {checboxText}
    </label>
  );
};

Checkbox.propTypes = {
  onClickFunc: PropTypes.func.isRequired,
  checked: PropTypes.oneOf([true, false, 'indeterminate']).isRequired,
  checboxText: PropTypes.string,
  textBold: PropTypes.bool,
  labelStyle: PropTypes.any,
  testID: PropTypes.string,
  disabled: PropTypes.bool,
};

This is how I then rendered the checkbox component:

const handleChange = (event) => {
  const { value, checked } = event.target;

  const mappedData = isSelectedList.map((selected) => (selected.value === value ? { ...selected, isChecked: checked } : selected));
    setIsSelectedList(mappedData);
};

{alertTypes.map((alert) => (
   <div key={alert.value}>
      <CheckBox
         value={alert.name}
         name={alert.name}
         checboxText={alert.name}
         onClickFunc={(event) => handleChange(event)}
      />
   </div>
))}

Why does my webpack compiled code have references to coinbase wallet and ethereum?

I was trying to figure out why my compiled js code using webpack had the following error in the console?

Uncaught TypeError: Cannot assign to read only property 'ethereum' of object '#<Window>'

When I look at the code that generated the error I see a bunch of references to CoinbaseWalletAPI and Ethereum… It seems to be in a small module called requestProvider.js. Has anyone ran into this before? I have not been able to find any references to this error online. When I looked up that NPM module I found this page(https://www.npmjs.com/package/request-provider), I’m assuming one of my modules in my project is including requestProvider but I do not know which one and I cannot find references in the source code in my node modules folder.

How to compensate for daylight savings time in the future for ICS file calendar downloads

I have a list of deadlines for various projects. Once every 3 months, I download the next 3 months’ worth of deadlines as ICS files and add them to my calendar. Because I only download them once every 3 months, I am experiencing an issue with regards to daylight saving time (DST). Here is an example of the problem:

  • In January, I download the upcoming deadlines for February, March, and April, setting the time as 9:00 AM on their respective dates.
  • Come March 13th (the start of DST), the deadlines start to appear as 8:00 AM because when I downloaded them, it was not DST, so when we “sprung forward,” what used to be 9:00 AM is now 8:00 AM, and the files are not compensating for that.

I have had trouble determining where the best way to solve this problem would be:

  • In the configuration of the ICS file itself. I imagine that if there was a place to do this, it would be here. I have scoured the documentation of ICS files and have yet to find something that would auto-compensate for DST in the future.
  • In JavaScript on the front-end. I know that JavaScript has the option of setting the timezone to a region (“America/New_York”) instead of a time zone, which helps it auto-compensate for DST, but I have not been able to get that feature to work on a date in the future, as it only references the current time.
  • In PostgreSQL on the back-end. I have tried various versions of AT TIME ZONE to no avail. I encounter the same problem I did in JavaScript: It sets the time in the specified time zone without taking into account whether or not the date would be affected by DST in the future.

How to toggle style property using UseState

In react I would like to lock scroll-bar when sub-menu is out and then again unlock it when menu is hidden. I press the same button to open and close sub-menu (adds and removes translate for this element).
With what i did page sucessfully locks but when i press menu button and sub-menu dissapears the page is still locked, how can i change that the code is below:

const [isActive, setActive] = useState(false);
const toggleClass = () => {
    setActive(!isActive);
    document.body.style.overflow = "hidden"
  };

 <div className="button"
   onClick={toggleClass}
   className={
   isActive ? "nav-button closebtn active" : "nav-button closebtn"}>
   <span></span>
 </div>

how can I toggle the value of overflow from hidden to unset by pressing the button, just like i do with adding the class when i press the same button

Change innerHtml of div according to value of model item in view .NET6 EF6 Razor Pages No MVC

Change innerHtml of div according to value of model item in view
.NET6 EF6 Razor Pages No MVC

I am trying to have a due date optional in a todo list.
Since date fields are not nullable/required, I set the default due date to 09/09/9999.
That date represents a todo that does not have a due date.
What I want is to have the innerHtml of that due date display “None” if the due date is 09/09/9999.

My code however shows “None” in the due date div in the table of only the first row, regardless of the date.

enter image description here

Here is the javascript code

function hideDueDate () {
const dueDateDiv = document.querySelector('#due-date');

if (dueDateDiv.innerHTML = "09/09/9999") {
    dueDateDiv.innerHTML = "None";
    }   
}

hideDueDate();

And here is the view.

    <tbody>
         @*READ*@
            @foreach(var obj in Model.ToDo)
            {
             <tr>
                <td width="10%">@Convert.ToString(string.Format("{0:MM/dd/yyyy}", obj.CreateDate))</td>
                <td width="20%">@obj.Name</td>
                <td width="40%">@obj.Description</td>
                <td width="10%">
                    <div id="due-date">@Convert.ToString(string.Format("{0:MM/dd/yyyy}", obj.DueDate))</div>
                </td>
                <td width="20%" class="">
                    <div class="row d-flex justify-content-center">
                    <input asp-for="@obj.Complete" class="form-check-input mt-3" type="checkbox" readonly="readonly" />
                    </div>
                </td>
                <td>
                    <div class="w-65 btn-group" role="group">
                    <a asp-page="View" asp-route-id="@obj.Id" class="btn btn-outline-info rounded-pill mx-2">
                        <i class="bi bi-binoculars">&nbsp;View</i>
                    </a>
                    <a asp-page="Edit" asp-route-id="@obj.Id" class="btn btn-outline-success rounded-pill mx-2">
                        <i class="bi bi-pencil-square">&nbsp;Edit</i>
                    </a>
                    <a asp-page="Delete"  asp-route-id="@obj.Id" class="btn btn-outline-danger rounded-pill mx-2">
                        <i class="bi bi-trash-fill">&nbsp;Delete</i>
                    </a>
                    </div>
                </td>
             </tr>
            }
    </tbody>

If else statement not working with getElementByClassName

I have some inputs that I want to be all filled out before a button appears. I wrote some some code using document.getElementById(”) and an if else statement, but that only works for one element. So I made a class for the inputs. Now it isn’t working.

JavaScript:

function disableAdd() {
        if(Document.getElementsByClassName("foodInput").value != "") {
document.getElementById("add").style.display ="inline-block";
}
else{
document.getElementById("add").style.display ="none";
}
}