Can javascript cause 1-2 min delay randomly before displaying a web page?

Since I added the following javascript in the header of my webpages code as well as used hisorange/browser-detect in Laravel, I experienced random delay every 10-15 min before the requested page appears on screen. After that everything is completely normal for another 10-15 min then it happens again and again…

In Firefox dev tools, there is no network activity… just a long delay.

The purpose of the above is to detect window size and resize and display the correct html code in Laravel blade.

 <script type="text/javascript" src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js"></script>
 <script type="text/javascript">
 var limit = 769;
 var width = $(window).width();
 Cookies.set('windowW',$(window).width(),{ expires:7});
 $(window).resize(function() {
     if ((width > limit && $(window).width() < limit) || (width < limit && $(window).width() > limit)) {
           Cookies.set('windowW',$(window).width(),{ expires:7});
           location.reload();
      }
 });
 </script>

For xxx, here is the code I have in AppServiceProvider.php:

 use Browser;

 $platform = 'desktop'; $is_mobile = false;
 if (Browser::isMobile()) { $platform = 'mobile'; $is_mobile = true; }
 else if (Browser::isTablet()) { $platform = 'tablet'; $is_mobile = false; }
 if (getCookie('windowW')) { $windowW = getCookie('windowW')[0]; } else { $windowW = 1000; }

When I remove the javascript above as well as the use of Browser, I do not get delays anymore.

So my question is … is there anything wrong in the way I am doing that? And is it possible that the code above could cause the error?

TypeScript/ES6: what is an “:” in the below context?

I understand below two usages in TS/ES6.

  1. Below, a variable myname of type string which is going to be constant(final) is declared.

    const myname: string = ‘abcd’;

  2. Below a variable/function initialPath is declared and is assigned a function body using the => operator.

    const initialPath = ({pathRoot, myvar = ”, locale = ”}) =>
    path.join(process.cwd(), pathRoot, myvar, locale.toLowerCase());

But I am not sure of the below usage, what is : in the below doing.

module.exports = {
  application: myname,
  myservicePostfix,
  loadablePath: ({pathRoot, myvar}) =>
    path.join(basePath({pathRoot, myvar}), 'loadable.json')
}

-> does application: myname mean that application = myname and application is of type typeof(myname).
-> similarily what does loadablePath: above mean

is sync state with prop bad in react?

If I do this, passing prop as default state, it won’t update if I do

const MyComp = ({ isOpen: _isOpen }) => {
const [isOpen, setIsOpen] = useState(_isOpen)

return <div>{isOpen.toString()}<button onClick={() => setIsOpen(true)}></button></div>
}

I fixed it with this

const MyComp = ({ isOpen: _isOpen }) => {
const [isOpen, setIsOpen] = useState(false)

useEffect(() => {
setIsOpen(_isOpen)
}, [_isOpen])

return <div>{isOpen.toString()}<button onClick={() => setIsOpen(true)}></button></div>
}

is this an anti-pattern?

canvasjs-chart in angular 2way binding

I am using canvasjs-chart in my angular to draw chart.(I am new in Angular)
here is my component ts code :

