Active menu item based on URL and ID

I want to have active menu items in my navigation based on URL and ID, not href. None of the available solutions (this one, this one , or this one) worked for me.

My Navigation looks like this

<nav id="PageNavigation">
    <div class="nav_ebene_2">
        <div role="button" class="nav-item" id="P_Bogendaten.aspx?IDNavi=194">
            <p>menu item 1</p>
        </div>
    </div>
</nav>

The URL, if clicked on menu item 1, is https://example.de/App_AspxFiles/P_Bogendaten.aspx?IDNavi=194. I want to add the class menuactive to the parent element (div which includes nav_ebene_2)

I need to compare the id with the current url, if it matches, add menuactive. This would be my way, but the if conditions is never true.

  var currenturl  = window.location.href
  for (const div of document.querySelectorAll("#PageNavigation nav-item")) {
    if (div.id == currenturl ) {
      div.parentElement.classList.add("activemenu");
    }
  }

Thank you very much!

Chanel ID returns undifined DISCORD JS V13

I have a question I am currently upgrading my Discord bot to DISCORD JS V13. Now I’m trying to get the Chanel ID of certain Chanels, but I keep getting undifiend or 0 back. I’ve already tried to rewrite my old code from the DISCORD JS V12, but it doesn’t work. There is also not much online about DISCORD JS V13.

const path = require("path");
const fs = require('fs');
const {
    Client,
    Intents,
    Collection
} = require('discord.js');
require("dotenv").config();

const client = new Client({
    intents: [Intents.FLAGS.GUILDS]
})
const functions = fs.readdirSync("./src/functions").filter(file => file.endsWith(".js"));
const eventFiles = fs.readdirSync("./src/events").filter(file => file.endsWith(".js"));
const commandFiles = fs.readdirSync("./src/commands").filter(file => file.endsWith(".js"));

client.commands = new Collection();
client.buttons = new Collection();

(async () => {
    for (file of functions) {
        require(./functions/${file})(client);
    }

    client.handleEvents(eventFiles, "./src/events");
    client.handleCommands(commandFiles, "./src/commands");
    client.handleButtons();
    client.login(process.env.BOT_TOKEN);
    const connection = client.dbLogin();
    console.log(await client.channels);
    client.channels.fetch('691022255098036375')
        .then(channel => console.log(channel.name))
        .catch(console.error);
    console.log(await client.channels.cache.get("691022255098036375")); //undefined
    //client.joinHome();
})();

live search in input with checkbox filter value

I have a select in which the checkbox is located, it also contains an input through which I want to find the necessary items. I did the search like this, first I accept an array and then lowercase it and search for matches. Somehow I need to match the required id to exclude unavailable ones and display the necessary checkboxes

In simple terms, I want to filter my query and display it in real time.

I must use only vanila JS

let search = document.getElementById("search"); 
let s = document.querySelectorAll("input[type=checkbox][name=one]");

//s.forEach((item) => {
search.addEventListener("input", () => {
  let data = [];
  
  let count = Array.from(s).map((i) =>  i.value.toLowerCase().includes(search.value.toLowerCase())
  );

  console.log(count);
  
});
//});
<div id="checkboxes2">
        <div class="control">
          <input
            class="input"
            type="text"
            placeholder="Поиск"
            id="search"
          />
          <span class="icon is-small is-left">
            <span class="searchIcon"></span>
          </span>
        </div>
        <label for="one2" class="select_label">
          <input type="checkbox"  value="Показать все" name="one" id="one2" />Показать все
          <span class="select_label-icon"></span
        ></label>
        <label for="one2" class="select_label">
          <input type="checkbox"  value="Показать все" name="one" id="one2" />Показать все
          <span class="select_label-icon"></span
        ></label>

        <label for="one2" class="select_label">
          <input type="checkbox"  value="Показать все" name="one" id="one2" />Показать все
          <span class="select_label-icon"></span
        ></label>
        <label for="one2" class="select_label">
          <input type="checkbox"  value="Показать все" name="one" id="one2" />Показать все
          <span class="select_label-icon"></span
        ></label>
        <label for="one2" class="select_label">
          <input type="checkbox" name="one2" id="one2" />Показать все
          <span class="select_label-icon"></span
        ></label>
        <label for="one3" class="select_label">
          <input type="checkbox" value="Наименование лекарства" name="one" id="one3" />Наименование лекарства
          <span class="select_label-icon"></span
        ></label>
        <label for="one4" class="select_label">
          <input type="checkbox" value="Наименование лекарства" name="one" id="one4" />Наименование лекарства
          <span class="select_label-icon"></span
        ></label>
        <label for="one5" class="select_label">
          <input type="checkbox" value="Наименование лекарства в две длинных строки" name="one" id="one5" />Наименование лекарства
          в две длинных строки <span class="select_label-icon"></span
        ></label>
      </div>

