I’m having trouble displaying an html button with javascript

I have two buttons on an HTML page, and I’m trying to show them once a button is pressed, but only one actually displays.

This is the HTML

<button onclick="testLeft()" class="item-description" id= "left-item-description">.</button>
<button onclick="testRight()" class="item-description" id= "right-image-description">.</button>

This is the CSS

.item-description {
    display: none;
    box-sizing: border-box;
    position: fixed;
    z-index: 4;
    font-size: 35px;
    font-weight: 600;
    height: auto;
    top: 30%;
    padding: 10px 10px;
    color:white;
    background-color: transparent;
    border-radius: 4px;
    border: 3px solid black;
    transition: all 0.2s ease;
}


#left-item-description {
    margin-left: 10%;
    margin-right: 60%;
}

#right-image-description {
    margin-right: 10%;
    margin-left: 60%;
}

And this is the javascript

function newGame(){
    score = -1;
    increaseScore();
    correct = true;

    for (let i = 0; i < used.length; i++){
        used[i] = false;
    }

    indexLeft = shuffleIndex();
    indexRight = shuffleIndex();
    var left = document.getElementById("left-item-description");
    var righ = document.getElementById("right-item-description");
    
    left.style.display = "block";
    left.innerText = items[indexLeft];
    document.getElementById("left-item-image").src=images[indexLeft];
    
    righ.style.display = "block";
    righ.innerText = items[indexRight];
    document.getElementById("right-item-image").src=images[indexRight];

}

The left button works perfectly how I want it to, but for some reason, the right button doesn’t display

How can javascript extract specified key value from json blob with many nested values?

I have an https query which returns a json blob in the following format:

{
"metric_data": {
    "from": "2021-12-09T01:25:32+00:00",
    "to": "2021-12-09T01:55:32+00:00",
    "metrics_not_found": [],
    "metrics_found": [
        "Mobile/Crash/All"
    ],
    "metrics": [
        {
            "name": "Mobile/Crash/All",
            "timeslices": [
                {
                    "from": "2021-12-09T01:24:00+00:00",
                    "to": "2021-12-09T01:54:00+00:00",
                    "values": {
                        "call_count": 5
                    }
                }
            ]
        }
    ]
}

}

I want to find and extract the value for call_count. What is the best way to do that with Javascript? The following code will actually print out all the json values, including the call_count but all my efforts to just grab the value for call_count are failing.

var json = `{
"metric_data": {
    "from": "2021-12-09T01:25:32+00:00",
    "to": "2021-12-09T01:55:32+00:00",
    "metrics_not_found": [],
    "metrics_found": [
        "Mobile/Crash/All"
    ],
    "metrics": [
        {
            "name": "Mobile/Crash/All",
            "timeslices": [
                {
                    "from": "2021-12-09T01:24:00+00:00",
                    "to": "2021-12-09T01:54:00+00:00",
                    "values": {
                        "call_count": 5
                    }
                }
            ]
        }
    ]
}
}`;
    
    // Convert a JSON object to a Javascript object
var obj = JSON.parse(json);

// This function prints nested values
function printValues(obj) {
    for(var k in obj) {
        if(obj[k] instanceof Object) {
            printValues(obj[k]);
        } else {
            document.write(obj[k] + "<br>");
        };
    }
};

// Printing all the values from the resulting object
printValues(obj);

document.write("<hr>");
    
    // This is where I fail as I try to print a single value.
    document.write(obj["metrics"]["call_count"] + "<br>");

Any feedback would be much appreciated!

p5js clipping mask equivalent?

I have a super simple script that creates a circle with alternating “slice” colors

let slices = 12;


function setup() {
  createCanvas(400, 400);
  noStroke();
}

function draw() {
  background(220);
  translate(width/2, height/2);
  
  let inc = TWO_PI/slices;
  let c = 0
  for (let i = 0; i < TWO_PI+inc; i+=inc) {
    if (c % 2 == 0) {
      fill('white')
    } else {
      fill('black')
    }
    arc(0, 0, width/2, width/2, i, i+inc);
    c++
  } 
}

