My object in javascript not returning the wanted value

I can’t seem to figure out how to do the object part, I need to make it calculate the age dynamically. I’ve written most of the stuff here and it works fine the only down side is my dynamic age calculation, I don’t know what I’m doing wrong and can’t find my mistake.

<html>
    <head>
        <title>WEB PROGRAMIRANJE</title>
    </head>
    <body>
        <script type="text/javascript">
        var niza=new Array (9,8,7,6,5,4,3,2,1);
        var izbrisani=niza.shift();
        var izbrisanip=niza.pop();
        var sortirani=niza.sort();
       // form an arrey delete first and last:
       // sort the arrey:
        document.write(sortirani);  

        function babati(a,b,c)
        {
            var total;
            total=(a+b+c)/3;
            alert(total);
        }
        document.write("<br>");
        </script>
                <input type="button" value="Call" onClick="babati(0,5,10)";>
                <script type="text/javascript">
                document.write("<br>");
                var ucenik=new Object();
        // giving them value to object elements:
        ucenik.ime="Name";
        ucenik.prezime="Surname";
        ucenik.godina=2021;
        ucenik.roden=2003;
        // printing the object elements:
        document.write(ucenik.ime);
        document.write("<br>");
        document.write(ucenik.prezime);
        document.write("<br>");
        document.write(ucenik.roden);
        document.write("<br>");
        // The function:
        // This will calculate the age dinamicly This year - Birth year:
        ucenik.vozrast=function()
        {
            this.godina - this.roden;   
        }
        ucenik.vozrast();
        document.write(ucenik.vozrast);
         //This line above prints the dynamic age:
        </script>
    </body>
</html>

Can someone please change this from python into javascript for me? [closed]

import urllib2
import json
import random
import webbrowser

songsbytemp= {
   'scorching':
      {
      'ss-collie':
         {
         'url':    'https://www.youtube.com/watch?v=TLcmtBA-W_s',
         'title':  'Collie Man',
         'artist': 'Slightly Stoopid',
         'mood':   'happy',
         'tempo':  'andante'
         },
      'beck-loser':
         {
         'url':    'https://www.youtube.com/watch?v=YgSPaXgAdzE',
         'title':  'Loser',
         'artist': 'Beck',
         'mood':   'happy',
         'tempo':  'allegro'
         }
      }, #end of scorching
   'hot':
      {
      'ween-voodoo':
         {
         'url':    'https://www.youtube.com/watch?v=sRCRi8qfKu0',
         'artist': 'Ween',
         'title':  'Voodoo Lady',
         'mood':   'getdown',
         'genre':  'rock',
         'tempo':   'andante'
         },
       'ween-voodoo':
         {
         'url':    'https://www.youtube.com/watch?v=sRCRi8qfKu0',
         'artist': 'Ween',
         'title':  'Voodoo Lady',
         'mood':   'getdown',
         'genre':  'rock',
         'tempo':   'andante'
         }
      }, #end of hot
   'nice':
      {
      'al-weneedhelp':
         {
         'url':    'https://www.youtube.com/watch?v=d93_iILNji8',
         'artist': 'The Album Leaf',
         'title':  'We Need Help',
         'mood':   'sad',
         'genre':  'rock',
         'tempo':   'andante'
         },
      'am-when the sun goes down':
         {
         'url':    'ww.youtube.com/watch?v=d93_iILNji8',
         'artist': 'The Arctic Monkeys',
         'title':  'When the Sun Goes Down',
         'mood':   'sad',
         'genre':  'rock',
         'tempo':   'andante'
         }
      }, #end of warm
   'lukewarm':
      {
      'bb-drytherain':
         {
         'url':    'https://www.youtube.com/watch?v=wsbR2dEmHGc',
         'title':  'Dry the Rain',
         'artist': 'Beta Band',
         'mood':   'happy',
         'genre':  'indie',
         'tempo':   'andante'
         },
      'bb-castars':
         {
         'url':    'https://www.youtube.com/watch?v=gxzMbAMO73k',
         'title':  'California Stars',
         'artist': 'Billy Brag and Wilco',
         'mood':   'happy',
         'genre':  'americana',
         'tempo':   'andante'
         }
      }, #end of lukewarmm
   'frigid':
      {
      'es-bars':
         {
         'url':    'http://www.youtube.com/watch?v=zH8-lQ9CeyI',
         'title':  'Between the Bars',
         'artist': 'eliott smith',
         'mood':   'sad',
         'genre':  'rock',
         'tempo':   'andante'
         },
      'so-mag':
         {
         'url':     'https://www.youtube.com/watch?v=q0IeGx5-gsk',
         'title':   'Hold On Magnolia',
         'artist':  'Songs: Ohia',
         'mood':    'sad',
         'genre':   'indie',
         'tempo':   'lento'
         }
      }, # end of cold
   'freezing':
      {
      'so-lion':
         {
         'url':    'http://www.youtube.com/watch?v=zH8-lQ9CeyI',
         'title':  'Between the Bars',
         'artist': 'eliott smith',
         'mood':   'sad',
         'genre':  'rock',
         'tempo':   'andante'
         },
      'rh-lotus':
         {
         'url':    'https://www.youtube.com/watch?v=cfOa1a8hYP8',
         'title':  'Lotus Flower',
         'artist': 'Radiohead',
         'mood':   'sad',
         'genre':  'rock',
         'tempo':   'lento'
         },
      'so-mag':
         {        
         'url':     'https://www.youtube.com/watch?v=wxAaf16xXRk',
         'title':   'Lioness',
         'artist':  'Songs: Ohia',
         'mood':    'sad',
         'tempo':   'lento',
         }
      } # end of freezeing
  
   } # end of temp ranges         

