Reading the content of a file with JavaScript from the server and returning it to the application

I have a JavaScript function that reads a file from the server. I wanted it to return the result to me, but it doesn’t work. The codes are as follows. The alert does not work. what is the reason ? And how can I fix it?

function red(filename) {
    let xhttp = new XMLHttpRequest();
    xhttp.onload = function() {
    return this.responseText;
    }
    xhttp.open("POST",filename, true);
    xhttp.send();
    }
    
    alert( red("file.txt"));

Insert MySQL Data into Javascript Array not working

Im a beginner in javascript, I try to insert mysql-data which is requested in a while loop
to an javascript array. I tried a lot of codes from the forum here, but nothing works.

The alert i use to check what kind of data is in the array for debugging.

If I set the alert above the push-command, I get a empty array as i should.
But if I move the alert command under the first push command, nothing happens. No alert show up and (i think) no data was added to the array. Can someone tell me why?

Heres my (shortened) code:

echo "<script>
                                            var name = []; 
                                            var ip = []; 
                                            var id = []; 
                                        </script>";
                                while ($zeile = $erg->fetch_object()) {
                                    
                                    $
                                    echo "<script>";
                                    echo "name.push('".$json_array."');";
                                    echo "alert(name);";
                                    /*echo "ip.push('".$zeile->ip."');";
                                    echo "id.push('".$i."');";*/
                                    echo "</script>";   }

Hope someone can help me.

Greetings Tom

Can’t set breakpoints in my angular app after moving to Angular 7

After upgrading Visual Studio Code (to ver 1.85.1) I was getting warning in the Debug Console WARNING: Processing source-maps of 'xxx' took longer than 'yyy' ms and the app was very slow, however I could set the breakpoints in my app.
I have found the solution on internet to set the resolveSourceMapLocations variable in launch.json. So my launch.json looks like this:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
   
    "configurations": [

        {
            "type": "chrome",
            "request": "launch",
            "name": "Launch Chrome against localhost",
            "url": "http://localhost:4200",
            "webRoot": "${workspaceFolder}",
            "sourceMaps": true,
            "resolveSourceMapLocations": [
                "${workspaceFolder}/**",
                "${workspaceFolder}/dist/**/*.js",
                "**/node_modules/**"
            ],
        }
    ]
}

The warning has disappeared, my angular app is responsive again, but now I can’t set the breakpoints.
The “sourceMap”: true in my tsconfig.json to generate sourcemaps.
Can somebody please help me to set my launch.json so I can set breakpoint in my angular map.

How to sync React with pure JS class service

I’d like to use refs to class services inside React and the problem is sync between React and Service values updates.

My approach is to use “update” function after every data update in Service, which trigger re-render of React components where created context is used. In general it works and should work even in memo components but I wonder if I missed something.

Expected result is to use this approach without issues related to components re-rendering and live data updates across application. Do you think I can go this way? What kind of issues I can expect? What is other option to sync React with class services refs?

enter image description here

How can I implement auto-scroll into a chat app?

I’m making a chat app as a foundation for a sort of forum website, and I want it to automatically scroll to the bottom of the div once a message is sent (and if the user is close to the bottom of it.)

HTML:

<!DOCTYPE html>
<html>
<head>
    <title>Chat App</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <div id="chat-container">
        <ul id="messages"></ul>
        <form id="form">
            <input id="input" autocomplete="off" />
        </form>
    </div>

    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
      $(function() {
          var socket = io();

          function scrollToBottom() {
              var container = $('#chat-container');
              var scrollHeight = container.prop('scrollHeight');
              var scrollTop = container.scrollTop();
              var containerHeight = container.height();
              if (scrollTop + containerHeight >= scrollHeight - 50) { // 50px offset for tolerance
                  container.scrollTop(scrollHeight);
              }
          }

          socket.on('init', function(messages) {
              messages.forEach(function(message) {
                  const listItem = $('<li>');
                  const username = $('<strong>').text(message.message.split(':')[0] + ':');
                  const msgText = $('<span>').text(message.message.split(':').slice(1).join(':'));
                  listItem.append(username).append('<br>').append(msgText);
                  $('#messages').append(listItem);
              });
              scrollToBottom();
          });

          socket.on('chat message', function(message) {
              const listItem = $('<li>');
              const username = $('<strong>').text(message.message.split(':')[0] + ':');
              const msgText = $('<span>').text(message.message.split(':').slice(1).join(':'));
              listItem.append(username).append('<br>').append(msgText);
              $('#messages').append(listItem);
              scrollToBottom();
          });

          $('#form').submit(function(e) {
              e.preventDefault();
              var message = $('#input').val();
              if (message) {
                  socket.emit('chat message', message);
                  $('#input').val('');
              }
          });
      });

    </script>