How can I do this same thing but with a square? That is, I want the alternating slice colors but encapsulated in a square rather than a circle. I am not sure how to do this since I used arc() to create the slices. Is there some way I can create a mask or something? Or is there an easy solution to my problem?

How to make mock api axios call in test?

Hello I am new to testing and I am following this client’s testing protocol where they make an axios.post request to a localhost end point (they start up a separate express server during test script)

describe("Arrived For Delivery", () => {
it("POST /courier/arrivedForDelivery should return success", async () => {
    const res = await axios.post(
        `http://localhost:8888/courier/arrivedForDelivery`,
        { order_id: "MOCK" },
        {
            params: {
                authentication: mockAuth,
            },
        }
    );
    // Assertion
    expect(res.data).to.be.equal("success");
});

it("POST /courier/arrivedForDelivery should return error data", async () => {
    // Arrange
    const stubProviderStorage = stub(ProviderStorage, "GetProviderByID");
    stubProviderStorage.throws({ message: "test" });

    try {
        // Act
        await axios.post(
            `http://localhost:8888/courier/arrivedForDelivery`,
            { order_id: "MOCK" },
            {
                params: {
                    authentication: mockAuth,
                },
            }
        );

        // Assert
        expect.fail();
    } catch (error) {
        expect((error as AxiosError).response?.data).to.be.eqls({
            code: 400,
            message: "arrivedForDelivery Error test",
        });
    }
    stubProviderStorage.restore();
});

});

is it possible to use sinon to make a mock api call and define what the response should be? because my senior dev from another company is telling me that i shouldnt be making real axios requests in an unit test nor i should make requests outside the code base.
any suggestions?

Object with nested array to filter, want to return entire object with new filtered array

I’m attempting to remove an object out of an array nested within my movie object and then copy it to a new variable. So my original object looks like this:

{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 3,
            "lastName": "Weaver",
            "firstName": "Sigourney"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

and what I’m doing right now is

const updatedMovie = const updatedMovie = movie.actors.filter((actor) => actor.id !== id);

but as you know that only returns the array of actors I filtered. I want to copy the entire object with the newly filtered actors so the object will come out like this (removing actor id 3):

{
    "id": 1,
    "title": "Avatar",
    "movieLength": 162,
    "releaseDate": "2009-12-18",
    "trailerUrl": "https://www.youtube.com/watch?v=5PSNL1qE6VY",
    "genre": {
        "id": 1,
        "genre": "Action"
    },
    "rating": {
        "id": 3,
        "rating": "PG-13"
    },
    "director": {
        "id": 1,
        "lastName": "Cameron",
        "firstName": "James"
    },
    "actors": [
        {
            "id": 2,
            "lastName": "Worthington",
            "firstName": "Sam"
        },
        {
            "id": 4,
            "lastName": "Saldana",
            "firstName": "Zoe"
        }
    ],
    "comments": []
}

I’ve tried reading around but I’m not having any luck getting any solutions to work with me, so if anyone can help or point me in the right direction that would be great!

How can I make a regular expresion that verify if a opening parenthesis has its closing parenthesis?

I’ve got a question. I have this regular expresion:

const r = /((B[(])*(w)+(b[)])*(s)*)+/g;

But lets suppose that we have the string :

ball (doll) (bicycle

So we wanna verify if every opening parenthesis has its closing parenthesis, then I wanna that this string returns me a false value, because the substring “(bicycle” hasn’t its closing parenthesis.

What can I do to create a pattern with regexp that verifies this? THANKS!! 😀

element onclick in class never called

I have a simple class.

The problem im having is that my onClick function is never called when clicking on the div element.

class card {
  constructor(parent, element) {
    this.parent = parent;
    this.element = element;

    this.element.on({
      'click': $.proxy(this.onClick, this)
    });
  }

  onClick() {
    console.log("onclick");
  }

}

class cards {
  constructor() {
    this.element = $(".cards");
    this.cards = [];

    this.element.children(".card").each((obj) => {
      this.cards.push(new card(this, $(obj)));
    });

  }
}

var my_a = new cards();

how to convert Array object to table javascript?

I have the following array of objects, and I need to display it in a table as shown in the screenshot:

This is the object:

[
    {
        "dayText": "Viernes",
        "monthText": "Diciembre",
        "date": "2021-12-10T15:26:55.273Z",
        "start": "08:00",
        "end": "08:30",
        "scheduled": true
    },
    {
        "dayText": "Viernes",
        "monthText": "Diciembre",
        "date": "2021-12-10T15:26:55.273Z",
        "start": "09:00",
        "end": "09:30",
        "scheduled": false
    },
    {
        "dayText": "Sábado",
        "monthText": "Diciembre",
        "date": "2021-12-11T15:26:55.273Z",
        "start": "08:00",
        "end": "08:15",
        "scheduled": false
    },
    {
        "dayText": "Sábado",
        "monthText": "Diciembre",
        "date": "2021-12-11T15:26:55.273Z",
        "start": "08:15",
        "end": "08:30",
        "scheduled": false
    },
    {
        "dayText": "Sábado",
        "monthText": "Diciembre",
        "date": "2021-12-11T15:26:55.273Z",
        "start": "08:30",
        "end": "08:45",
        "scheduled": false
    },

    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "08:00",
        "end": "08:30",
        "scheduled": false
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "09:00",
        "end": "09:30",
        "scheduled": true
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "10:30",
        "end": "11:00",
        "scheduled": true
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "11:00",
        "end": "11:30",
        "scheduled": false
    },
    {
        "dayText": "Domingo",
        "monthText": "Diciembre",
        "date": "2021-12-12T15:26:55.273Z",
        "start": "11:30",
        "end": "12:00",
        "scheduled": false
    },

    {
        "dayText": "Lunes",
        "monthText": "Diciembre",
        "date": "2021-12-13T15:26:55.273Z",
        "start": "10:30",
        "end": "11:00",
        "scheduled": false
    },
    {
        "dayText": "Lunes",
        "monthText": "Diciembre",
        "date": "2021-12-13T15:26:55.273Z",
        "start": "11:00",
        "end": "11:30",
        "scheduled": false
    },
    {
        "dayText": "Lunes",
        "monthText": "Diciembre",
        "date": "2021-12-13T15:26:55.273Z",
        "start": "11:30",
        "end": "12:00",
        "scheduled": false
    }
]

This is how it should look like:
enter image description here

I am getting: ReferenceError: jsonObject is not defined in my console when using fetch to test POST submission form data to a test API endpoint

I am just beginning to learn javascript and am hung up on getting my code to POST submission data to a test api endpoint. My console is telling me ReferenceError: jsonObject is not defined. Please help, thanks

<form id="jobData" method="post">
    <fieldset>
        <label for="machineField">Heavy Equipment Machine Type</label>
        <input name="Machine" type="text"" id="machineField">
        </input>
        <label for="workField">Work To Be Performed</label>
        <input type="text"  name="work" id="workField">
        <label for="detailsField">Other Important Details</label>
        <textarea name="details" id="detialsField" cols="30" rows="10"></textarea>
        <button type="submit" name="submit">SEND</button>
    </fieldset>
</form>
<script>
    const url = "https://6fp4lq4r8d.api.quickmocker.com";
    const formEl = document.querySelector("form");
    formEl.addEventListener("submit", async (e) => {
      e.preventDefault();
      const formData = new FormData(formEl);
      const formDataSerialized = Object.fromEntries(formData);
      console.log(formDataSerialized, "formDataSerialized");
      try {
          const response = await fetch(url, {
              method: 'POST',
              body: JSON.stringify(jsonObject),
              headers: {
                  'Content-Type': 'application/jason'
              }
          });
          const json = await response.json();
          console.log(json);
      } catch(e){
          console.error(e);
          alert("An Error Occured");
      }
    });
</script>

Webpack on the backend: missing exports

I’m trying to use webpack on the backend to transpile this code (called sub.js):

export const foo1 = () => {
  console.log("I'm foo1");
};

console.log('loaded');

I can compile it and then import it fine. On import (require) I see the ‘loaded’, but the imported object is empty and in particular has no function foo1.

This is my webpack.config.js:

const path = require('path');
const webpack = require('webpack');

module.exports = {
  entry: `./sub.js`,
  module: {
    rules: [{
      test: /.(js|jsx)$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      options: {
        plugins: [
          '@babel/plugin-proposal-class-properties'
        ]
      },
    }],
  },
  resolve: {
    extensions: ['*', '.js', '.jsx'],
  },
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'backend.js'
  },
  mode: 'production',
};

My package.json:

{
  "name": "sub",
  "version": "1.0.0",
  "description": "",
  "main": "dist/backend.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.13.8",
    "@babel/plugin-proposal-class-properties": "^7.13.0",
    "@babel/preset-env": "^7.13.9",
    "@babel/preset-react": "^7.12.10",
    "babel-loader": "^8.2.2",
    "webpack": "^5.65.0",
    "webpack-cli": "^4.9.1"
  }
}