#pull api from wunderground                                                                                                                                                                          

def gettemp():
   f = urllib2.urlopen('http://api.wunderground.com/api/e7fa1fe6de662dfd/geolookup/conditions/q/CA/San_Francisco.json')
   json_string = f.read()
   parsed_json = json.loads(json_string)
   location = parsed_json['location']['city']
   temp_f = parsed_json['current_observation']['temp_f']
   print "Current temperature in %s is: %s" % (location, temp_f)
   f.close()
   return temp_f

def getsongurl(temprange):
   songs=songsbytemp[temprange]
   mysong=random.choice(songs.keys())

   for key in songs[mysong]:
      print key,
      print songs[mysong][key]


   url=songs[mysong]['url']
   print 'url =', url
   return url


        #get the current temp                                                                                                                                                                                
temp=gettemp()

# Chose a song from the proper temp range                                                                                                                                                            
if temp > 90:
   print "above 90 and scorching"
   url=getsongurl('scorching')
elif temp > 82:
   print 'over 82, less than 90, and hot'
   url=getsongurl('hot') 
elif temp > 72:
   print "over 72, less than 82, and nice"
   url=getsongurl('nice')
elif temp > 65:
   print "over 65, under 72, and lukewarm"
   url=getsongirl('lukewarm')
elif temp > 55:
   print "over 55, under 65, and frigid"
   url=getsongurl('frigid')
elif temp > 45:
   print "over 45, under 55, and cold!"
   url=getsongurl('freezing')
else:
   print "Just go back to bed.  It's too cold to be alive"


# Play it!                                                                                                                                                                                           
webbrowser.open_new(url)

I need to be able to have a background music for my weather app that I am making in javascript. I I am not familiar with python and I wanted to see if anyone can translate it for me. It would be kindly appreciated. It is the only weather based music api that I have come across after researching for some time now.

A Grid slowing the moving element on JS canvas

I’m drawing a grid on a JavaScript canvas on this canvas I also have a moving element so the Grid can be on/off with a button all is well apart from the speed of the moving element when grid is on it becomes extremely slow. I’m not really sure where am I going wrong. Can someone please give me some help. Thank you

HTML