enter image description here

Html table horizontal scroll in the middle like on touchscreens

I’m trying to horizontal scroll the table not with the scrolling bar, but with the mouse inside the table just like its done with a touch screen. Does anyone know if its possible to do this without a plugin? To make the table horizontally “draggable” just for scrolling?

Ps.: I know that the snippet below does what I want in mobile mode, but I want to achieve that with the mouse.

.container {
  width: 30em;
  overflow-x: auto;
  white-space: nowrap;
}
<div class="container">
  <table>
    <tbody>
      <tr>
        <td>Image 1</td>
        <td>Image 2</td>
        <td>Image 3</td>
        <td>Image 4</td>
        <td>Image 5</td>
        <td>Image 6</td>
        <td>Image 1</td>
        <td>Image 2</td>
        <td>Image 3</td>
        <td>Image 4</td>
        <td>Image 5</td>
        <td>Image 6</td>
      </tr>
      <tr>
        <td>Image 1</td>
        <td>Image 2</td>
        <td>Image 3</td>
        <td>Image 4</td>
        <td>Image 5</td>
        <td>Image 6</td>
        <td>Image 1</td>
        <td>Image 2</td>
        <td>Image 3</td>
        <td>Image 4</td>
        <td>Image 5</td>
        <td>Image 6</td>
      </tr>
    </tbody>
  </table>
</div>

enter image description here

Issue With Clicks Inside Mousedown

I have multiple buttons that can be clicked by mousedown/touchstart, after 2 seconds, you get a popup to make sure, and you can click “yes” or “no”.

The issue comes when you click one, then select “no” and click another one. When logging the “data-id”, the first one clicked is the one passed, instead of the clicked one.

I thought this was an event.preventDefault(), event.stopImmediatePropagation issue, but this is not helping me at all, I don’t know what else to try anymore or know WHY this is happening.

Here’s a preview of the JS file:

$('.btn').on('mousedown touchstart', function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    let button = $(this);
    console.log('Before setTimeOut: ', button.attr('data-treatment-id'));
    
    timer = setTimeout(async function() {
    $('#make-sure-location').show();
    
    $('#not-in').on('click', function(e) {
      console.log('not in location: ', button.attr('data-treatment-id'));
      e.preventDefault();
      e.stopImmediatePropagation();
      $('#make-sure-location').hide();
      clearTimeout();
    });

    $('#inside').on('click', function(e) {
      console.log('on location: ', button.attr('data-treatment-id'));
      e.preventDefault();
      e.stopImmediatePropagation();
    });
    
  }, 2000)
})

Here’s a working fddle:
https://jsfiddle.net/rj8ofLym/28/

To recreate issue:

  1. MouseDown first button
  2. Click “No” on div.
  3. Check logs (correct “data-id”)
  4. MouseDown second button
  5. Click “No” on div.
  6. Check logs (INcorrect “data-id” – still first one)

push (redirect) to a route after successful login

Till now I was redirecting to the User Dashboard from the React component, but I want to apply a different approach, I want to redirect after getting the success response from the saga itself.

For this, I have attempted to use redux-first-history (which comes with the support of react-router6) I have followed their documentation, almost everything is working but an action @@router/CALL_HISTORY_METHOD getting called twice.

Here are my routes

export default function App() {
  return (
    <AuthProvider>
      <Router history={history}>
        <Routes>
          <Route element={<Layout />}>
            <Route path="/" element={<PublicPage />} />
            <Route path="/login" element={<LoginPage />} />
            <Route
              path="/protected"
              element={
                <RequireAuth>
                  <ProtectedPage />
                </RequireAuth>
              }
            />
          </Route>
        </Routes>
      </Router>
    </AuthProvider>
  );
}

which goes across the project, below is my store.

import { applyMiddleware, compose, createStore } from "redux";
import { persistReducer, persistStore } from "redux-persist";
import storage from "redux-persist/lib/storage";
import createSagaMiddleware from "redux-saga";
import rootReducer from "../store/reducers";
import { watchAuth } from "../store/sagas/index";
import { createReduxHistoryContext } from "redux-first-history";
import { createBrowserHistory } from "history";

const composeEnhancers =
  process.env.NODE_ENV === "development"
    ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
    : null || compose;

