How to write data to a two-dimensional array of objects?

The question is that I receive data via a websocket and I need to write it to a two-dimensional array. How to do it?

myWs.onmessage = function (message) {
    const jsonParse = JSON.parse(message.data);    
    try {  
        
        for (let i = 0; i < mockLineData.length; i++) {         
          mockLineData[i].data[i].y = jsonParse[i]['value_state'];
          mockLineData[i].data[i].x = inc;
          console.log(mockLineData[i].data[i].y);               
        }     
    } catch (error) {
        console.log('Error: ', error);
    }
};


export const mockLineData = [
  {
    id: "ИБП Uвх",
    color: tokens("dark").redAccent[200],
    data: [
      {
        x: 0, 
        y: 1,
      },
      
    ],
  },
];

Trouble Implementing Google OAuth in React Native Expo App with Separate Backend

I am relatively new to mobile app development and currently learning React Native with Expo. I have previous experience with ReactJS, where I successfully implemented Google OAuth using Passport for authentication in the backend.

Now, I am attempting to integrate Google OAuth into my React Native Expo app, and I’m facing challenges in understanding the workflow. Specifically, I am uncertain about whether I need to run the frontend and backend separately when building an Expo React Native app.

Here’s a snippet of the code where I am trying to perform authentication:

backend
index.js

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require("passport");
const authRoutes = require('./routes/authRoutes');
const setupSwagger = require('./swagger');
const cookieSession = require("cookie-session");


const app = express();

app.use(
    cookieSession({
        name: "session",
        keys: ["cyberwolve"],
        maxAge: 24 * 60 * 60 * 100,
    })
);
app.use(passport.initialize());
app.use(passport.session());

// Integrate Swagger configuration
setupSwagger(app);

app.use(bodyParser.json());
app.use(
    cors({
        origin: "http://localhost:8081",
        methods: "GET,POST,PUT,DELETE",
        credentials: true,
    })
);

// Use authentication routes
app.use('/auth', authRoutes);


const PORT = process.env.PORT || 8080;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

authRoutes.js

const express = require('express');
const router = express.Router();
const passport = require("passport");

router.get("/google", passport.authenticate("google", { scope: ["profile", "email"] }));
router.get(
 "/google/callback",
 passport.authenticate("google", {
   successRedirect: process.env.CLIENT_URL,
   failureRedirect: "/auth/login/failed",
 })
);

module.exports = router;

passport.js

require('dotenv').config()
const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;


passport.use(
  new GoogleStrategy(
    {
      clientID: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      callbackURL: "/auth/google/callback",
      scope: ["profile", "email"],
    },
    function (accessToken, refreshToken, profile, callback) {
      return callback(null, profile);
    }
  )
);

passport.serializeUser((user, done) => {
  done(null, user);
});

passport.deserializeUser((user, done) => {
  done(null, user);
});

Frontend:

api.js

import axios from 'axios';
import { API_BASE_URL } from '../../.env';

const signInWithGoogle = async () => {
  try {
    const response = await axios.get(`${API_BASE_URL}/auth/google`);
    console.log(response.data);
    return response.data;
  } catch (error) {
    console.error('Error signing in with Google:', error);
    return null;
  }
};

export { signInWithGoogle };

.env.js

export const API_BASE_URL = "http://localhost:8080";

welcomescreen.jsx

import React from "react";
import { View, Text, TouchableOpacity, StyleSheet, Image } from "react-native";
import { useNavigation } from "@react-navigation/native";
import { AntDesign } from "@expo/vector-icons";
import { primaryColor, secondaryColor } from "../../utils/constants/color";
import { signInWithGoogle } from "../../services/api";

export const WelcomeScreen = () => {
  const navigation = useNavigation();

  const handleSignInWithGoogle = async () => {
    const user = await signInWithGoogle();
    if (user) {
      console.log("User signed in:", user);
      navigation.navigate("Balance");
    } else {
      console.log("Sign-in failed");
    }
  };

 

  return (
    <View style={styles.container}>
     
      <View style={styles.buttonContainer}>
        <TouchableOpacity
          style={styles.googleButton}
          onPress={handleSignInWithGoogle}
        >
          <AntDesign name="google" size={24} color="white" />
          <Text style={styles.buttonText}>Sign In with Google</Text>
        </TouchableOpacity>
       
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center",
  },
  logo: {
    width: 100,
    height: 100,
    borderRadius: 20,
    marginBottom: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: "bold",
    color: primaryColor,
    marginBottom: 20,
  },
  buttonContainer: {
    width: "80%",
    marginTop: 20,
  },
  googleButton: {
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: secondaryColor,
    padding: 10,
    borderRadius: 5,
    marginBottom: 10,
  },
  buttonText: {
    marginLeft: 10,
    color: "white",
    fontWeight: "bold",
  },
});

The issue I’m encountering is “I’m getting a network error when attempting to connect to the backend server”. I’ve checked changing the local host to ipaddress and .env file to .env.js , but the problem persists.