<div>
    <input type=button id="up" onClick=move_img(id); value='Up'>
    <input type=button id="down"  onClick=move_img(id); value='Down'>
    <input type=button id="left"  onClick=move_img(id); value='Left'>
    <input type=button id="right"  onClick=move_img(id); value='Right'>
    <input type=button id="stop"  onClick=move_img(id); value='Stop'>
    <input type=button id="grid"  onClick=gridOn(); value='Grid'>
    <br>
    <p></p>
</div>

JavaScript

    var isGrid = new Boolean(false);
    var canvas = document.getElementById("canvas");
    b = canvas.getContext("2d");

    var width = canvas.width = 600;
    var height = canvas.height = 400;
    
    document.body.appendChild(canvas);

    b.fillStyle = "#F0F8FF";
    b.fillRect(0, 0, canvas.width, canvas.height);

    var posX = 10;
    posY = 10;
    x = 0;
    y = 0;
    
    setInterval(function () {
   
        b.fillStyle = "#F0F8FF";
        b.fillRect(0, 0, width, height);
        posX += x;
        posY += y;

        if (posX > width - 20) {
            x = 0;
            posX = width - 20;
        }
        if (posX < 0) {
            x = 0;
            posX = 0;
        }
        if (posY > height - 20) {
            y = 0;
            posY = height - 20;
        }
        if (posY < 0) {
            y = 0;
            posY = 0;
        }

    b.fillStyle = "red";
    b.fillRect(posX, posY, 20, 20);
    
    /**  Grid ***/
    if(isGrid){
        drawGrid();
    }
    /**************/
    
    }, 5)
   
    function move_img(id) {
        switch (id) {
        case "down":
            moveDown();
            break;
        case "up":
            moveUp();
            break;
        case "left":
            moveLeft();
            break;
        case "right":
            moveRight();
            break;
        case "stop":
            moveStop();
            break;
        }
    } 
    
    function moveDown(){
        x = 0;
        y = 1;
    }
    function moveUp(){
        x = 0;
        y = -1;
    }
    function moveLeft(){
        x = -1;
        y = 0;
    }
    function moveRight(){
        x = 1;
        y = 0;
    }
    function moveStop(){
        x = 0;
        y = 0;
    }
    function gridOn() {
        if(isGrid){
            isGrid = false;
        }else{
            isGrid = true;
        }
    } 
    
    function drawGrid(){    
        b.strokeStyle = 'black';
        b.lineWidth = 0.5;
        
        for(i = 0; i<= 600; i=i+40){
            b.moveTo(i, 0);
            b.lineTo(i, 600);
            b.stroke();
        }
        for(j = 0; j<= 600; j=j+40){
            b.moveTo(0, j);
            b.lineTo(600, j);
            b.stroke();
        }
    }

Скрипт меняет имя отправителя на “[email protected]”. Но получатель получает письмо без аватарки (иконки). Как разрешить проблему? [closed]

Функция отправляет  письмо клиенту, заполнившему форму, на указанный в форме Email.

`function sendEmailToClient() {

Текущая Гугл Таблица записана в переменную:

var ss= SpreadsheetApp.getActiveSpreadsheet ();

Лист текущей таблицы с именем "Ответы на форму (1)", в который загружаются ответы из формы, записан в переменную:

var listAnswers = ss.getSheetByName (“Ответы на форму (1)”);

Получен email клиента из ячейки с адресом: последняя строка, 4 ряд, – и записан в переменную:

var clientEmail = listAnswers.getRange (listAnswers.getLastRow (),2).getValue ();

  var body =  "Здравствуйте!</br>"+


  "Благодарю за заказ!</br>"+


  "В ближайшее время я с Вами свяжусь.";


Отправлено письмо клиенту (отправителем будет тот, кто запускает скрипт):


Для отправки используется функция sendEmail, метод класса MailApp


  MailApp.sendEmail(clientEmail, "Ваша заявка получена", "",{


  htmlBody:body,


  name: "[email protected]"


  }); 

}`

Receiving encoded JSON response from API call