const { createReduxHistory, routerMiddleware } = createReduxHistoryContext({
  history: createBrowserHistory(),
  oldLocationChangePayload: true,
  showHistoryAction: true,
});
const sagaMiddleware = createSagaMiddleware();
const middleware = [sagaMiddleware, routerMiddleware];
const persistConfig = {
  key: "root",
  storage,
  whitelist: ["auth"],
};

const persistedReducer = persistReducer(persistConfig, rootReducer);

export const store = createStore(
  persistedReducer,
  composeEnhancers(applyMiddleware(...middleware)),
);
const persistor = persistStore(store);
sagaMiddleware.run(watchAuth);

export const history = createReduxHistory(store);
export default store;
export { persistor };

and my Saga

import { call, delay, put } from "redux-saga/effects";
import axios from "../../../config/axios";
import {
  authFail,
  authStart,
  authSuccess,
  checkAuthTimeout,
  logout,
  logoutSucceed,
  setAlert,
} from "../../actions/auth/auth";
import { LOGIN_API } from "../../apiCollecitions";
import { push } from "redux-first-history";

export function* authLoginSaga(action) {
  yield put(authStart());

  const authData = {
    email: action.email,
    password: action.password,
  };
  try {
    const response = yield axios.post(
      `${LOGIN_API}?lng=${localStorage.getItem("i18nextLng")}&active=true`,
      authData,
    );
    yield localStorage.setItem("token", response.data.token);
    yield localStorage.setItem("expirationDate", expirationDate);
    yield put(authSuccess(response.data.token));
    yield put(push("/protected")); //should redirect to the specified route
  } catch (error) {
    yield put(authFail(error.response.data.message));
  }
}

I have also set up a sample GitHub repo for the same, for your reference.

NUXT JS insert Array inside Array and display forEach

Good afternoon everyone!

I’m stuck since 3 days searching answers in forums and here also, and i can’t solve it.. Maybe you can help about this problem:

In javascript is easier, but in NUXT we can’t insert Javascript where we wan’t..

In the component page:

<script>
  async fetch() {
      this.ArraySkills= await fetch(`https://api.test/player/${id}`
      ).then((res) => res.json ())
      
    },
    data () {
      return {
        ArraySkills: []
      }
    }
</script>

This url is a test. But it’s return an array about skills of player 1. I already display the skills of this player.

But i need to display the forEach players, their skills (40 players).

I created an ArraySkills. And i would like to visit the url1, url2, url3 etc.. And to push() inside the ArraySkills

In pure JS i would done :

let id=1
while (id<41) {
 id++;
  async fetch() {
      this.ArraySkill= await fetch(`https://api.test/player/${id}`
      ).then((res) => res.json ())

    },

   ArraySkills.push(ArraySkill);

}
#And then he will fill the ArraySkills with the 40 players

But in Nuxt it's seems harder :/

React Native Components Do Not Recognize Taps

I have just recently switched to React navigation v6 in my RN app and I can’t seem to understand why my Button(s) and Touchable(s) do not recognize onPress function the second time they are being pushed.

The scenario:

  1. I launch Home Screen.
  2. Press go to test screen button. The console prints the message.
  3. On Test Screen press go back. The console prints the message. I go back.
  4. Back on the Home Screen the button doesn’t work anymore. Console does not print the message

Home.tsx

<View style={{ flex: 1, paddingTop: 30 }}>
      <Button
        title='go to test screen'
        onPress={() => {
          console.log('pressed to test');
          navigate(TEST_SCREEN);
        }}
      />
</View>

TestScreen.tsx

<View style={{flex: 1, paddingTop: 30}}>
   <Button
     title='go back'
     onPress={() => {
       console.log('pressed go back');
       goBack();
     }}
   />
</View>

navigate func:

export function navigate(name: string, params?: any | undefined) {
  if (navigationRef.isReady()) {
    navigationRef.navigate(name, params);
  }
}

navigator:


const Home = createStackNavigator();

export default function HomeNavigator(): JSX.Element {
  return (
    <Home.Navigator
      initialRouteName={HOME_SCREEN}
      screenOptions={{ headerShown: false }}
    >
      <Home.Screen name={HOME_SCREEN} component={HomeScreen} />
      <Home.Screen name={TEST_SCREEN} component={TestScreen} />
    </Home.Navigator>
  );
}

routes:

export const HOME_SCREEN = 'Home';
export const TEST_SCREEN = 'Test';

Using HTMLCanvas element how to draw line with specific condition in Vuejs?