I would appreciate any guidance on the correct flow for implementing Google OAuth in a React Native Expo app with a separate backend. Additionally, if there are specific considerations or configurations needed for Expo apps, please provide insights.

Thank you for your assistance!

Mouseover event not trigerring for google maps markers

I am using Google Maps API to display some markers for my website. Now I want to display some description of the marker when someone hovers over it. I tried adding a 'mouseover‘ event to the marker according to the docs, but it seems it is not working. If I change the event to something like 'click' then it detects it.

Below is the code for it.

async function initMap() {
    // Request needed libraries.
    const { Map } = await google.maps.importLibrary("maps");
    const { AdvancedMarkerElement } = await google.maps.importLibrary("marker");
    const map = new Map(document.getElementById("map"), {
        center: { lat: 37.4239163, lng: -122.0947209 },
        zoom: 11,
        mapId: "4504f8b37365c3d0",
    });

    for (const property of properties) {
        const markerViewWithText = new AdvancedMarkerElement({
            map,
            position: property.position,
            title: property.title,
        });

        const details = document.createElement("div");
        details.innerHTML = property.details;
        const infowindow = new google.maps.InfoWindow({
                content: details,
        })

        markerViewWithText.addListener("mouseover", () => {
            console.log("Mouse over");
            infowindow.open({
                anchor: markerViewWithText,
            })
        })
    } 
}

const properties = [
    {
        title: "Title 1",
        position: { lat: 37.419, lng: -122.09 },
        href: "https://www.google.com",
        details: "Details of the marker 1",
    },
    {
        title: "Title 2",
        position: { lat: 37.319, lng: -122.09 },
        href: "https://www.youtube.com",
        details: "Details of the marker 2",
    },
]
initMap();

Any help is much appreciated.

Getting the file data of a PDF contained in an Embed tag

I’m working on a small electron app to manage editable character sheet pdfs. I’m currently trying to implement saving the pdf via hotkey, as well as autosaving.

I’m displaying said sheets using an html <embed> tag like so:

<embed src="../sheets/page.pdf">

To save the file, given these PDFs have editable fields, I need to pull the file data from the embed in its current state. Is getting this data possible, and if so, how would I go about doing it?

Thank you.

cropping javascript library

i am searching for a cropping js library that i can integrate it in to a nuxt 3 web app. the issue is user takes picture from his/her passport and if passport is far away from camera, picture should be cropped from angles. and if user holds passport with some angle around x axis or y axis it should remove angles.

i found vue-advanced-cropper it should do the work but it doesn’t seem to fix angles around x axis. any help with finding the library with fixing this issue would be appreciated. thank you in advance

Socket IO, JS – handle retrieving previous messages

I’m building a chat application using Socket IO and React. Currently, whenever a user selects a conversation, all the previous messages for that chat are fetched and displayed. The problem with this solution is that users have to wait each time they select a chat for the previous messages to be loaded.

One solution would be to initially load x amount of previous messages for all chats, so users only have to wait once. However, if messages are added to a chat later, then the user wouldn’t see them when selecting a chat, as those messages wouldn’t have been fetched initially.

A fix to this could be to initially load x amount of previous messages for all chats, however on the server, emit a socket event everytime a new message is added to one of the user’s chats in the database, and then on the client, retrieve this new message and add it to the previous messages state for the relevant chat in the frontend. This way, after selecting a chat, the latest previous messages are up-to-date as possible. Are there any problems with this solution?

If so, are there any better alternative solutions to retrieving previous messages for chats as well as handling adding new messages to chats when they are sent in via socket io?

One potential issue is that a socket event would be emitted everytime a new message is added to a conversation, which may negatively affect performance.

EJ Syncfusion React Scheduler Not Working

So i have this ej2 syncfusion calendar for appointments and i have copied the codes from this link https://ej2.syncfusion.com/react/demos/#/material3/schedule/block-events and tried to run the code from my ReactJs.

This is my JS and CSS code https://pastecode.io/s/jsa8hxon.

Please i reuqest for assistance as to why my code is running but the css is not properly loading for me as this is the output i want to get
Expectation but my program is giving me this output where everything is all over the place. My Website My Website

I think something is wrong with my style

I would really appreciate the assistance and if anything unclear please do clarify with this.

Fetch. fulfillRequest return binary data

I’m trying to use CDP to intercept the request and return bytes so that the user can download it directly, but it seems that the body of Fetch.fulfillRequest only supports base64 encoding and does not support binary data return.

It is expected that the request can be intercepted so that the request can directly download the specified content.

Why don’t my shot move directly towards where i’m shooting?

When I click it finds the amount pixels to move left and top. Though there seems to be some predetermined location they are traveling to.