import { Component } from '@angular/core';
import { NgModule } from '@angular/core';
@Component({
  selector: 'app-counter-component',
  templateUrl: './counter.component.html'
})
export class CounterComponent {
  public books = [{
    title: "Life is good",
    author: "benny",
    category: "life"
  }, {
    title: 'Canned in',
    author: "francis",
    category: "style"
  }];
  chartOptions = {
    title: {
      text: "Basic Column Chart in Angular"
    },
    data: [{
      type: "line",
      dataPoints: [
        { label: "Apple", y: 121 },
        { label: "Orange", y: 15 },
        { label: "Banana", y: 25 },
        { label: "Mango", y: 30 },
        { label: "Grape", y: 28 }
      ]
    }]

  };
  public changeChartData() {
    this.chartOptions.data[0].dataPoints[0].y =20;
  }

As you can see I have a books object which it passed to html :

<button class="btn btn-primary" (click)="changeChartData()">change chart Data</button>
<canvasjs-chart [options]="chartOptions"></canvasjs-chart>

The data is shown correctly but my problem is when I click on the change chart Data to change the value of my books object I can’t see the changes in the chart .I think the problem is the chart is not binding to books object

in angular v16 project I need to wait for an http response in a sync manner for a guard and other components handle the result

I’m using an AuthService into which I created a function that returns a boolean, isUserAuthenticated(): boolean. Into this function according some conditions, I need to make an http call to recover user data from backend, and according to the response, the function will return true/false to a guard or other components take the decision to redirect user to login page.

Here is my function:

isUserAuthenticated(): boolean {
  return this.checkUserAuthenticated();
}

Due to http is async I had to use async/await this way:

private async checkUserAuthenticated() {
    const token = this.sessionStorageService.getTokens();
    const user = this.sessionStorageService.getUser();
    const isUserDataOk = user.username !== '' && user.username != undefined;

    if (token != null && user.id != null && isUserDataOk) {
      this.userAuthenticated = true;
      return true;
    } else if (!isUserDataOk && user.id != null) {
      const result = await this.recoverUserData(user.id);
      if (result.body?.user != undefined) {
        this.userAuthenticated = true;
        return true;
      }
    } else {
      this.userAuthenticated = false;
      return false;
    }

    return this.userAuthenticated;
  }

Code is going through await this.recoverUserData(..) that calls the http:

private async recoverUserData(userId: string)  {
    console.log('recovering user data');

    return await firstValueFrom(
      this.http.post<LoginResponseDto>(
        AppApis.Auth.signInData, { 'userId': userId }, { observe: 'response' }
      )
    );
  }

The problem is these chain of async calls are becoming hard to manage as sync, the line of code: return this.checkUserAuthenticated(); is returning a promise<boolean> but I need a simple boolean because for example can activate guard condition is: if (authService.isUserAuthenticated()) return true.

firstValueFrom is new and it returns a promise from an observable.

React Echarts Error for render custom Svg floor plan

I use react to visualise a Svg floor plan (heatmap) in reactjs.
However, it will return error at「cannot read properties of undefined (reading regions)」.

I have struggled for this issue several weeks, please give me some hints! Thanks

Kindly find the source code and Svg file below for your further investigation

Code:

import React, { useRef, useEffect } from "react";

import * as echarts from "echarts";

import mapData from "./map.svg";

export default function Heatmap(){

const ref = useRef(null);

let mapInstance = null;

const option = {

    tooltip: {},

    visualMap: {

    left: 'center',

    bottom: '10%',

    min: 5,

    max: 100,

    orient: 'horizontal',

    text: ['', 'Price'],

    realtime: true,

    calculable: true,

    inRange: {

        color: ['#dbac00', '#db6e00', '#cf0000']

        }

    },

series: [

  {

    name: 'French Beef Cuts',

    type: 'map',

    map: 'testing',

    roam: true,

    emphasis: {

      label: {

        show: false

      }

    },

    selectedMode: false,

    data: [

      { name: 'Queue', value: 15 },

      { name: 'Langue', value: 35 },

      { name: 'Plat de joue', value: 15 },

      { name: 'Gros bout de poitrine', value: 25 },

      { name: 'Jumeau à pot-au-feu', value: 45 },

      { name: 'Onglet', value: 85 },

      { name: 'Plat de tranche', value: 25 },

      { name: 'Araignée', value: 15 },

      { name: 'Gîte à la noix', value: 55 },

      { name: "Bavette d'aloyau", value: 25 },

      { name: 'Tende de tranche', value: 65 },

      { name: 'Rond de gîte', value: 45 },

      { name: 'Bavettede de flanchet', value: 85 },

      { name: 'Flanchet', value: 35 },

      { name: 'Hampe', value: 75 },

      { name: 'Plat de côtes', value: 65 },

      { name: 'Tendron Milieu de poitrine', value: 65 },

      { name: 'Macreuse à pot-au-feu', value: 85 },

      { name: 'Rumsteck', value: 75 },

      { name: 'Faux-filet', value: 65 },

      { name: 'Côtes Entrecôtes', value: 55 },

      { name: 'Basses côtes', value: 45 },

      { name: 'Collier', value: 85 },

      { name: 'Jumeau à biftek', value: 15 },

      { name: 'Paleron', value: 65 },

      { name: 'Macreuse à bifteck', value: 45 },

      { name: 'Gîte', value: 85 },

      { name: 'Aiguillette baronne', value: 65 },

      { name: 'Filet', value: 95 }

    ]

  }

]

}

const renderMap = (myChart) => {

    /*const renderedMapInstance = echarts.getInstanceByDom(ref.current);

    if (renderedMapInstance) {

      mapInstance = renderedMapInstance;

    } else {

      mapInstance = echarts.init(ref.current);

    }

    mapInstance.setOption(option);*/

    myChart.setOption(option)

  };

  useEffect(() => {

    fetch(mapData)

      .then((response) => response.text())

      .then((svgText) => {

        echarts.registerMap("testing", { svg: svgText });

      });

    var chartDom = document.getElementById('beef');

    var myChart = echarts.init(chartDom);

    renderMap(myChart);

  }, []);

/*

  useEffect(() => {

    window.onresize = function () {

    };

    return () => {

      mapInstance && mapInstance.dispose();

    };

  }, []);  mapInstance.resize();

    

*/

  return (

    <div>

      <div style={{ width: "100%", height: "50vh" }} ref={ref} id='beef'></div>

    </div>

  );

}

———————————————————————————————

Svg file

