Weather app doesn’t render full header info until permanent permission is granted from the user

I’ve been stuck on this problem for a couple of days now and I think it’s time to ask.

I have this weather app I’m building as practice, and so far I can retrieve the API data I’m using and storing it in functions and variables just fine, but I have a big problem: whenever the user gets asked to give permission to the browser to use their location, it just renders the last function on the screen, but whenever the user gives permanent permission for the browser to retrieve their location, and then reload the page, the app renders the info just fine. Why is this happening? , here’s the code:

main document:
import { weatherCodeObject } from './weathercodeobject.js'
import { getWeather } from './defaultweather.js'


// Prints the header's climate information: 

const temperatureDisplay = document.querySelector(".temperature");
const weatherStatus =  document.querySelector(".weather-status");
const tempParameters =  document.querySelector(".temp-parameters");

//Header current temp display
    
    const displayCurrentWeather = async () => {
        
         const { currentWeather } = await getWeather();
         const displayedTemp = temperatureDisplay.append(`${Math.round(currentWeather.temperature)}°F`);
         return displayedTemp;
    }

    displayCurrentWeather();
  

   //Header weather status
   console.log(weatherCodeObject)
   
   const weathercodeDisplay = async () => {
    const { weatherCode } = await getWeather();
    const weatherStatusCode = weatherCodeObject.find(x => x.code === weatherCode)
    const display = weatherStatus.append(weatherStatusCode.label);
    return display;
   };
   
   weathercodeDisplay();

//header min-max temp of the day display
const displayTempParameters = async () => {
    const { dailyMaxTemp, dailyMinTemp } = await getWeather()
    tempParameters.append(`L: ${Math.round(dailyMinTemp)}°F H: ${Math.round(dailyMaxTemp)}°F`)
}

displayTempParameters();

getWeather function: 

