Why am I receiving this type error in my function

This is my Javascrip file that shows for my tetris game, like in the game the object is to cover a row and have it removed however in the removed squares section it will not work giving me a type error saying squares.splice is not a function

function scoreBoard () {
    for (let i = 0; i < 199; i +=width) {
        const rows = [i, i+1, i+2, i+3, i+4, i+5, i+6, i+7, i+8, i+9]

        if(rows.every(index => squares[index].classList.contains('taker'))) {
            score +=10
            scoreDisplay.innerHTML = score
            rows.forEach(index => {
                squares[index].classList.remove('taker')
            })
            const removedSquares = squares.splice(i, width)
            console.log(removedSquares)
        }

    }
}

Merge and remove duplicates from multiple arrays

My function takes an array of arrays and returns the merged array without duplicates

function mergeArrayOfPrimitives<T>(
  primitiveArraysTobeMerged: Array<Array<T>>
): Array<T> {
  const merged: Array<T> = [];
  primitiveArraysTobeMerged.forEach((primitiveArray: Array<T>) =>
    [...merged].concat([...primitiveArray])
  );
  return [...new Set([...merged])];
}

But when I test it on typescript playground with below inputs, it returns [] instead of ['CORE - AGILE']

console.log(mergeArrayOfPrimitives([[], ['CORE - AGILE']])); ==> [LOG]: []

Using Inertia in a Modularised Laravel app

Inertia is working nicely in my Laravel App. I’ve set it up as per the Inertia pages, not entirely dissimilar to this >> guide (though there are significant differences in my app).

I’m in the process of trying to modularise >> my app, which again I have no issues with in principle. the Modules functionality works nicely.

The issue I’m having is that I’d like to build my Vue logic inside each of my modules’ “Resources” directory. When I have many modules, this means that the source Vue code will be spread over many “Modules”, meaning that the resolve() function (in the JS script below) needs to check different locations for the files.

I found this SO >> post on how to “discover” Vue files from different locations. Because import.meta.glob won’t accept dynamic values, it has to be executed via a switch or complex array of if statements (or whatever). This much is fine as well. If I switch the moduleVar parameter for a hard-coded value in the code below, I can load files from different modules (a few pseudo-cody glitches notwithstanding – code has been simplified to illustrate my problem).

The problem is that I can’t find a way to pass the moduleVar parameter into the resolve() function. Conceptually, what I’d like to do is the following:

createInertiaApp({
  id: 'app',
  resolve: async(name, moduleVar) => { // moduleVar is pseudo-code. I can't find a way to actually pass a parameter in here
    const dirs = {
      'appfnd': () => import.meta.glob('../../Modules/appfnd/Resources/assets/js/vue/**/*.vue'),
      'sales':  () => import.meta.glob('../../Modules/sales/Resources/assets/js/vue/**/*.vue',
      'std':    () => import.meta.glob('./vue/**/*.vue'),
    };
    const pages = dirs[moduleVar](); // if I hard-code moduleVar to (e.g.) 'sales' my app works
    let page;
    switch (moduleVar) {
      case 'appfnd':
      case 'sales':
        page = (await pages[`../../Modules/${moduleVar}/Resources/assets/js/vue/${name}.vue`]()).default;
        break;
      default:
        page = (await pages[`./vue/${name}.vue`]()).default;
    }

    if (page.layout === undefined) {
      page.layout = Layout;
    }
    return page;
  },
  setup({ el, App, props, plugin }) {
    createApp({ render: () => h(App, props) })
      .use(plugin)
      .use(store)
      .use(ZiggyVue, Ziggy)
      .component('Head', Head)
      .component('Link', Link)
      .mount(el);
  },
  title: (title) => title + " - My Lovely App",
});

My idea is that the value would be passed in from Laravel’s Controller, something like this:

<?php

namespace ModulesAppFoundationHttpControllers;

use AppHttpControllersController;
use InertiaInertia;

class PersonController extends Controller
{
    private $module = 'appfnd';

    public function fnFromLaravelRouter() {
        // `moduleVar` parameter in line below, matches variable name that I'd like to pick up in the JS code above.
        // This doesn't actually work, but hopefully illustrates what I'd like to achieve
        return Inertia::render('modules/appfnd/MyVueFile', ['moduleVar',$this->module]);
    }
}

The name parameter inside the JS resolve() function is the name of the file passed in from Inertia::render(), which in the above example is 'modules/appfnd/MyVuFile'. What I could do is to perform some string manipulation on this value, essentially passing in the data I want via a hack. Buck I want to know if there’s a better way to achieve what I want.

Hopefully I’ve explained clearly enough!

$http get request with angularjs

I’m very new to AngularJS and I’m trying to make a weather app just for practice.
as weather service i use: https://openweathermap.org. my http request does not work, here’s my code:

angular.module("weather", []).controller('WeatherController', function($scope,$http){
    
$scope.getWeather = function() {
    $http.get('https://api.openweathermap.org/data/2.5/weather?q=London&appid=69f76656f3a6e0a34db5e6052e851f76', config).then(function successCallback(response){
        console.log(response);
    }, function errorCallback() {
        console.log('error');
    }) 
}
        
    
      
   
});
<div class="n-p-b" ng-app="weather" ng-controller="WeatherController">
<button ng-click="getWeather()">click</button>
    <img src="png/righr-arrow .png" class="arrow-right">
    <div class="card" style="width: 50rem; height: 35rem; border-radius: 5%; box-shadow: 0 0 2rem rgba(0, 0, 255, 0.1);">
        <img src="img/blue.png" class="card-img-top" alt="...">
        <div class="card-body" style="padding: 0%;">
           <div class="b-card">
            <div class="twitter">
                <p>Twitter Feed</p>
            </div>

            <div class="weather-week">
                <p>mon</p>
                <p>tue</p>
                <p>wed</p>
                <p>thu</p>
                <p>fri</p>
                <p>sat</p>
                <p>sun</p>
            </div>
           </div>

          </div>
      </div>
    <img src="png/left-arrow.png" class="arrow-left">
    
</div>

I tried to use different forms of requests(shortcut etc),different links, but it does not work

WordPress with Elementor Latest Version Export Kit doesn’t work, any solution?

I have latest WordPress v6.2 and latest Elementor v3.12.0 and Hello theme v2.7.1. I made some page, section and container templates that I’d like to export. When I go to Elementor > Tools > Import / Export Kit and click on Start Export, I am just getting message “App could not be loaded”.

This is the error in console:

TypeError: Cannot read properties of undefined (reading 'remove')
at app.min.js?ver=3.12.0:3:40724
at Dr (react-dom.min.js?ver=18.2.0:10:73052)
at Or (react-dom.min.js?ver=18.2.0:10:73238)
at xl (react-dom.min.js?ver=18.2.0:10:92482)
at react-dom.min.js?ver=18.2.0:10:89829
at v (react.min.js?ver=18.2.0:10:3385)
at ce (react.min.js?ver=18.2.0:10:5527)
at A. (load-scripts.php?c=1&load%5Bchunk_0%5D=jquery-core,jquery-migrate,hoverIntent,utils,wp-polyfill-inert,regenerator-runtime,wp-polyfill,wp-hooks&ver=6.2:13:16077)
at P (load-scripts.php?c=1&load%5Bchunk_0%5D=jquery-core,jquery-migrate,hoverIntent,utils,wp-polyfill-inert,regenerator-runtime,wp-polyfill,wp-hooks&ver=6.2:13:15885)
at MessagePort.E (load-scripts.php?c=1&load%5Bchunk_0%5D=jquery-core,jquery-migrate,hoverIntent,utils,wp-polyfill-inert,regenerator-runtime,wp-polyfill,wp-hooks&ver=6.2:13:15942)

My server has ZIP support and has memory limit set to 512MB. PHP versions I tried are 7.4, 8.0, 8.1 and 8.2.

I need help immediately

Thank You

Chrome extension: Block file chooser popping up from a click event dispatched on a dynamically created element

I am trying to write an extension that tries to block file chooser from popping up when the user clicks on an element, with the goal to prevent file input.

This is what my content script looks like:

content.js

function preventFileChooser(event) {
  event.stopPropagation();
  event.preventDefault();
}

document.addEventListener('click', function(event) {
  if (event.target && event.target.nodeName === 'INPUT' && event.target.type === 'file') {
    preventFileChooser(event);
  }
}, true);

While this works for most cases, it fails when the input element is dynamically created (but not appended to the body) and a click event is dispatched upon it. An example of such a page:

test.html

<!DOCTYPE html>
<html>
<head>
    <script src='test.js'></script>
</head>
<body>
    <button id='btn'>click</button>
</body>
</html>

test.js

document.addEventListener('click', (e)=>{
  if(e.target.id==='btn'){
    var ele = document.createElement('input');
    ele.type='file';
    
    ele.addEventListener('change', async (e) => {
          //Here, using a package such as https://www.npmjs.com/package/file-selector allows the                    page to convert the file input into File objects.
    })
    
    ele.dispatchEvent(new MouseEvent('click'));
  }
})

jsFiddle : https://jsfiddle.net/yu0wjvb4/

In a page such as this, when the button is clicked, the content script fails to listen to the dispatched click event on the dynamically created (but not appended) input element and therefore fails to prevent the file chooser from opening.

Core questions about CSR/SSR and dynamic/pre-rendering SPA webpages

I want to rebuild our webpage and I am unsure whether I should build our webpage as a Vue.js SPA webpage or a Nuxt.js SSR webpage. Our webpage is basically a forum where people can post deals they found on the internet and discuss them. Therefore, I would guess SEO is critical for us.

I do know that webpages which are written in JavaScript and rely on client-side rendering, such as SPA webpages, are harder to be crawled and indexed by Google and some search engines cannot even crawl/understand JavaScript webpages.

However, the user experience is a lot better when it comes to SPA webpages. Just take your smartphone and visit the mobile version of airbnb.com. It’s insanely smooth and really feels like a native app.

What I want to know and what I do not understand so far is the following:

  1. There is an option called pre-rendering. This technic allows us to create an SPA webpage but the Googlebot or any other crawling bot of a search engine will get delivered a static HTML version of our SPA webpage. Therefore, the bot has is much easier to read and understand the content of our webpage. There is a service called prerender.io which can do exactly this for me. However, it’s a paid service and it’s quite expensive.
    I also came across some plugins for Vue.js such as rendora and prerender-spa-plugin. Sadly, the prerender-spa-plugin is deprecated, it has not been updated in years and I haven’t found a newer supported version. However, the question is, is pre-rendering even an option as we have quite a dynamic webpage which gets added new pages (deals) continuously? I have read, that pre-rendering is not really scalable.

  2. Can I use an SPA which makes use of SSR as well or not? I am a bit confused and I am unsure whether it is possible to do that.

  3. Are there any other alternatives to prerender.io or plugins like rendora or prerender-spa-plugin for achieving SEO-friendly rendering of an SPA webpage?

Kind regards

Get Chinese punctuation in a string

With the answers in

I have gotten close to what I need: get all the Chinese punctuations in the string.

And Intl.Segmenter is much better than String.prototype.split(" ")

But with one problem /p{P}/u.test(segment.segment) test all the punctuations, not just Chinese punctuation, so I get English punctuation like apostrophe, comma, question mark and period.

I hope I need not to resolve to the answer in Chinese punctuation Unicode range?. It is too complicated. According to this wiki about Chinese punctuation there are only about 20.

So is there any easy way to do that ?

const str = "你好,让我们试试这个分词效果,你说怎么样?Let's try Intl.Segmenter, should we ?"
let segmenterZH = new Intl.Segmenter('zh', { granularity: 'grapheme' })
let segments = segmenterZH.segment(str)
for (let segment of segments) {
  if (/p{P}/u.test(segment.segment)) {
    console.log(`${segment.index}:${segment.segment}`)
  }
}

Flow error property is missing in object literal [1] when using reduce to create a dictionary from an array

I’m trying to use reduce to create a dictionary from an array. However I run into a flow error property is missing in object literal [1] when using reduce to create a dictionary from an array. This happens for all three keys ‘A’, ‘B’, and ‘C’.

  const foo = [
    'A',
    'B',
    'C',
  ];

  const bar = foo.reduce((acc, curr) => {
 
    // the actual code will do some logic on the string value in foo
    // but for the test just create a dictionary of the key to itself as value

    acc[curr] = curr;
    return acc;
  }, {});

https://flow.org/try/#1N4Igxg9gdgZglgcxALlAJwKYEMwBcD6aArlLnALYYrgA2WAzvXGCADQgYAeOBARgJ74AJhhhYiNXClzEM7DFCLl602QF92kEdQA6UAAT7IUern0wIEfQF59AbT2HDAcgCCz1o6fOAQh68uAML+BvoAugDcel7Gpvq8WGg25pYAdJhCRGAYABQ5OGCsRkRoaACUNgB8+sCOAfoA9A36uAAWGPo8RFg0RhAi+gDucDS9Qlb0EJT6NJYA1kQADvrQKRD1TfFEZhZJbR24GHEAVkRxYJhYh536Qsxk0In8KzAt7fpzGM+4VnC49BgaK8GPoAG49IgYaKhQwFOxgEpoMLJBGlKIw-SYXAlAwFdGGDQ1NRlCJsECgjBoJjQaiggAMqQATHSACypOkgNRAA

How does equality operator work? Because my code is not working [closed]

I’m trying to make a roller which rolls 1 to 6 and if it rolls 6 it rolls again up to 2 times, and my problem is that if I roll two 6’s the third 6 does not roll

Also the problem might be really obvious but I tend to make stupid mistakes.

hn = 100 //Math.floor(Math.random() *100 +1)
guesses = 0;

document.getElementById('submit').onclick = function() {
  guess = document.getElementById('textbox').value

  if (guess > hn) {
    document.getElementById('yn').innerHTML = 'Wrong, ur                          guess is too high!'
    guesses += 1
  } else if (guess < hn) {
    document.getElementById('yn').innerHTML = 'Wrong, ur guess is too low!'
    guesses += 1
  }

  //i think the prob,em is here since this is the third dice roller
  else if (guess == hn) {
    guesses += 1
    document.getElementById('yn').innerHtml = 'HORRAY, u got it right in {guesses} tries!'
  }
}
<!DOCTYPE html>
<html>

<head>
</head>

<body>
  <h3><label id="Mylabel"> Guess a number from 1 to 100!       
    </label></h3>
  <hr><br>
  <input id="textbox" placeholder="for example 50"><br>
  <hr>
  <button id="submit">guess</button>
  <h5><label id="yn"></label></h5>
</body>

</html>

I tried everything with my pea brain but it just does not work.

Effective way to update array object in javascript

i have to update an element in array object based on a condition. currently i am using forEach and based on condition i am applying calculation in that element. i want to know the easiest way to updating the array without for loop
below is my array

[{index:123,total:20,family:'mobile'},
{index:321,total:40,family:'mobile'},
{index:543,total:54,family:'mobile'}]

i want to update total with total*2 for an element with index ‘321’in the above array
my array should look like below after executing logic

[{index:123,total:20,family:'mobile'},
{index:321,total:80,family:'mobile'},
{index:543,total:54,family:'mobile'}]

i am using below code

var selectedId = 321;
this.arrayList.forEach((element, indexval) => {
  if((element.index== selectedId){
    this.arrayList[indexval].total = element.total*2
  } 
});

can this be optimized so that i need not iterate the list

Else Works Everytime, While If I Remove Else Block, Everything Works Perfect [closed]

So this is my code

stem = "/*smth*/"
for (var i = stem.length - 1; i >= 0; i--) {
    if (stem[i] == 'ա' && stem[i-1] == 'ե' && stem[i+1] != undefined) {
        var alternated = stem.slice(0, i) + stem.slice(i+1)
    } else if (stem[i] == 'ե' && stem[i+1] == 'ւ' && stem[i+2] != undefined) {
        var alternated = stem.slice(0, i) + "ի" + stem.slice(i+1)
    } else if (stem[i] == 'ո' && stem[i+1] == 'յ' && stem[i+2] != undefined) {
        var alternated = stem.slice(0, i+1) + "ւ" + stem.slice(i+2)
    } else if (stem[i] == 'ո' && stem[i+1] == 'ւ' && stem[i+2] != undefined) {
        var alternated = stem.slice(0, i) + stem.slice(i+2)
    } else if (stem[i] == 'ի' && stem[i+1] != undefined) {
        var alternated = stem.slice(0, i) + stem.slice(i+1)
    } else if (stem[i] == 'է' && stem[i+1] != undefined) {
        var alternated = stem.slice(0, i) + "ի" + stem.slice(i+1)
    } else {
        alternated = stem
    }
}
alert(alternated)

It must change the stem‘s value in some conditions and not to change in others and give the changed/not changed value to alternated. But it doesn’t work, never change the stem, else statement works everytime. If I delete else statement everything works great. I tried to write it with switch, it had the same problem, didn’t work with default: and worked great without…

console.logs in onClick handleSubmit do not print out

There is a login component in React 18.x front end to take input of username and password, and then send them to backend server for verification. If verified, then route to a path defined with react-route-dom. The browser is Chrome. Here is the login component:

export default function ELogin () {
    console.log("from Elogin11");  //<<==show up in Chrome's console 
    const [loginName, setLoginName] = useState('');
    const [password, setPassword] = useState('');
    const authVal = useContext(authContext);

    const handleSubmit = async (event) => { 
        console.log("from Elogin handleSubmit : ", event); //<<==NO show 
        let url = `${GLOBAL.BASE_URL}/logins?password=${encodeURIComponent(password)}&loginName=${encodeURIComponent(loginName)}`
        //let url = `${GLOBAL.BASE_URL}/express_backend`
        let obj = {
            username:loginName,
            password:password
        };
        try {
            let employee = await helper.fetchpost(url, obj); //<<==fetch show up on backend node/express server
            console.log("fire up from react browser", employee); //<<==NO show 
            authVal.setEmpUser(employee.results);             
            //redirect
            return <Navigate to="/employee" />;
        } catch(err) {
            console.log("Error in login", err);
        };
       
    };

    const handleLoginName = (event) => {
        setLoginName(event.target.value);
    };

    const handlePassword = (event) => {
        console.log("handle password : ", event.target);  //<<==show up in Chrome's console 
        setPassword(event.target.value);
    };
    console.log("before return Elogin");  //<<==show up in Chrome's console 
    return (
        <React.Fragment>
            <Row>
            <Col sm={true}></Col>
            <Col sm={true}>
                <Form onSubmit={() => {} }>
                    <h3 className="text-center" >Login Page</h3>

                    <div className="form-group">
                        
                        <input type="text" className="form-control"  placeholder="登录名" onChange={handleLoginName} />
                    </div>

                    <div className="form-group">
                        
                        <input type="password" className="form-control"  placeholder="密码" onChange={handlePassword} />
                    </div>

                    <Button onClick={()=>{console.log("button clicked") //<<==NO show; handleSubmit()}} type="submit" className="btn btn-primary btn-block" >Login</Button>
                
                </Form>
                </Col>
                <Col sm={true}></Col>
            </Row>
        </React.Fragment>
    );
}

However none of the console.log in handleSubmit gets printed in Chrome’s console, and Navigate seems not fired as well.

Reorder li in order for ultiple ul-list with javascripts

I want to re-order several ul-list on my web.
Each ul with the same class should be in numerical order after using javascript.

The list may look like below

 <ul class="filelist">
     <li data-sortby="3">3</li>
     <li data-sortby="2">2</li>
     <li data-sortby="1">1</li>
     <li data-sortby="4">4</li>
 </ul>
 <ul class="filelist">
     <li data-sortby="5">5</li>
     <li data-sortby="2">2</li>
     <li data-sortby="1">1</li>
     <li data-sortby="4">4</li>
 </ul>

I want them show in order like

 <ul class="filelist">
     <li data-sortby="1">1</li>
     <li data-sortby="2">2</li>
     <li data-sortby="3">3</li>
     <li data-sortby="4">4</li>
 </ul>
 <ul class="filelist">
     <li data-sortby="1">1</li>
     <li data-sortby="2">2</li>
     <li data-sortby="4">4</li>
     <li data-sortby="5">5</li>
 </ul>

I tried the code down below

$(document).ready(function() {
   var ul = $('ul.filelist');
   for (let u = 0; u < ul.length; u++) {
       const element = ul[u];

       li = element.querySelectorAll('li');

                    
       li.detach().sort(function(a,b) {
       return $(a).data('sortby') - $(b).data('sortby');  
       });
                    
      u.append(li);
                }

     });

But the error indicated that li.detach is not a function.
Could someone help me solve this problem?
Thanks!