var example1 = new Vue({
  el: '#example-1',
  data: {
    questions: [{
        id: '1',
        message: '1',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '2',
        message: '2',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '3',
        message: '3',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '4',
        message: '4',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '5',
        message: '5',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '6',
        message: '6',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '7',
        message: '7',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
    ],
    answers: [{
        id: '1',
        message: '1',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '2',
        message: '11',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '3',
        message: '3',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '4',
        message: '2',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '5',
        message: '5',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '6',
        message: '2',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '7',
        message: '4',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '8',
        message: '5',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '9',
        message: '4',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
      {
        id: '10',
        message: '4',
        checked: false,
        statuses: ['match', 'closeTo', 'veryfar']
      },
    ]
  },
  methods: {

  }
})
.example-1 {
  float: left;
}

.example-2 {
  float: right;
  margin-top: -144px;
}

.container {
  padding: 20px;
}

.container2 {
  width: calc(100% - 105px);
  padding: 8px 0;
  height: 30px;
  box-sizing: border-box;
}

.h-line {
  height: 1px;
  margin-bottom: 18px;
  width: 100%;
  background-color: black;
}
<div class="container">
  <div id="example-1">
    <div v-for="que in questions" :key="que.id" :que="que">
      <input type="checkbox" v-model="que.checked" /> {{ que.message }}
    </div>



    <div class="example-2">
      <div v-for="ans in answers" :key="ans.id" :ans="ans">
        <input type="checkbox" v-model="ans.checked" /> {{ ans.message }}

      </div>
    </div>

Logic I am trying to achieve :- https://stackblitz.com/edit/vue-laepf5

Using above provided logic in “stackblitz”. I am trying to write logic into two components and achieve the same functionality. During that process, i am facing multiple issues like,

[Vue warn]: Error in v-on handler: “TypeError: fromEl.getBoundingClientRect is not a function”
TypeError: fromEl.getBoundingClientRect is not a function

Codesandbox link, Where trying to split logic in two components.

https://codesandbox.io/s/laughing-star-5w2bq?file=/src/components/One.vue

javascript donwload image not working as expected

I have an image that was readed to javascript.

I used sublime text to see the image and it is like this:

enter image description here

I readed this image and generate javscript arrayBuffer of Uint8Array

Inside this arrayBuffer, i see also ffd8 ffe0 like in photo above.

Now, i need to downlaod it to local machine, i used

 var blob1 = new Blob([byteArray], {type: 'application/octet-stream'});
                var fileName1 = "cool.bin";
                function saveAs(blob, fileName) {

    var url = window.URL.createObjectURL(blob);
    var anchorElem = document.createElement("a");
    anchorElem.href = url;
    anchorElem.download = fileName;
    anchorElem.style = 'display: none';

    document.body.appendChild(anchorElem);
    anchorElem.click();

    document.body.removeChild(anchorElem);

    // On Edge, revokeObjectURL should be called only after
    // a.click() has completed, atleast on EdgeHTML 15.15048
    setTimeout(function() {
        window.URL.revokeObjectURL(url);
    }, 1000);
}

After i downlaoded this image from javascript,
I see in sublime text diffrent bytes

enter image description here

What worng with my javascript donwload code ?

Google Places Autocomplete API error, “google is not defined”

I am scaffolding a simple prototype using google places and maps api using Vue.

In index.html, I added the script tag, libraries, and api key, I get 200 response in the network tab.

        <script src="https://maps.googleapis.com/maps/api/js?key=My-api-key&libraries=places" async defer></script>

In App.vue, I added the following

 <input ref="autocomplete" type="text" />
 ...
<script>
  export default {
  name: "App",
  data() {
   return {
     autocomplete: "",
    };
  },
  methods: {},
  mounted() {
    const center = { lat: 40.84498856765032, lng: -73.71060855293794 };
    // Create a bounding box with sides ~10km away from the center point
    const defaultBounds = {
    north: center.lat + 0.1,
    south: center.lat - 0.1,
    east: center.lng + 0.1,
    west: center.lng - 0.1,
  };
  const originAutoComplete = google.maps.places.AutoComplete(
    this.$refs["autocomplete"],
   {
     bounds: defaultBounds,
   }
 );
 originAutoComplete.addListener("place_changed", () => {
   console.log(originAutoComplete.getPlace());
 });

enter image description here

How do I resolve this error? Is there a way to initialize this in App.vue script tag? The example google developers youtube works great, but I’d like to implement this in a Vue context.
One other note, I tried adding window before the .google, no dice.

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();
        }
    }