JavaScript, different if made with one object mapped

Currently I have this code:

if (downloadReports.current && socialAssistant.socialattentions?.url) {
  window.open(socialAssistant.socialattentions.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsRecords?.url) {
  window.open(socialAssistant.socialattentionsRecords.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsAdvices?.url) {
  window.open(socialAssistant.socialattentionsRecordReviews.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsRecordReviews?.url) {
  window.open(socialAssistant.socialattentionsRecordReviews.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsGroups?.url) {
  window.open(socialAssistant.socialattentionsGroups.url, '_blank');
}
if (downloadReports.current && socialAssistant.socialattentionsGroupattendants?.url) {
  window.open(socialAssistant.socialattentionsGroupattendants.url, '_blank');
}

How can I do a shorten code for that?

socialAssistant is an object that could contain different properties, so depending on those property is the paraemeter to use in window.open method.

I was thinking in something like:

const someVar = ? // how to get which property has?
if (downloadReports.current && someVar) {
  window.open(someVar, '_blank')
} 

Json-server generates new password on any user property change

I am using json-server and json-auth to mock backend of my react app. So i have a situation where i need to give a user status of “inactive”. When i check db.json i can see that whenever a change of isActive property of user happens, encrypted password is being changed. So instead of my user getting error message that he is blocked he gets message that password is not correct. Is this normal behavior of json-server and json-auth and is there any workaround? I hope my question is clear. Thanks in advance.

Get the last day of a month BUT just the number with Vuejs or JS

I am trying to get the last day of a month, it worked but it displays a very long description and I just need the day.

My code is this one:

var today = new Date();
var data = new Date(today.getFullYear(), today.getMonth()+1, 0);

and it returns

Sat Apr 30 2022 00:00:00 GMT-0400

But I just want to get the 30… only that

how can I do it? Thanks

Can I load an external SVG file once, then clone copies multiple time?

I have an application that I have created a template SVG file for, but depending on user interaction, will need to create multiple (say 6 to 20) instances of the image and modify each independently through code. I know how to load the file into an object element, and how to access and modify the elements within the image, but I’m trying to find if it is possible to do this without having to import the SVG source file for each object as it’s created, or can I somehow buffer the source file as an XML structure and then copy that? My target environment is plain HTML and javascript.

For reference, I need to make a navigable display of the nodes and edges of a graph describing the Tower of London cognitive assessment. I want to place an image of the balls and posts arrangement in a circle for each of the nodes and allow the user to traverse the graph. The SVG source file has the balls and posts, to represent a particular node I just change the position of the circle elements that represent the balls to move them to the appropriate post. I could brute force this by loading a new copy of the SVG template for each object representing a node but I’m hoping for a more elegant solution.

How do I get my sidebar navigation to only display when a user is logged in

I am currently using react V6. I have a sidebar nav and a top bar nav. The top bar nav is supposed to display when the user has NOT been authenticated. The sidebar nav is only supposed to display when the user has logged in. But my sidebar nav is showing on for all routes and my top nav isn’t displaying at all.

APP.JS

function App() {

const { user, authIsReady } = useAuthContext()

  const theme = createTheme({
    palette: {
      mode: 'light',
    },
    typography: {
      guideline: {
        color: 'gray',
        display: 'block',
      },
    },
  });

return (
 <ErrorBoudry>
   <div className="App">
    {authIsReady && (
    <BrowserRouter>
        {user && <Sidebar />}
        <div className='container'>
        <NavBar/>
             <Routes>
               <Route path="/" element={<LandingPage />} />
               <Route path="/login" element={<LoginPage />} />
               <Route path="/register" element={<RegisterPage />} />


                <Route path="/dashboard" element={
                <ProtectedRoute>
                <DashboardPage/>
                </ProtectedRoute>
                 }/>
                <Route path="/findMatch" element={
                 <ProtectedRoute>
                <findMatchPage />
                </ProtectedRoute>
                }/>
                <Route path="/profile" element={
                 <ProtectedRoute>
                <ProfilePage />
                </ProtectedRoute>
                }/>
                <Route path="/match-history" element={
                  <ProtectedRoute>
                <MatchHistoryPage />
               </ProtectedRoute>
                }/>
              </Routes>
               </div>
                {user && <OnlineUsers />}
              </BrowserRouter>
              )}
              </div>
             </ErrorBoudry>
            );
         }
export default App

NAVBAR.JS

export default function Navbar() {

    const { logout, isPending } = useLogout()
    const { user } = useAuthContext()

    return (
        <div className='navbar'>
            <ul>
                <li className='logo'>

                    <span>Gamers Meet</span>
                </li>

                {user ?
                    <li>
                            {!isPending && <button className='btn' onClick={logout}>logout</button>}
                            {isPending && <button className='btn' disabled>logging out</button>}
                    </li>
                :
                    <>
                            <li>
                            <Link to='/landing'>Home</Link>
                            </li>

                        <li>
                            <Link to='/login'>login</Link>
                        </li>
                        <li>
                            <Link to='/register'>Register</Link>
                        </li>
                    </>
                }
            </ul>
        </div>

    )

}

SIDEBAR.JS

export default function Sidebar() {


    const { user } = useAuthContext()

    return (
        <div className='sidebar'>
            <div className='sidebar-content'>
                <div className='user'>
                    <Avatar src={user.photoURL} />
                    <p>hey {user.displayName}!</p>
                </div>
                <nav className='links'>
                    <ul>
                        <li>
                            <NavLink exact to='/dashboard'>
                                <img src={DashboardIcon} alt='dashboard icon' />
                                <span>dashboard</span>
                            </NavLink>
                        </li>
                        <li>
                                <NavLink to='/findMatch'>
                                <img src={AddIcon} alt='add icon' />
                                <span>Find a Match</span>
                            </NavLink>
                        </li>
                    </ul>
                </nav>
            </div>

        </div>
    )
}

PROTECTEDROUTE.JS

import React from 'react';
import { Navigate } from 'react-router-dom';



const ProtectedRoute = ({ isLoggedIn, children }) => {
 if (!isLoggedIn) {
 return <Navigate to="/" replace />;
 }
 return children;
};
export default ProtectedRoute;

Qual a melhor forma para somar valores até uma data limite? (Tip Counter / Contador de gorjetas) jQuery

Preciso construir um contador de gorjetas, que seguem algumas regras – o usuário que controla a página pode adicionar através de alguns campos:

  • O valor inicial arrecadado em gorjetas (exemplo, 250,00)
  • O valor a ser somado
  • Um valor para indicar em quantos dias esses 2 valores devem ser somados.

Em outras palavras, inicialmente tenho acumulado em gorjetas 250 reais e em 4 dias quero mostrar para o usuário que agora temos 450. Utilizando setInterval para mostrar dinamicamente a cada segundo o contador subindo.

Parando para analisar agora também noto que preciso indicar o dia inicial para começar a valer o contador, uma vez que não uso banco e nem busco informações no servidor. Adicionar esse campo para o usuário também é possível.

        var tipCounterDataReference     = jQuery(".counter-item"); 
        var initialValue                = tipCounterDataReference.attr('data-initial-value'); //eg: 250,00
        var daysDuration                = tipCounterDataReference.attr('data-days-duration'); // 4
        var increasementValue           = tipCounterDataReference.attr('data-increase-value'); // 200
        //converte o valor de dias para milissegundos:
        var milliseconds                = parseFloat(daysDuration * 24 * 60 * 60);
        var resultField                 = jQuery("#tip-counter-result");
        
        var currentTime = new Date();
        setInterval(function() {
            //TODO corrigir formula esta errada
            var money = parseFloat(initialValue) + parseFloat(increasementValue);

            resultField.text('R' + money.toFixed(2).replace(".", ","));

        }, 1000);

Por fim, preciso de uma ajuda para abstrair a fórmula que faz isso :/

Fast Scrolling, the content disappears from the viewport

I have built a webpage with static content, without scrolling effects or javascript events on scrolling. My issue is that if I scroll fast from top page to bottom, the content disappears and appears again after 0.5 seconds, Even divs with colored backgrounds disappear for an instant and that appears again.
Could you please let me know why this is happening? Why my content do not stay visible no matter how fast I scroll the page, I would like a scroll-like on the stack overflow website.

Thanks,
Andrei

How to prevent all breakpoints in chrome?

I’d like to configure Chromium to always ignore breakpoints. Several sites I have to use adopt anti-user behavior of calling debugger; from some JS blob to inconvenience developer tools access. I know I can toggle Breakpoints (ctrl+f8) but since it resets on opening and closing the developer tools it gets inconvenient.

Is it possible to either permanently disable breakpoints all together, or to make the Breakpoints toggle setting persist indefinitely?

Javascript-Sorting elements of div

<div> class="tasks">
    <div> class="task">
        <span> id="taskname">1</span>
    </div>
    <div> class="task">
        <span> id="taskname">2</span>
    </div>
    <div> class="task">
        <span> id="taskname">3</span>
    </div> 
    ...
</div>

Hello.My code is like this. I have to sort div elements. But I don’t know how.

How to get from local storage when key is crazy

Msal is storing tokens to my localstorage with a crazy string, multiple of them. 1 accesstoken, 1 refresh token and a tokenId. I just need to get the refresh token value.. but the key is 35eef60c-0000-0000-0000-20cd77000000.bf390000-0000-0000-0000-528094e00000-login.windows.net-refreshtoken-00000000-0000-0000-bf00-000000000003—-
How would I attempt to get this value when the key changes its string and is so long?

How to use bleno in real-time situation?

I have an iOS application that communicates BLE with an embedded linux module running nodejs.

I am using bleno 0.5.0 to get that communication working.

Getting the information needed takes around 2sec.

Now, I needed to have another app running in that linux module to run in real-time with priority 1 (PR=-2).

This makes the BLE communication going very slow and instead of 2sec to get everything, it takes around 20 to 40sec.

The Linux box is running Bluez and this is what bleno needs.

So, I tried to run my javascript using bleno with the same real-time priority

chrt -r 1 node myapp.js

It took more time than the ‘normal’ priority (up to 50sec)

I tried to run nice -n -20 instead and got around 20sec.

Now my question is does the bleno is running real-time also when executing with chrt -r 1 or only my javascript?

Or what else could make the BLE communication slows down that much?

I also noticed that sometimes I see Bluetooth: received HCILL_WAKE_UP_IND in state 2 popping up from Linux. Maybe related to my issue?

Thanks in advance

p5js 3d text performance issue

i wonder if there is a way to improve performance. I think that the problem might be that I instantiate the object inside the draw() function, but I’ve no idea how to change the value of the text.
Thanks


function setup() {
      createCanvas(windowWidth, windowHeight, WEBGL);
      background(255);
      
      // Ignore this, fix for easyCam in p5 version 0.7
      Dw.EasyCam.prototype.apply = function(n) {
      var o = this.cam;
      n = n || o.renderer,
      n && (this.camEYE = this.getPosition(this.camEYE), this.camLAT = this.getCenter(this.camLAT), this.camRUP = this.getUpVector(this.camRUP), n._curCamera.camera(this.camEYE[0], this.camEYE[1], this.camEYE[2], this.camLAT[0], this.camLAT[1], this.camLAT[2], this.camRUP[0], this.camRUP[1], this.camRUP[2]))
    };
      
      cam = createEasyCam();
      cam.zoom(3000);
      
  }
    
    function displayX(data){      
      word = new Word3D(
    data,       // The actual character that you want to draw (anything that can be passed into "text()")
        4,             // How thick the 3D rendered letter is (i.e. how many cube pixels of size "size" it is on z-axis)  
        width/200,     // The size of a unit "box()" making up part of the letter  
        50,            // The size of the canvas it renders the letter on (higher is more detailed, 30-40 is a good range)  
        true,          // [OPTIONAL, default = true] Gives the bevelled, embossed 3D look (as seen in screenshot)  
        "Arial",     // [OPTIONAL, default = "Georgia"] Gives the font uses, can be any default ones or anything added  
        BOLD           // [OPTIONAL, default = BOLD] Gives the chosen style out of BOLD, NORMAL, ITALIC  
      );

    }

  function draw() {
  
    data =  new Date().toLocaleString(undefined, {year: 'numeric', month: '2-digit', day: '2-digit', weekday:"long", hour: '2-digit', hour12: false, minute:'2-digit', second:'2-digit'})

    background(255);

      displayX(data);
      normalMaterial();
      word.show(); 

  }

socket.io ERR_CONNECTION_REFUSED and Failed to load resource

Hello I try to establish a two-way connection with socket.io but I receive these two errors:

socket.io.js:1 Failed to load resource: net::ERR_CONNECTION_REFUSED Maniptwo.php:889

Uncaught ReferenceError: io is not defined at Maniptwo.php:889

I’m at my first use of socket.io so sorry if my questions seem stupid.

server.js :

```
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);


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

io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
  socket.on('chat message', (msg) => {
    console.log('message: ' + msg);
    
  });
});

server.listen(3000,'192.168.2.38', () => {
  console.log('listening on *:3000');
}); ```

client

```
<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io();
  socket.emit('chat message', "hello");
</script>
```

the client runs on an apache server is it possible that apache prevents the connection of the socket