export async function getWeather() {
    try {
      const success = await new Promise((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject);
      });

      const coordinates = success.coords;
      const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
      localStorage.setItem('latitude',`${coordinates.latitude}` );
      localStorage.setItem('longitude', `${coordinates.longitude}`);
  
      const res = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${coordinates.latitude}&longitude=${coordinates.longitude}&hourly=temperature_2m,apparent_temperature,precipitation_probability,weathercode,windspeed_10m&daily=weathercode,temperature_2m_max,temperature_2m_min&current_weather=true&temperature_unit=fahrenheit&windspeed_unit=mph&timeformat=unixtime&timezone=${timezone}`);
      const data = await res.json();

      console.log("variable", data.current_weather.weathercode)
      const weatherData = {
      
        currentWeather: data.current_weather,
        dailyMaxTemp: Math.max(parseFloat(data.daily.temperature_2m_max)),
        dailyMinTemp: Math.max(parseFloat(data.daily.temperature_2m_min)),
        tempUnit: data.daily_unit,
        hourlyUnits: data.hourly_units,
        weatherCode: data.current_weather.weathercode

      }

      return weatherData;
    } catch (error) {
      return {
        currentWeather: {
          temperature: null,
          weatherDescription: null,
        },
        dailyMaxTemp: null,
        dailyMinTemp: null,
        weatherCode: null,
      };
    }
  }

weatherCodeObject:

export const weatherCodeObject = [
    {
        code: 0, 
        label: 'Clear Sky'
    },
    {
        code: 1,
        label: 'Mainly clear'
    },
    {
        code: 2, 
        label: 'Partly cloudy'
    },
     {
        code: 3,
        label: 'Overcast'
    },
    {
        code: 45,
        label: 'Fog'
    },
    {
        code: 48,
        label: 'Depositing rime fog'
    },
    {
        code: 51,
        label: 'Light drizzle'
    },
    {
        code: 53,
        label: 'Moderate drizzle'
    },
    {
        code: 55,
        label: 'Dense drizzle'
    },
    {
        code: 61,
        label: 'Slight rain'
    },
    {
        code: 63,
        label: 'Moderate rain'
    },
    {
        code: 65,
        label: 'Heavy rain'
    },
    {
        code: 66,
        label: 'Light freezing Rain'
    },
    {
        code: 67,
        label: 'Heavy Freezing Rain'
    },
    {
        code: 71,
        label: 'Slight snow fall'
    },
    {
        code: 73,
        label: 'Moderate snow fall'
    },
    {
        code: 75,
        label: 'Heavy snow fall'
    },
    {
        code: 77,
        label: 'Snow grains'
    },
    {
        code: 80,
        label: 'Slight rain shower'
    },
    {
        code: 81,
        label: 'Moderate rain shower'
    },
    {
        code: 82,
        label: 'Violent rain shower'
    },
    {
        code: 85,
        label: 'Slight snow showers'
    },
    {
        code: 86, 
        label: 'Heavy snow showers'
    },
    {
        code: 95,
        label: 'Thunderstorm'
    }

];

I’m working with modules for the first time, so sorry if my code is not separated correctly for the post.

I’ve tried to reload the page with javascript, but it still doesn’t work for me.

Schema is not defined (Mongoose)

I am getting Schema not defined for Schema.Types options

const mongoose = require('mongoose');

const mineralSchema = mongoose.Schema({
    larry: Schema.Types.Mixed,
    specimen: {
        type:        {type: String, lowercase: true},                // thumbnail, miniature, display
        matrix:      {type: String, lowercase: true},              
        color:       {type: String, lowercase: true},
        location:    {type: String, lowercase: true},
        mine:        {type: String, lowercase: true},
        pocket:      {type: String, lowercase: true},              
        size:        Schema.Types.Mixed, 
        weight:      Number,
        comments:    Schema.Types.Mixed,
        description: Schema.Types.Mixed,
        purch_date:  {type: Date, default: Date.now },
        purch_price: Number,
        supplier:    Schema.Types.Mixed,
        images:      String
    }
});

I thought maybe this was a scope issue due to nested objects, but even larry is having issues.
Can I have some help please?

Node.js v19.7.0
[nodemon] app crashed - waiting for file changes before starting...
[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
C:Usersxxx.xxx.xxxapp.js:14
    larry: Schema.Types.Mixed,
           ^

ReferenceError: Schema is not defined
    at Object.<anonymous> (C:UsersxxxDesktopxxxxxxapp.js:14:12)
    at Module._compile (node:internal/modules/cjs/loader:1275:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1329:10)
    at Module.load (node:internal/modules/cjs/loader:1133:32)
    at Module._load (node:internal/modules/cjs/loader:972:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
    at node:internal/main/run_main_module:23:47

Node.js v19.7.0
[nodemon] app crashed - waiting for file changes before starting...

How to replace src image and use transition with Javascript

I’m trying to learn Javascript by example. I have been working with a script example that creates a 3×3 slide puzzle if found online. I’ve been able to add a few features and bells and whistles, but I am stuck on what I thought would be easy. Once the user has solved the puzzle my script calls the function solvedIt() which displays the complete puzzle. What I want to do is replace the middle row of 3 tiles with 3 different images and have a smooth transition. I am able to simply replace the src, but even after reading very many other posts about transitioning images, I’m still stuck. It seems there may be 2 ways to solve my problem. One would be to somehow use and change the css class of each of the tiles. The other would be to somehow place the second images over the first ones by using their id and then call a css function to animate the change. I’d like to solve this without any libraries. Here are excerpts from the code I have:

        html
        <body>
         <div>id="board"></div>
    </body>

        css
    body {
        font-family: Arial, Helvetica, sans-serif;
        text-align: center;
        color: #0c67ae;
    }
    #board {
        width: 360px;
        height: 360px;
        background-color: lightblue;
        border: 10px solid #0c67ae;
    
        margin: 0 auto;
        display: flex;
        flex-wrap: wrap;
    }
    
    #board img {
        width: 118px;
        height: 118px;
        border: 1px solid #0c67ae;
    }

var rows = 3;
var columns = 3;

var currTile;
var otherTile; //blank tile
// var imgOrder = ["1", "2", "3", "4", "5", "6", "7", "8", "9"];
var imgOrder = ["4", "1", "3", "7", "2", "5", "8", "6", "9"];

window.onload = function() {
  for (let r=0; r < rows; r++) {
    for (let c=0; c < columns; c++) {
      //<img id="0-0" src="1.jpg">
      let tile = document.createElement("img");
      tile.id = r.toString() + "-" + c.toString();
      tile.src = "./" + src_dir + "/" + imgOrder.shift() + ".jpg";
      //DRAG FUNCTIONALITY
      tile.addEventListener("dragstart", dragStart);  //click an image to drag
      tile.addEventListener("dragover", dragOver);    //moving image around while clicked
      tile.addEventListener("dragenter", dragEnter);  //dragging image onto another one
      tile.addEventListener("dragleave", dragLeave);  //dragged image leaving anohter image
      tile.addEventListener("drop", dragDrop);        //drag an image over another image, drop the image
      tile.addEventListener("dragend", dragEnd);      //after drag drop, swap the two tiles           
      // added mouse click handlers
      tile.addEventListener("click", mouseClick);      //            
      document.getElementById("board").append(tile);
    }
  }  
} // end window.onload

function solvedIt() {  
  // replace 4.jpg, 5.jpg and 6.jpg with code1.jpg, code2.jpg and code3.jpg
  // 4.jpg has id of '1-0', 5.jpg id='1-1' and 6.jpg='1-2'
  let xTile = document.getElementById('1-0');
  xTile.src="./"+src_dir+"/code1.jpg" ;
  let xTile = document.getElementById('1-1');
  xTile.src="./"+src_dir+"/code2.jpg" ;
  let xTile = document.getElementById('1-2');
  xTile.sr
}

In Vue.js 3 Composition API with WebSockets. Where should I create the instance of Laravel Echo and Pusher?

I am using WebSockets in the backend and I need to know where I should instantiate the Laravel Echo and Pusher libraries applying good practices. Should I instantiate them in the main.js file or should I create another file in a specific directory and import it? (My intention is to apply best practices, I then want to make a progress bar for uploading files.).

I understand that this is the way:

`
import Echo from ‘laravel-echo’;
import Pusher from ‘pusher-js’;

window.Echo = new Echo({
broadcaster: ‘pusher’,
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
encrypted: true,
authEndpoint: ‘/broadcasting/auth’,
auth: {
headers: {
‘X-CSRF-TOKEN’: $(‘meta[name=”csrf-token”]’).attr(‘content’)
}
}
});
`

Finding an AWS JavaScript Lambda module regardless of whether the lambda is hot or cold

AWS Lambda here (Node 16.x/JavaScript). I have the following project directory structure:

my-lambda/
  src/
    common/
      simple.js
    lambda/
      index.js <-- entry point for lambda

Where common.simple.js is:

module.exports.soSimple = function() {

  console.log("doing some simple stuff...");

};

And where lambda/index.js is:

exports.checkHealth = async (event) => {

    soSimple = require('../common').soSimple;

    let response = {};

    try {

        soSimple();

        response = {
            statusCode: 200,
            body: JSON.stringify(items)
        };

    } catch (e) {
        response = {
            statusCode: 400,
            body: "Unable to do even the simplest of things"
        };
    }

    console.info(`response from: ${event.path} statusCode: ${response.statusCode} body: ${response.body}`);
    return response;

}

When I deploy this Lambda and hit the API Gateway sitting in front of it, I get back a 502 from the gateway. When I look at the Lambda logs, I see:

{
    "errorType": "Error",
    "errorMessage": "Cannot find module '../common'nRequire stack:n- /var/task/src/lambda/index.jsn- /var/runtime/index.mjs",
    "code": "MODULE_NOT_FOUND",
    "requireStack": [
        "/var/task/src/lambda/index.js",
        "/var/runtime/index.mjs"
    ],
    "stack": [
        "Error: Cannot find module '../common'",
        "Require stack:",
        "- /var/task/src/lambda/index.js",
        "- /var/runtime/index.mjs",
        "    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:995:15)",
        "    at Function.Module._load (node:internal/modules/cjs/loader:841:27)",
        "    at Module.require (node:internal/modules/cjs/loader:1067:19)",
        "    at require (node:internal/modules/cjs/helpers:103:18)",
        "    at Runtime.exports.checkHealth [as handler] (/var/task/src/lambda/index.js:3:25)",
        "    at Runtime.handleOnceNonStreaming (file:///var/runtime/index.mjs:1085:29)"
    ]
}

What do I need to do in the code (without changing the file/folder structure) so that common/simple.js#soSimple can be used inside my Lambda event handler when the Lambda is running both warm and cold?

How do I build a gui for our terraform solution?

We recently did a project with terraform to deploy virtual machines on a on-premises vcenter. Now we want to build a nice gui for this. Imagine a IT teacher needs to prepare a class and needs 10 windows servers. We know how to do this with terraform, we know how to build a desktop application (html, css and JavaScript using electron) but how do we connect the two? We are looking for some advise from experienced programmers as we aren’t. Any tips are appreciated!

We tried to write .tf files with JavaScript using the node library “GenesisDevice”, but I don’t think this is best practice

onSelect prop on channellist of getstream.io not doing anything

The onselect prop on the channelListScreen component isnt doing anything.I tried to console log to get some type of response. i tried looking through the docs and it says just this should be enough, i was following a tutorial from getstream.io to begin with and I cant find what i did different thats making it not work.

import { StatusBar } from "expo-status-bar";
import { StyleSheet, Text, View, Button, SafeAreaView } from "react-native";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import { useChatClient } from "./useChatClient";
import { AppProvider } from "./AppContext";
import { OverlayProvider, Chat, ChannelList, Channel, MessageList, MessageInput, List } from "stream-chat-expo";
import { StreamChat } from "stream-chat";
import { chatApiKey, chatUserId } from "./chatConfig";
import { useAppContext } from "./AppContext";
import { GestureHandlerRootView } from "react-native-gesture-handler";

const Stack = createNativeStackNavigator();

const chatClient = StreamChat.getInstance(chatApiKey);

const filters = { members: { $in: [chatUserId] } };

const ChannelScreen = (props) => {
  const { channel } = useAppContext();
  return (
    <Channel channel={channel}>
      <MessageList />
      <MessageInput />
    </Channel>
  );
};
const sort = {
  last_message_at: -1,
};

// const Home = (props) => {
//   const { navigation } = props;
//   return (
//     <Text>
//       Home
//       <Button title="Go to Home" onPress={() => navigation.navigate("ChannelListScreen")} />{" "}
//     </Text>
//   );
// };

const test = () => {
  console.log(`selected`);
};
const ChannelListScreen = (props) => {
  const { setChannel } = useAppContext();
  return (
    <ChannelList
      onSelect={(channel) => {
        const { navigation } = props;
        setChannel(channel);
        navigation.navigate("ChannelScreen");
        console.log(channel);
      }}
      filters={filters}
      sort={sort}
    />
  );
};

const NavigationStack = (props) => {
  const { clientIsReady } = useChatClient();

  if (!clientIsReady) {
    return <Text>Loading chat...</Text>;
  }

  return (
    <OverlayProvider>
      <Chat client={chatClient}>
        <Stack.Navigator>
          {/* <Stack.Screen name="Home" component={Home} /> */}
          <Stack.Screen name="ChannelListScreen" component={ChannelListScreen} />
          <Stack.Screen name="ChannelScreen" component={ChannelScreen} />
        </Stack.Navigator>
      </Chat>
    </OverlayProvider>
  );
};

export default function App() {
  return (
    <AppProvider>
      <GestureHandlerRootView style={{ flex: 1 }}>
        <SafeAreaView style={{ flex: 1 }}>
          <NavigationContainer>
            <NavigationStack />
          </NavigationContainer>
        </SafeAreaView>
      </GestureHandlerRootView>
    </AppProvider>
  );
}

I need it to navigate to the specific channel list thats been clicked on. this is my first time posting here, so if the code isnt enough please do ask for more because im not sure exactly what i need to share. Thank you in advance:).

Images no rendering on mobile

I have recently completed my portfolio (jay-lee-portfolio.netlify.app) but some pics don’t show on my phone (Google Pixel 6) however, they show with no issues on my laptop.
There are no errors in the browser, so I’m unsure why.
My code is public on my GitHub (https://github.com/7Jay-Lee7/Portfolio) as not sure what part of the code I should put here. Any help would be much appreciated.

Have tried on multiple devices and only failed on my mobile. Loads then disappears to just whiteness.

Add grid layout to HTML element using JavaScript

How could I add a grid layout to HTML using JavaScript
I have this code:

const formatItem = item => `<div class="card" ${item.category}">
<div class="image-container"><img src="${item.image}" />
  <div class="container">
    <h5 class="product-name">${item.productName.toUpperCase()}</h5>
    <h6>£${item.price}</h6>
  </div>
</div>`;

productContainer.innerHTML = paginator(products, currentPage, perPage)
  .data.map(item => formatItem(item)).join("");
`

I have then appended this code to the HTML document. Although the div class displays correctly, the div id does not display in a grid layout. Why is this and how could I fix it?

CSS code:

#products {
    display: grid;
    grid-template-columns: repeat( auto-fit, minmax(250px, 1fr) );
    column-gap: 1.5em;
    padding: 2em 50px;
}