I test using:

> npx webpack && node --eval "r = require('./dist/backend.js'); console.log(r);"
asset backend.js 45 bytes [emitted] [minimized] (name: main)
runtime modules 396 bytes 2 modules
./sub.js 204 bytes [built] [code generated]
webpack 5.65.0 compiled successfully in 250 ms
loaded
{}

I was expecting to see:

loaded
{foo1: [Function]}

or similar.

RegEx Character set with conditional

I’m trying to do the next:

/b[abcd(e|f)]{5}b/g

Then, should be equivalente to:

/b([abcde]{5}|[abcdf]{5})b/g

But, actually, considering the parenthesis part of the set.

My input is letters with no order:

abedg cbade cfead acbdf

Should return: cbade acbdf, but it also return cfead. But cannot be e and f at the same time

Why does one function cause component to rerender but the other does not Nextjs?

In my Nextjs web application, one of my pages has two functions that allow for emails to be added or removed from an array using nextjs’s useState().

const [invites, setInvites] = useState([])
// other code
const lmao = () => {
    console.log(invites)
}
const addEmail = async (email) => {
    if(!invites.includes(email)) {
        setInvites([...invites, email])

    }
    lmao()
}
const removeEmail = async (email) => {
    let tempArray = invites
    const index = tempArray.indexOf(email)
    if(index > -1) {
        tempArray.splice(index, 1)
    }
    setInvites(tempArray)
    lmao()
}

The function addEmail successfully results in a component rerender, and when ran, will visibly update the page with the added email. However, the function removeEmail fails to rerender the page. I used the function lmao() to see that invites was indeed being changed as needed, the page just was not rerendering to display the change.

I have also looked at Why does setState([…arr]) cause a rerender but setState(arr) does not?, and it does not answer my question because in my case, the item passed into the mutator is not === to its previous value, unless I am missing something. Does anyone know why this is?

What is the unit of x and y in canvasrendering2d.moveTo() in canvas of html5?

everyone. I made a different sizes canvas and drew a line with the same values for moveTo() and lineTo() but I get different sized lines.

This is the code.

    function testCanvas(height, width){
    canvas = document.createElement("canvas");
    ctx = canvas.getContext('2d');

    canvas.style.display = "inline-block";
    canvas.style.border = "1px solid black";

    canvas.height = height;
    canvas.width = width;

    document.getElementById("chartContainer").appendChild(canvas);
    }

    function drawLine(x1, y1, x2, y2){
    ctx.beginPath();
    ctx.moveTo(x1,y1);
    ctx.lineTo(x2,y2);
    
    ctx.stroke();
    }
  1. When i go to inspect element > console and call:

     testCanvas(300,300);
     drawLine(10,50,110,50);
    