        <svg

                              xmlns="http://www.w3.org/2000/svg"

                              width="591"

                              height="373"

                              preserveAspectRatio="xMidYMid meet"

                              viewBox="0 0 376 237"

                            >

                              <g transform="translate(-7.69,10.06)">

            

            <path

              

              d="m 536.375,106.46875 c 5.2885,14.34201 10.52945,33.1769 13.78125,43.21875 -0.0655,0.0771 -0.13181,0.1476 -0.21875,0.21875 l 16.5625,0.9375 10.5,-8.5 11,-17 -13.5,-18 -38.125,-0.875 z"

              stroke="#A5A5A5" 

              stroke-width="0.75"

              stroke-linecap="round"

              fill="#FFFFFF"

              fill-rule="evenodd"

              id="path3702"

              name="Langue" 

              transform="matrix(0.6362812,0,0,0.6362812,7.6936433,-10.065285)"

            />

            

            </g>  

        </svg> 

What is the best way to pass session data from a Client component to a server component in NEXT.js 13>?

I am developing a web app where I need to pass session?.user?.email from useSession() in next-auth/react to a sever side component where it carries out a fetch request to /api/users/email/ to find out if a user exists with that particular email address.

After reading the documentation, I realised that you are not supposed to use server components inside 'use client' components where I have my useSession()

What is the best way to structure this?

org.jinterop.dcom.common.JIException: The object name is not found [0xC0000034]

I am having a problem using “J-INTEROP” trying to make an OPC DA client for andriod devices.

I made all the DCOM configurations and today I can connect to the server from any PC that is within my network regardless of the user that connects.

The error that is throwing me is: org.jinterop.dcom.common.JIException: The object name is not found [0xC0000034]

The OPC DA server I am using is KepServerEX.V4

The error occurs in the following line: val comServer = JIComServer(JIProgId.valueOf(“KEPware.KEPServerEx.V4”), “192.168.1.11”, session)

import android.os.Bundle
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.jacob.com.Dispatch
import org.jinterop.dcom.common.JIException
import org.jinterop.dcom.common.JISystem
import org.jinterop.dcom.core.IJIComObject
import org.jinterop.dcom.core.JIComServer
import org.jinterop.dcom.core.JIProgId
import org.jinterop.dcom.core.JISession
import org.jinterop.dcom.impls.JIObjectFactory
import org.jinterop.dcom.impls.automation.IJIDispatch
import java.net.UnknownHostException



class MainActivityOPCDA : AppCompatActivity() {