Calculate point B coordinates knowing angle and distance from point A

Can someone help me with a math thing. I’m trying to calculate the travel distance from point A to point b.
this is what i have so far: https://editor.p5js.org/Marcel0024/sketches/Np03rgmxO
I can’t get the **angle ** to work, in this case i want the circle to be drawn the direction of the mouse click.

Calculate angle formula i got here: https://maththebeautiful.com/angle-between-points/

New point formula i got here: Angle between two Vectors 2D

But i can’t get them to work together.

So i have

function mouseClicked(){
  var angle = Math.atan2(mouseY - point1.y, mouseX - point1.x)

  const x = point1.x + Math.sin(angle) * travelDistance;
  const y = point1.y - Math.cos(angle) * travelDistance;
  
  circle(x, y, 10)
}

But the angle is way off

How do I prevent my Prisma mock from creating entries in the database

I am trying to unit test my database based on the Prisma unit testing documentation. When I run my tests though, calls are actually going out to the database. I was under the impression mocking the Prisma client would prevent that.

I wrote code to initialize the Prisma client.

import { PrismaClient } from "@prisma/client"

let prisma

if(process.env.NODE_ENV === 'production') {
    prisma = new PrismaClient()
} else {
    if(!global.prisma) {
        global.prisma = new PrismaClient()
    }
    prisma = global.prisma
}