I’m sending a POST request to a REST API endpoint, and am receiving JSON response back filled with question mark diamonds and other unicode characters. But when I test API on Postman, I am correctly receiving JSON response. Here is my code for calling API:

xhr.open(method,url);
xhr.setRequestHeader("Authorization", "Bearer" + " " + accessToken);
xhr.setRequestHeader("Content-Type", "application/json");

xhr.onreadystatechange = function () {
  if (xhr.readyState === 4) {
     console.log(xhr.status);
     console.log(xhr.responseText);
  }};
xhr.send(JSON.stringify(data));

The response I’m getting is like this: ��}�r�8���|ʧj���t���<Pe3�H���8�灖(��2�!��=S]�?䜟�_r��I�”

Read and store content of file React Native

I know this is probably one of the dumbest question but i can’t seem to find the solution, I simply want to read the content of a file and store it in a variable without using any external library. How do we do that in React Native ? Thank you.

if you need more info about what i’m exactly trying to do: I want to store this SVG file’s content to return it in a component, and using ” import Bla from “./bla.svg” ” is working on android and ios only and not web (I’m using expo) and i know that returning the content of the svg (ex: <svg … /> ) works on web.

How do I confirm user permission for mediaDevices correctly?

It’s safe to say the snippet below will error any-time there’s a problem but between all browsers, that DOMExecution is a different response. I could go ahead and collect them all and be compliant this way but are there other ways?

This is what I use to soft-check:

try {
  await navigator.mediaDevices.getUserMedia({
    audio: true,
    video: true
  });
} catch (e) {
  Message.receive.public(`Media Error: ${e.message}.`);
}

I would return and call it quits if there’s a catch, but during media-selection there’s possibly 1 out of many devices in use and that will throw an error and with my app that won’t matter they can try the device any ways to see if it produces or not.

random images change with every refresh made

so I have linked two images in HTML from the folder: images/ however in javascript I’m trying to make these images for the dice to randomly change after every time refreshes.
I’m not sure why isn’t working

here is the HTML code

<div class="container">
  <h1>Refresh Me</h1>

  <div class="dice">
    <p>Player 1</p>
    <img class="img1" src="images/dice6.png">
  </div>

  <div class="dice">
    <p>Player 2</p>
    <img class="img2" src="images/dice6.png">
  </div>

    </div>

and here is the js code

imgArray = [
"dice1.png",
"dice2.png",
"dice3.png",
"dice4.png",
"dice5.png",
"dice6.png"
]


function images(){
  // the random images
  var randomNumber1 = Math.floor(Math.random() * imgArray.length);
  // get images at randomNumber1
  selectedImages = imgArray[randomNumber1]
  // display the images()
  document.getElementByClassName("img1").src = "./images/${selectedImages}"

}

Note: I’m a new learner still trying to understand javascript. thank you for your humble reply and help. and if isn’t too much to make the explanation simple so I could follow.

boothstrap from-control input bigger

I’m using boothstrap form-control for my project,
and I want the text area to be bigger for the user to add his text, I don’t want it to be just one line.
Of course I tried to give the input an id and play with his height and width in css.
it doesn’t work. can you please help me?
I need to use an input so putting textare type is not possible as well.
that’s the code from the html:

      />`enter code here`
<div id="formDiv">
  <div class="p-3" id="inputsDiv">
    <div class="input-group mb-3 pt-4" id="inputDiv">
      <span class="input-group-text">Task Info:</span>
      <input
        type="text"
        id="taskInfo"
        class="form-control"
        placeholder="Task Info:"
        aria-label="Task Info:"
        aria-describedby="basic-addon1"
      />
    </div>
    </div>

Cypress: Read from file and upload it again

I am trying to go through an number of tab-separated words in a file and check if the key is in the structure (json):
The json object looks like this:

[
  {
    "Name" : "Cypress Upload 1", 
    "Description" : "Cypress upload descrition 1"
  },
  {
    "Name" : "Cypress Upload 2",
    "Description" : "Cypress upload descrition 2"
  }
]