</body>
</html>

JS:

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const mongoose = require('mongoose');

const app = express();
const server = http.createServer(app);
const io = socketIo(server);

const mongoDB = 'MONGODB SERVER REPLACE THIS';
mongoose.connect(mongoDB)
.then(() => console.log('Connected to MongoDB'))
.catch(err => console.error('Error connecting to MongoDB:', err));
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });

// Define a schema and model for chat messages
const messageSchema = new mongoose.Schema({
  message: String,
  timestamp: { type: Date, default: Date.now }
});
const Message = mongoose.model('Message', messageSchema);

// Serve static files from the "public" directory
app.use(express.static('public'));

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/public/index.html');
});

// Function to generate random usernames
function generateRandomUsername() {
    const adjectives = ["Ancient", "Mysterious", "Silent", "Wandering", "Hidden"];
    const nouns = ["Traveler", "Wanderer", "Explorer", "Sage", "Pilgrim"];
    const adjective = adjectives[Math.floor(Math.random() * adjectives.length)];
    const noun = nouns[Math.floor(Math.random() * nouns.length)];
    const number = Math.floor(Math.random() * 1000);
    return `${adjective}${noun}${number}`;
}

io.on('connection', (socket) => {
    const username = generateRandomUsername();

    // Fetch and emit past messages
    Message.find().sort({ timestamp: 1 }).lean().exec()
    .then(messages => {
      socket.emit('init', messages);
    })
    .catch(err => {
      console.error('Error fetching messages:', err);
    });

    socket.on('chat message', (msg) => {
        const fullMessage = `${username}:${msg}`;
        const newMessage = new Message({ message: fullMessage });
        newMessage.save()
        .then(savedMessage => {
            io.emit('chat message', savedMessage);
        })
        .catch(err => {
            console.error('Error saving message:', err);
        });
    });
});

const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
  console.log(`Server listening on port ${PORT}`);
});

It (obviously) uses MongoDB as a server, I excluded my database here.

I’ve tried this a couple times and even asked GPT-4 about it, but nothing seems to work.

Google translate snippet not working in React app

I’m trying to add a Google Translate solution to my app (the objective is to automatically translate the client-custom content of the app when it loads, based on the device preferred language).

I stumbled upon this snippet, but my IDE flags the window.googleTranslateElementInit and the window.google elements as not found.

This comes from this snippet:
https://stackblitz.com/edit/react-ts-bblv1z?file=index.tsx

Is this script event supported?

useEffect(() => {
  let addScript = document.createElement('script');
  addScript.setAttribute(
      'src',
      'https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit'
  );
  document.body.appendChild(addScript);
  window.googleTranslateElementInit = googleTranslateElementInit;
}, []);

  const googleTranslateElementInit = () => {
     new window.google.translate.TranslateElement(
        {
          pageLanguage: 'ta',
          includedLanguages: 'en,ms,ta,zh-CN,fr', // include this for selected languages
             layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
        },
        'google_translate_element'
     );
  };

// ...

// component return
//...
   <div id="google_translate_element"></div>