export default prisma

I wrote code to create an entry in the database.

export async function createTest(id) {
    const result = await await prisma.test.create({
        data: {
            id: id,
        },
    })

    return result
}

And I wrote code to test the create function.

import { createTest } from '../lib/crud'
import { prismaMock } from '../lib/mock/singleton'

it('confirms an entry can be created in the database', async () => {
    const id = 1

    prismaMock.test.create.mockResolvedValue(id)

    await expect(createTest(id)).resolves.toEqual({
        id: 1,
    })
})

Am I missing something? Why is the create function actually creating entries in the database when the tests run?

Is there any way to fix this code?(POST Logger w/ formData)

My problem is that my POST logger is not logging the requests from my javascript. Here is the code for each:

  1. Client Side

     // JavaScript code to handle form submission
     const form = $("#register-form");
    
     form.submit(function(event) {
        event.preventDefault(); // prevent the form from submitting normally
    
     const formData = form.serialize(); // serialize the form data
    
     $.ajax({
         url: "http://localhost:3000",
         method: "POST",
        data: formData,
        success: function(response) {
        // the response was successful
        console.log("Login successful!");
     },
     error: function(xhr, status, error) {
       // an error occurred while sending the request
       console.error(error);
     }
     });
     });
    

2.Server Side

const express = require('express');
const bodyParser = require('body-parser');

const app = express();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

// handle POST request
app.post('/', (req, res) => {
console.log(req.body);
res.send('Received POST request');
});

app.listen(3000, () => {
   console.log('Server listening on port 3000');
});

I had checked the server with curl, and I think that’s a client side issue. Cheers!