The code looks like this:

cy.readFile(uploadPathFile).then((jData) => {
      cy.log(jData[0].Name);
      const objLn = Object.keys(jData).length;
      cy.get('@LASTDOWNLOADEDFILE').then((downFile) => {
        cy.readFile(downFile as unknown as string).then((txt) => {
          const lines = (txt as string).split('t');
          for (let o = 0; o < objLn; o++) {
            for (let i = 0; i < lines.length; i++) {
              cy.log(`Key ${lines[i]}  ${jData[o].Name}`);
              if (jData[o].hasOwnProperty(lines[i])) {
                cy.log(`Found Key ${lines[i]}`);
              }
            }
          }
        });
      });
    });

The first log: gives me the correct value of the Name key at position 0

18 log  Cypress Upload 1

The second log lists me all the names from the tab separated file:

...
21 log Key "ID" Cypress Upload 1
22 log Key "Name" Cypress Upload 1
23 log Key "Synonym 1" Cypress Upload 1
...

But it does not show the key found even though “Name” is there and jData[0].Name gives a value! Why is the line with “if (jData[o].hasOwnProperty(lines[i])) {” never true. I also tried “if (jData[o][lines[i]]) {

Luxon: get an array of offsets and untils (like we can in moment-timezone)

With the moment-timezone library I’m currently just retrieving the raw information for a particular timezone and then using that directly in my downstream code.

const zone = moment.tz.zone('Europe/London');

This is an object containing the following:

{
    "name":"Europe/London",
    "abbrs":["GMT","BST","GMT","BST", ...],
    "untils":[-1691964000000,-1680472800000,-1664143200000,-1650146400000, ...],
    "offsets":[0,-60,0,-60,0, ...],
    "population":10000000
}

The offsets and untils arrays are really all I need from moment… the rest I handle myself “manually” in the downstream code using the offsets and untils arrays (or actually just a small subset thereof)… without having to rely on moment as a dependency.

Is there an equivalent way to extract offsets and untils arrays in the luxon library?

Set custom dataTransfer with react-dnd

I am using the react-dnd library to handle drag and drop in React (with the multi back-end to have support for both desktop and mobile platforms) . I’m also using the Ace editor in my app.

The Ace editor accepts dragging and dropping text into the editor as long as the dataTransfer object of the event has {Text: thetexttopaste}.

I would like to generate this dataTransfer for the draggable items that I already handle with react-dnd. However, I can’t find a way to set this dataTransfer data, nor to access the native event.

Here’s the code where I declare my react-dnd draggable items:

export function AvailableBlock(props: AvailableBlockProps) {
    const {block} = props;

    const [collected, drag, dragPreview] = useDrag(() => ({
        type: 'available-block',
        item: {type: 'Text'}
    }))

    return (
        <div className="task-available-block" ref={drag}>
            <div className="task-available-block-name">
                {block.caption}
            </div>
        </div>
    );
}

Is there a way to do it?

How to prevent Chrome and Brave browsers from issuing a Browser notification after javascript removes an item from sessionStorage

As far as I can tell this browser behaviour is new.

I have searched using Google, Bing and Brave Search and can find no trace of the behaviour being documented.

When javascript computationally removes an item from sessionStorage, the browser drops a notification:

[Site] says:

[ItemName] Item removed from sessionStorage

User feedback reveals this notification hinders seamless UX.

One user reported waiting for several minutes before deleting the tab – she didn’t understand the message and she didn’t realise that she needed to press the “OK” button in the bottom right hand corner of the notification to make it go away and enable the page to finish loading.


Example:

sessionStorage.setItem('Test Key', 'Test Value');

setTimeout(() => sessionStorage.removeItem('Test Key'), 300);

/*

It doesn't look like StackSnippets will allow the javascript above.

*/

Is there a way to prevent the browser issuing a notification when javascript removes an item from sessionStorage ?


N.B. This is almost certainly a Blink issue.

I’ve noted that Firefox does not behave in the same manner as Chrome and Brave.