    lateinit var errortextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main_opcda)

        errortextView = findViewById(R.id.etextView)

        Thread(Runnable {
            JISystem.setInBuiltLogHandler(false)
            JISystem.setAutoRegisteration(true)


            
            val session = JISession.createSession("192.168.1.11", "opcuser", "123456")
            session.useSessionSecurity(true)
            session.globalSocketTimeout = 5000



try {

   val comServer = JIComServer(JIProgId.valueOf("KEPware.KEPServerEx.V4"), "192.168.1.11", session)


   val serverObj = comServer.createInstance() as IJIComObject

   val opcServer = JIObjectFactory.narrowObject(serverObj.queryInterface("6E6170F0-FF2D-11D2-8087-00105AA8F840"))

                val opcServerDispatch = opcServer.queryInterface(IJIDispatch::class.java.name) as Dispatch
                val server = Dispatch.call(opcServerDispatch, "QueryInterface", IJIDispatch::class.java.name).toDispatch()




            } catch (e: JIException) {

                e.printStackTrace()
                runOnUiThread {
                    errortextView.text = "ERROR: ${e.message.toString()}"
                }


            } catch (e: UnknownHostException) {
                e.printStackTrace()
                runOnUiThread {
                    errortextView.text = "ERROR: ${e.message.toString()}"
                }
            }
 }).start()


    }

I did a lot of testing on the DCOM setup. Assuming a problem with some windows permission, for these tests I am using Windows 10. And the tests are with real andriod devices.

I also did tests with different OPC DA clients for windows and the communication with the server works correctly for me.

How to debug a scroll block in JavaScript

I’m using scrollIntoView(), but the behaviour is the same for scrollTo(...) and even location = '#....

When I use a timeout > 500ms for the scrolling action it works. How can I debug this? Something must be interfering with the programmatic scrolling.

PS: When clicking a button which has as href #..., the scrolling works also. Somehow, the user event goes through without the need for a timeout.

jQuery.remove() and array.splice() issue

So I have a page where there’s an item list and a shopping list. If you add an x number of items from the items list to the shopping list, then try to remove them one by one, by clicking on the items from the shopping list and hitting delete on the modal that opens it works – the first time. Now here’s the problem, if you try doing that all over again, for example adding another set of x number items to the shopping list and try to remove them one by one again. As soon as you hit the delete button on the modal I get unpredictable results, it either removes ALL the shopping list items, or 2 or 3 along with the item you’re supposed to delete.

It’s a simple jQuery.remove() and array.splice yet I can’t get it to work. Apparently it’s more complicated than I thought, and I’ve tried doing it a bunch of different ways.

Here’s the page:
http://bigbiz.io/pos/

Thanks in advance!

Refactoring the code

Search for a keyword in multiple files and return me the result with previous and following line

I’m using Node JS, I want to search for a keyword in multiple .txt files, and then that return me the previous line and the following one.

Im expecting something like this:

Cars
Scooters
Skates
Airplanes
Ships
Trucks
Bikes

Then I search for the word using some nodejs package, in this example is ship. So the package return to me the line that is upper and down. For example something like this:

{"result":"
Airplanes
Ships
Trucks
"}

Forwarding a request from Nodejs

I need to forward / redirect request received by nodejs endpoint to a .net 7 web API end point. Nodejs endpoint is triggered by an external party and it receives the request as expected. the problem is redirecting / forwarding from nodejs to .NET web api endpoint, its not getting triggered.

This is my code block.

exports.rerouteIncomingEmail = async (req, res)  => {

var to = extractRequestHeaders(req.headers, 'x-recipient');
var endPoint = await services.getPushEndpointFromEmailList(to,req.app.locals.db);

endPoint ? res.redirect(308,endPoint) : res.send(200,'endpoint not found');    

};

How I can make website like codewithharry

How I can make website like codewithharry

I want to create website like codewithharry design is ready but need BACKEND

Can anyone help. Me to create it

Or any steps or tutorials or any tutorial which have tell or make website back-end like him plz answer…………..,..,…,..,,.,,.,..,.,………

I want to create website like codewithharry design is ready but need BACKEND

Can anyone help. Me to create it

Or any steps or tutorials or any tutorial which have tell or make website back-end like him plz answer…………..,..,…,..,,.,,.,..,.,………

DiscordJS v14 – How to check if bot is already connected to a voice channel?

So I have a problem that when I use interaction.member.guild.voiceStates.cache.get('BOT_ID') it doesn’t update when the bot is already disconnected or being moved.

const getVoice = interaction.member.guild.voiceStates.cache;
const botVoiceChannel = getVoice.get('BOT_ID');

if (botVoiceChannel) {
  errEmbed = new EmbedBuilder()
  .setDescription("I'm already connected to a voice channel")
  return interaction.reply({ embeds: [ errEmbed ] });
}

I expect the value of botVoiceChannel to change to a new voice channel or null when the bot is being moved or disconnected.

lingui library’s macro t not working on react

i use the this latest library for translate, but the macro t not working, the <Trans> working fine.

To Reproduce

  1. open codesandbox
  2. yarn install
  3. yarn start
  4. click different language on the top of screen

bug description:
only content in <Trans> content </Trans> will translated, but the last content on {t`hello react`} not translated.

index.tsx:

import React from 'react';
import ReactDOM from 'react-dom/client';
import reportWebVitals from './reportWebVitals';
import { StoreProvider } from './components/store-provider';
import createStore from './store'
import { LanguageProvider } from './components/language-provider';
import { LangSwitcher } from './components/lang-switcher';
import { Trans, t } from '@lingui/macro';

const store = createStore();

const root = ReactDOM.createRoot(
    document.getElementById('root') as HTMLElement
);
root.render(
    <React.StrictMode>
        <StoreProvider store={store}>
            <LanguageProvider>
                <LangSwitcher />
                <p>
                    <Trans>hello world</Trans>
                </p>
                <p>{t`hello react`}</p>
            </LanguageProvider>
        </StoreProvider>
    </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. 
reportWebVitals();

package.json:

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@lingui/react": "^4.1.2",
    "@reduxjs/toolkit": "^1.9.5",
    "@testing-library/jest-dom": "^5.14.1",
    "@testing-library/react": "^13.0.0",
    "@testing-library/user-event": "^13.2.1",
    "@types/jest": "^27.0.1",
    "@types/node": "^16.7.13",
    "@types/react": "^18.0.0",
    "@types/react-dom": "^18.0.0",
    "make-plural": "^7.3.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.5",
    "react-scripts": "5.0.1",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.2.3",
    "typescript": "^4.4.2",
    "web-vitals": "^2.1.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
        "extract": "lingui extract --clean",
    "compile": "lingui compile --strict"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@lingui/cli": "^4.1.2",
    "@lingui/macro": "^4.1.2"
  }
}

lingui.config.ts:

const linguiConfig = {
  catalogs: [
    {
      path: '<rootDir>/src/locales/{locale}/messages',
      include: ['<rootDir>/src'],
    },
  ],
  compileNamespace: 'cjs',
  fallbackLocales: {
    default: 'en-US',
  },
  format: 'po',
  formatOptions: {
    lineNumbers: false,
  },
  locales: [
    'en-US',
    'zh-CN',
    'zh-TW',
  ],
  orderBy: 'messageId',
  rootDir: '.',
  runtimeConfigModule: ['@lingui/core', 'i18n'],
  sourceLocale: 'en-US',
  pseudoLocale: 'pseudo',
}

export default linguiConfig

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
        "baseUrl": "src"
  },
  "include": [
    "src"
  ]
}