and

    testCanvas(150,150);
    drawLine(10,50,110,50);

The length of lines is not equal.
Now, if the input for moveTo and lineTo were in pixel unit, these lines would have same length isnt is? What is the default unit here?

How do you make an alert from API become text on a webpage?

I have it set up so you have a list of countries and when you click on it it gives a pop-up with the sub region and then shows the country flag next to the country. How can I change it so that the sub region shows up with the flags using my API?

var xhttp = new XMLHttpRequest();
var respJSON = [];
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    resp = this.responseText;
    respJSON = JSON.parse(resp);

    html = document.getElementById("list");
    html.innerHTML = "";

    for (var i = 0; i < respJSON.length; i++) {
      html.innerHTML += "<li id=" + i + " onClick='clickMe(" + i + ")'>" + respJSON[i].name + "</li>"
    }
  }
}
//connect our api
xhttp.open("GET", "https://restcountries.com/v2/all", true);
xhttp.send();

function clickMe(index) {
  li = document.getElementById(index);
  img = document.createElement("img")
  img.src = respJSON[index].flag;
  li.append(img); 
  {
    //create subregion text on website
    //unsure how to make it show as text and not as a pop-up
    alert(respJSON[index].subregion);
  }
}

cant create a new Database in Firebase

Hey Guys I really need your help its my first software project and Im a bloody beginner.

My Problem is that I cant create a new Database in Firebase I created a Database called User to store Profildata which works but now I need another to store something else heres my Code I cant find the mistake.

Everything is working but it dont creates the database on backend.
And I nearly used the same code which I used for the first Database.

function Waffen(){

  const [open, setOpen] = React.useState(false);
  const handleClose = () => setOpen(false);
  const handleOpen = () => setOpen(true);

  const [Hersteller, setHersteller] = useState(['Baretta', 
  'Walther']);
  const [Modell, setModell] = useState();
  const [Kaliber, setKaliber] = useState();
  const history = useHistory("");
  const [data] = useState({loading: false,});
  const { loading } = data;
  
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    await setDoc(doc(db, 'Waffen' ,auth.currentUser.uid),  
    
    { Hersteller: Hersteller, Modell: Modell, Kaliber: Kaliber 
    });
  
      setOpen(false)
      history.replace("/Profil");
    }; 
  




 return (
    <div >
      <Button onClick={handleOpen}>Meine Waffen</Button>
        <Modal 
          open={open}
          onClose={handleClose}>
          <Box sx={style} >
            <form  >

        <Grid
         container
         justifyContent="center"
         alignItems="center"
         spacing={2}
        >     
         
         <Autocomplete
            disablePortal
            id="combo-box-demo"
            options={Hersteller}
            sx={{ width: 300 }}
            renderInput={(params) =>  

      <TextField {...params}  label='Hersteller'
          value={Hersteller}  onChange={event => 
          setHersteller(event.target.value)}
      />}
      />
          

          <Grid item>
             <TextField sx={{ width: 300}} variant="outlined" 
               color="secondary" label="Modell" type="text"
               name="Modell" value={Modell} onChange={event => 
               setModell(event.target.value)}>
             </TextField>
          </Grid>

          <Grid item >
              <TextField sx={{ width: 300}} variant="outlined" 
               color="secondary" label="Kaliber" type="text"
               name="Kaliber" value={Kaliber} onChange={event => 
               setKaliber(event.target.value)}>
              </TextField>
          </Grid>
          
           <Grid item>
              <button onSubmit={handleSubmit} 
                  className="AnmeldenButton" >
                  {loading ? "Bearbeitet ..." : "Speichern"}
              </button>
          </Grid>

        </Grid>

           </form>
         </Box>
      </Modal>
    </div>

  ) ;
  }

  export default Waffen;