windows.open() is null while I call this only on javascript

  function print(data) {
    var printWindow = window.open();
    ...
  }
  
  function printWithAPI() {
    fetch('http://localhost:3000/api2')
          .then(response => {
          })
          .then(data => {
            if (data.printer_name) {
              print(data.data);
    ...
  }
    ...
  
  printWithAPI();

In here, when printer_name is exist print function called. but at that time var printWindow = window.open(); is null. why? How to fix this error?

Is that because of automatically running by javascript without HTML dom? I’m really not sure what’s the problem.

When printer_name exist want to print automatically by javascript!

Develop VsCode Extension i want replace text

I make vscode extension which replace Xpath code like

=//*[@id="id"]=

replace like this

WebDriverWait(driver, timeout=999999).until(EC.presence_of_element_located((By.XPATH,'//*[@id="id"]')))
driver.find_element(By.XPATH,'//*[@id="id"]')

I tried to this way .. but it’s not work

let data = [ 
  "=="
];

let max = data.length;
for (let i = 0; i < max; i++) {
  let regex = new RegExp("=", "g");
  data[i] = data[i].replace(regex, "yyyy");
}

console.log(data);

how can i do?

Keeping an overflowing div centered in parent’s viewport when upscaling/downscaling it

I am building a simple map system with features similar to Google Map’s : click and drag to scroll the map, zoom in/out, recenter.

For this, I use a mapContainer as a viewport for the map (since it only takes a portion of the screen). This mapContainer contains a div named map, which is bigger than the mapContainer, and absolutely positioned (because it’s top and left properties are modified as the user drags and scrolls the map).
The simplified code looks like this :

<div id="mapContainer">
  <div id="map"></div>
</div>
#mapContainer {
  position: relative;
  width: 500px;
  height: 500px;
  overflow: hidden;
}

#map {
  position: absolute;
  width: 800px;
  height: 600px;
}

I am however encountering a problem with the zoom in/out feature. To achieve that, I simply apply a scale transformation on the map div (zoomed out: 0.65, zoomed in: 1). The problem is, I would like to keep the map div centered in the mapContainer viewport when unzooming it.
Because the position of the map div can be changed freely, it will often look like the map zooms out and goes away to the left, or top, or bottom, or right, depending on where it is (its left and top properties) within the mapContainer viewport.

The only possibility I see is to readjust the top and left properties of the map div after it has been downscaled to 0.65, but idk how really.

I’ve been banging my head on this for two days now, and though I’m sure it all comes down to getBoundingClientRect() calculations in the end, I have yet to solve this problem.

I tried using getBoundingClientRect() calculations, without a lot of success.

How do I use browser state change tracking for generated data [duplicate]

Lets say i have simple content editable rectangle on screen.

Here is its data;

{“left”:438,”top”:252,”width”:410,”height”:257}

Even if i put this in in some text box which is normally tracked it doesn’t work.

I’m trying to leaverage the innate browser undo capabilities for a simple visual puzzle containing basic objects like rectangles.

I’m a novice. i tried a few things like inputting it differently through

innerText
innerHTML
Range and DocumentFragment
Dispatching Events

I don’t need code, just a tip for a method/strategy that could use built-in browser undo to move the rectangle to the previous position from where the used moved it to.

Extract array containing words and equations from a string

I’m trying to extract an array containing all the words (spaces and return inline included) and all the equations contained in a string with React.

I’ve tried this approach, but this math equation [ lim_{{n to infty}} frac{n}{n^2+1} = 0. ] is considered as words and not a singular equation.

Here is my code:

const regex = /\(.*?\)|bw+b|s+/g;
 const inputString = `To find the limit of the sequence \( a_n = \frac{n}{n^2+1} \) as \( n \) approaches infinity, we can identify the dominant terms in both the numerator and the denominator. The dominant term in the numerator is \( n \), and the dominant term in the denominator is \( n^2 \), since these terms will grow the fastest as \( n \) becomes very large.
 We can simplify \( \frac{n}{n^2} \) by recognizing it as \( \frac{1}{n} \), using the property \( a^n/b^n = (a/b)^n \):
  
  \( \frac{n}{n^2} = \frac{n^1}{n^2} = \frac{1}{n^{2-1}} = \frac{1}{n} \).
  
  The limit of \( \frac{1}{n} \) as \( n \) approaches infinity is 0, since the denominator becomes larger and larger, making the value of the fraction smaller and smaller.
  
  Therefore, the limit of the sequence \( a_n = \frac{n}{n^2+1} \) as \( n \) approaches infinity is 0:
  
\[ \lim_{{n \to \infty}} \frac{n}{n^2+1} = 0. \]`;

const words = inputString.match(regex);

How do I send i send an gmail api request- i did all the authentication steps but i hit a wall

I am trying to construct a Gmail replica but I’ve hit a roadblock in terms of making requests to Gmail API-

here’s my code:
index.js

const express = require("express");
const cors = require("cors");
const passport = require("passport");
const cookieSession = require("cookie-session");
require("./passport-setup");
const CLIENT_URL = "http://localhost:3000/inbox"
const passportSetup = require("./passport-setup");
const GoogleStrategy = require("./passport-setup").OAuth2Strategy;
var { gmail } = require('@googleapis/gmail');
const path = require('path');

const app = express();
   
app.use(cors({credentials: true, origin: 'http://localhost:3000'}));

app.use(express.urlencoded({ extended: false }));

app.use(express.json());

app.use(
  cookieSession({
    name: "session",
    keys: ["key1", "key2"],
  })
);

app.use(passport.initialize());
app.use(passport.session());

app.get("/", (req, res) => res.send("Hello World"));
app.get("/failed", (req, res) => res.send("Failed!"));

// GET /auth/google
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  The first step in Google authentication will involve
//   redirecting the user to google.com.  After authorization, Google
//   will redirect the user back to this application at /auth/google/callback
app.get("/google", passport.authenticate('google', {
  scope: ['profile',
      'email',
      'https://mail.google.com/'
  ],
  accessType: 'offline',
  prompt: 'consent'
  
  }))
// GET /auth/google/callback
//   Use passport.authenticate() as route middleware to authenticate the
//   request.  If authentication fails, the user will be redirected back to the
//   login page.  Otherwise, the primary route function function will be called,
//   which, in this example, will redirect the user to the home page.
app.get("/google/callback", passport.authenticate("google", {
  successRedirect: CLIENT_URL, 
  failureRedirect: "/failed"
}))

app.get(
  "/google/callback",
  passport.authenticate("google", { failureRedirect: "/failed" }),
);
app.get("/success", (req, res)=>{
  if(req.user) {
      res.status(200).json({
          success: true,
          message: "Login success!",
          user: req.user,
          cookies: req.cookies
  });
};
});


app.get('/inbox', (req, res)=> {
  gmail.users.messages.list({ 
    userId: 'me', 
    auth: oauth2Client,
    id: message.id,
    format: "full",
    pageToken: nextPageToken,
  }, function(err, response) {
      res.send(response);
    });
});

app.get("/logout", (req,res)=>{
  req.logout();
  res.redirect(CLIENT_URL);
})
app.listen(5000, () => console.log(`Server running at port ${5000}!`));

passport-setup.js

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

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

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

// Use the GoogleStrategy within Passport.
//   Strategies in Passport require a `verify` function, which accept
//   credentials (in this case, an accessToken, refreshToken, and Google
//   profile), and invoke a callback with a user object.
passport.use(
  new GoogleStrategy(
    {
      clientID: "insert client-id",
      clientSecret: "insert client secret",
      callbackURL: "http://localhost:5000/google/callback",
    },
    function (accessToken, refreshToken, profile, done) {
      return done(null, profile);
    }
  )
);

As seen in the following code I’m trying to pull out gmail.users.messages.list but have only been responded to with: “TypeError: Cannot read properties of undefined (reading ‘messages’)”.

me trying to request gmail.users.messages.list:

app.get('/inbox', (req, res)=> {
  gmail.users.messages.list({ 
    userId: 'me', 
    auth: oauth2Client,
    id: message.id,
    format: "full",
    pageToken: nextPageToken,
  }, function(err, response) {
      res.send(response);
    });
});

Photoshop: 2024 Want to export selected groups/layers in the layers panel to individual PNGs; But the script only works partially?

The script I tried works, but it’s only partially accurate because it only exports the first two selected layers/groups in the layer panel as individual PNGs.
Also, for the script to work as intended, the visibility of the selected layers needs to be disabled except for the topmost selected layer.
I want all the selected layers to be exported as individual PNGs. Regardless of their visibility in the layers panel.

Simply put I want to take a group merge its contents and export as a PNG with transparency then move on to the next group……

any help would be appreciated!

function main() {
    if (!documents.length) return;
    var doc = activeDocument;
    var oldPath = activeDocument.path;

    for (var a = 0; a < doc.layerSets.length; a++) {
        var layerSetName = doc.layerSets[a].name;
        var targetLayer = getLayerByName(layerSetName);

        if (targetLayer) {
            activeDocument.activeLayer = targetLayer;
            duplicateLayer();
            activeDocument.mergeVisibleLayers();

            // Assuming you want to save each group with its name
            var saveFile = new File(oldPath + "/" + layerSetName + ".png");
            SavePNG(saveFile);
        }
    }
}

function SavePNG(saveFile) {
    var pngOpts = new ExportOptionsSaveForWeb;
    pngOpts.format = SaveDocumentType.PNG;
    pngOpts.PNG8 = false;
    pngOpts.transparency = true;
    pngOpts.interlaced = false;
    pngOpts.quality = 100;
    activeDocument.exportDocument(saveFile, ExportType.SAVEFORWEB, pngOpts);
}

function duplicateLayer() {
    var desc143 = new ActionDescriptor();
    var ref73 = new ActionReference();
    ref73.putClass(charIDToTypeID('Dcmn'));
    desc143.putReference(charIDToTypeID('null'), ref73);
    desc143.putString(charIDToTypeID('Nm  '), activeDocument.activeLayer.name);
    var ref74 = new ActionReference();
    ref74.putEnumerated(charIDToTypeID('Lyr '), charIDToTypeID('Ordn'), charIDToTypeID('Trgt'));
    desc143.putReference(charIDToTypeID('Usng'), ref74);
    executeAction(charIDToTypeID('Mk  '), desc143, DialogModes.NO);
}

function getLayerByName(name) {
    var layers = activeDocument.layers;
    for (var i = 0; i < layers.length; i++) {
        if (layers[i].name === name) {
            return layers[i];
        }
    }
    return null;
}

main();

jquery issue in Rails 6 project

I have facing issues of jquery in my rails 6 project. I’ve attached the picture of my errors enter image description here

Ruby version is 2.7.6 and Rails version is 6.1.3.

In my application.js, I have

//= require active_admin/base
//= require jquery
//= require jquery-ui
//= require turbolinks
//= require jquery.turbolinks
//= require bootstrap-sprockets
//= require filter_bar
//= require filter_box
//= require nested_form_fields
//= require bootstrap-select.min
//= require tinymce
//= require parsley
//= require raphael-2.1.0.min
//= require morris
//= require dashboard-charts
//= require highcharts
//= require highcharts/highcharts-more
//= require bootstrap-datepicker
//= require_self
//= require_tree .

The gem list relevant to this issue I have is

gem 'jquery-rails', '~> 4.5', '>= 4.5.1'
gem 'jquery-ui-rails', '~> 4.2.1'
gem 'jquery-turbolinks', '~> 2.1'
gem 'activeadmin', '~> 2.13', '>= 2.13.1'

what i have tried so far is, I made different combination by moving jquery and relevant things to different position in application.js. I tried the following combination and many more. But end up finding nothing about this issue. I know the issue is happening because of active admin

//= require jquery
//= require jquery-ui
//= require turbolinks
//= require jquery.turbolinks
//= require bootstrap-sprockets
//= require active_admin/base
//= require filter_bar
//= require filter_box
//= require nested_form_fields
//= require bootstrap-select.min
//= require tinymce
//= require parsley
//= require raphael-2.1.0.min
//= require morris
//= require dashboard-charts
//= require highcharts
//= require highcharts/highcharts-more
//= require bootstrap-datepicker
//= require_self
//= require_tree .