function getCenter(element) {
const {left, top, width, height} = element.getBoundingClientRect();
return {x: left + width / 2, y: top + height / 2}
}

    const arrow = document.getElementById("arrow");
    const arrowCenter = getCenter(arrow);
    container.style.top = container.offsetTop + arrowCenter.y-6 + "px"
    container.style.left = container.offsetLeft + arrowCenter.x-6 + "px"
    
    window.addEventListener("mousemove", getAngleOfArrow)
    
    function getAngleOfArrow(e) {
      const rads = Math.atan2(e.clientY - arrowCenter.y, e.clientX - arrowCenter.x);
      let angle = rads*180/Math.PI
      let angleInt = parseFloat(angle)
        arrow.style.transform = "rotate("+angleInt+"deg)";
    }
    
    window.addEventListener("click", function(e){
      let shot
      shot = createShot()
      moveShot(shot, e)
    })
    
    function getRad(e){
      const rads = Math.atan2(e.clientY - arrowCenter.y, e.clientX - arrowCenter.x);
      console.log(rads)
      return rads
    }
    
    function createShot(){
      let div = document.createElement("div")
      div.setAttribute("class", "bullet")
      container.appendChild(div)
      div.style.top = div.offsetTop + -3 + "px"
      div.style.left = div.offsetLeft + -3 + "px"
      let bullet = document.getElementsByClassName("bullet");
      return div;
    }
    
    function moveShot(circle, e){
        let rad = getRad(e);
        let xshot = 7 * Math.cos(rad);
        let yshot = 7 * Math.sin(rad);
        const myInterval = setInterval(function () {
          circle.style.left = circle.offsetLeft + xshot + "px";
          circle.style.top = circle.offsetTop + yshot + "px";
          if(isInViewport(circle) == false){
            clearInterval(myInterval);
          }
        }, 16);
     }
    
    function isInViewport(element) {
        const rect = element.getBoundingClientRect();
        return (
            rect.top >= 0 &&
            rect.left >= 0 &&
            rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
            rect.right <= (window.innerWidth || document.documentElement.clientWidth)
        );
    }  

https://jsfiddle.net/7b486dvc/

I have tried to find if there some rounding going on using console commands but still have no answer.

I want to open datepicker but it need not opening. Thanks in advance

jQuery("#ttbl_lead_mst_ds_list").jqGrid("navButtonAdd","#tbl_lead_mst_pager",{caption:"Follow Up",
onClickButton:function(){
$("#tbl_lead_mstdialog-confirmFollowup").html("jQuery(".date").datepicker({dateFormat:"dd.mm.yy",changeMonth: true,changeYear: true});");
$("#tbl_lead_mstdialog-confirmFollowup").html('Next Follow Up Date : <input placeholder="Next Follow Up Date" title="Please Enter Next Follow Up Date Here" type="text" name="next_follow_up_date" id="ttbl_admin_lead_mst_ds_form_next_follow_up_date" class="date form-control"/>
}
});

The datepicker is not OPENING please help me

Scraping all Pages on Site Containing _dopostback Method href

New to scrapy… am scraping www.brickeconomy.com/sets/2000 and trying to move to the next page. To navigate over the pages, there are several links at the bottom [prev][1]…[7][next]. Links use _dopostback method.

next_page = response.xpath('//*[@id="ContentPlaceHolder1_ctlSets_UpdatePanelMain"]/div[3]/ul/li[9]/a/@href').get() if next_page is not None: yield response.follow(next_page, callback=self.parse)

The href calls doPostBack:

`response.xpath(“//*[@id=’ContentPlaceHolder1_ctlSets_UpdatePanelMain’]/div[3]/ul/li[last()]/a/@href”).get()

href = “javascript:__doPostBack(‘ctl00$ContentPlaceHolder1$ctlSets$GridViewSets’,’Page$2′)”`

Solutions I’ve read outline use of the parameters post call, I am not able to make sense of the parameters provided in post and have no idea how to begin replicating the parameters in the spider.

I’ve found the POST call parameters using Firefox, but lack the developer experience to find a solution.

About learn, teach, copy some code for solving solution [closed]

“I have read the terms and conditions of almost all learning websites.
I am totally confused because, after reading their terms, it seems they state that, copying any content from their website is not allowed.

I need to know that if there is any problem to learn , teach , or copying code for solving solutions from any e-learning website, for example, W3Schools, Stack Overflow, MDN. For my job purpose

Learning, teaching , copying code for solving from these resources is permissible

Should I need to give attribution, also how to give attribution on my project

JSON Array not working for put method under new library

`import com.liferay.portal.kernel.json.JSONArray;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
public static String Flow (String InputList, String Url, String Id)
{
String returnValue = StringPool.BLANK;
try
{
JSONObject jsonobject = JSONFactoryUtil.createJSONObject();
if (Validator.isNotNull(InputList))
InputList = InputList.replace (“:”);
InputList = JsonSanitizer.sanitize (InputList);
JSONArray Arr = JSONFactoryUtil.createJSONArray(InputList);
JSONObject Brr = (JSONObject)Arr.get(0);
String Crr = Brr.getString (“result”).toString();
Brr.put(“New Result”, Crr);
Arr.put(0, Brr);
jsonobject.put(“Id”, Id);
}
catch(Exception e)
{
_log.error(className + e);
}
return returnValue;
}

`