Access to mobx-state-tree-action not from a FC component

I am learning to use Mob-x-state tree in my pet project. And i have one problem:

I need to handle websocket events with my store like this:

const {
  AccountsStore
} = useStore();
blablalbalba
  socket.onopen = function () {
    AccountsStore.handleWsStart();
  };

I am trying to use AccountsStore.handleWsStart(); from my store:

.actions(self => ({
    // note the `({`, we are returning an object literal
    handleWsStart() {
      self.isFetching = true;
    }

And have this issure:
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons

I understand what i am doing wrong, cant you tell me how i can access to mobx-state-tree-action not from a FC component or antother way to handle WS events to store?

close bootstrap 5 modal before send ajax

I want to close the bootstrap 5 modal before sending ajax. For this, I used the following code, but Ajax runs first then the medal is closed.

jQuery.ajax({
        async: false,
        beforestart: function () {
            $("#freeModal").modal('hide');
        },
        url: '/url',
        })

And I don’t want to use the following codes:

$("#myModal").modal('hide')
$("#myModal").on('hidden.bs.modal', function(){
        jQuery.ajax({
            async: false,
            url: '/url',
            })
  });

Is there a way to close the medal first and then send Ajax?

Storing a variable for later use in a Cypress test without affecting the current chainable element

We’re testing the forgotten password email flow for our application. It goes something like this:

.getLastEmailHtml()
.then((html) => {
  cy.document().invoke('write', html)
})
.contains('Reset password') // <- this is a button/anchor
// Cypress doesn't support multiple tabs, so let's remove the target="_blank" on the link before clicking
.invoke('removeAttr', 'target')
.click()

/* do stuff on the new password page... */

Here we’re grabbing html of the email, writing it into a Cypress document and then clicking the link which takes us to a url with a token in the query for security. Once the new password has been set by the test, I’d like to check that the perviously visited url (the one containing the token) now shows that the token has expired after re-visiting it.

What’s the cleanest way I can store the original url for use in a visit later. I’d preferably want something where I didn’t have to break the current chainable, like:

.getLastEmailHtml()
.then((html) => {
  cy.document().invoke('write', html)
})
.contains('Reset password') // <- this is a button/anchor
// Cypress doesn't support multiple tabs, so let's remove the target="_blank" on the link before clicking
.invoke('removeAttr', 'target')
.invoke('attr', 'href').then(url => /* save the url for later use */)
.click()

/* do stuff on the new password page and then check token is expired... */

Of course the above breaks our chain and click() no longer works:

! CypressError

cy.click() failed because it requires a DOM element.

Why do my browser devtools suddenly show sources as flat view instead of tree view?

Up until about a week ago, in my browser devtools, my Javascript code looked like this: enter image description here

However, since a few days, it looks like a flat view:
enter image description here

More information which may be relevant:

  • It happens in all up-to-date local browsers that I have, so in Chrome, Edge, and Firefox;
  • This only happens with projects that I (re)build now. If I use (locally) build sources that are more than a week old, the sources look correct (so as a tree);
  • I tried going back one version with Node (and the linked NPM), but that did not make any difference;
  • I use an up-to-date Windows 11, and the latest VSCode;

What could be causing the different sources view? And how can I get the tree view back?

Storing a value and a key in a JavaScript object while looping

In the function below it takes a sentence as an argument and counts the total occurrence of letters and return them as an object. The letter being the key and total number of occurrence as the value. We are starting off with an empty object. I am getting confused how the object get populated as it started empty. My confusions are commented in the code.

const wordCounter = (sentence)=>{
  let words = {}
  //words object is empty here
  for(letter of sentence){
    //Words object is still empty here right?
    if(letter in words){
      //How did the letters automatically gets stored in the words object when they were previously empty on line 3 without calling any sort of function to do the storing?
      
      words[letter]++
    }else{
      words[letter] = 1
    }
  }
  return words
}
console.log(wordCounter('Help me with this I am confused'))
/*Output: { 
 :  6
 H: 1
 I: 1
 a: 1
 c: 1
 d: 1
 e: 3
 f: 1
 h: 2
 i: 2
 l: 1
 m: 2
 n: 1
 o: 1
 p: 1
 s: 2
 t: 2
 u: 1
 w: 1}
 */

Why have cors error when cors is disabled in server?

I have a backend application in spring where the cors configuration is as follows:

 @Bean
    public SecurityFilterChain filterChain(HttpSecurity http, HandlerMappingIntrospector introspector) throws Exception {
        MvcRequestMatcher.Builder mvc = new MvcRequestMatcher.Builder(introspector);
        return http
                .cors(cors -> cors.configurationSource(corsConfiguration()))
                .csrf(AbstractHttpConfigurer::disable)
                .headers(configurer -> configurer.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
                .sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
                .authorizeHttpRequests(request -> request
                        .requestMatchers(mvc.pattern("/admin/**")).hasAuthority("ADMIN")
                        .requestMatchers(mvc.pattern("/cart/**"), mvc.pattern("/user/**"),
                                mvc.pattern("/order/**"), mvc.pattern("/orders/**"),
                                mvc.pattern("/order-product/**"), mvc.pattern("/favorite-product/**"))
                        .authenticated()
                        .anyRequest().permitAll())
                .build();
    }
    @Bean
    UrlBasedCorsConfigurationSource corsConfiguration() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowedOriginPatterns(List.of("*"));
        corsConfiguration.setAllowedHeaders(List.of("*"));
        corsConfiguration.setAllowedMethods(List.of("*"));
        corsConfiguration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
        return urlBasedCorsConfigurationSource;
    }

The backend and frontend application is run as follows in docker:

shoponlineback:
    image: shoponlineback:latest
    container_name: shoponlineback
    ports:
      - "8080:8080"
    networks:
      - shoponlinenetwork
    environment:
      SPRING_DATASOURCE_URL: jdbc:mysql://mysqldatabase:3306/shoponline?useUnicode=true&characterEncoding=UTF-8

      SERVER_ADDRESS: 0.0.0.0
      SERVER_PORT: 8080
    depends_on:
      mysqldatabase:
        condition: service_healthy
  shoponlinefront:
    image: shoponlinefront
    container_name: shoponlinefront 
    networks:
      - shoponlinenetwork
    ports:
      - "80:3000"
    environment:
      REACT_APP_SERVER_URL: http://146.59.93.226:8080
      WDS_SOCKET_PORT: 0
    depends_on:
      - "shoponlineback"
volumes:
  mysql-data:
networks:
  shoponlinenetwork:
    driver: bridge

Host ip addres is 146.59.93.226.
Its wierd because cors allows all origins. On my local machine all works, but on docker host not .
Have you ideas how resolve it? :/

Its wierd because cors allows all origins. On my local machine all works, but on docker host not .
Have you ideas how resolve it? :/

useState variable not updating

I’m having issue in understanding the behavior of React useState hook. Please have a look at my code first.

import { useEffect, useState } from "react";

function UseEffectHook() {
  const [count, setCount] = useState(0)

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setCount(count++)}>Increment</button>
      <button onClick={() => setCount(++count)}>Increment</button>
      <button onClick={() => setCount(count+1)}>Increment</button>
      <button onClick={() => setCount(prevCount => prevCount - 1)}>Decrement</button>
    </div>
  )
}

export default UseEffectHook

I’m wondering why the first and second buttons aren’t working.
Here, is the link to codesandbox example: https://codesandbox.io/p/sandbox/useeffect-1-2pzgzw?file=%2Fsrc%2FUseEffectHook.js%3A1%2C9

Note: It’d be appreciated if someone could explain this concept in details.

Checkmarx vulnerability – if embeds untrusted data

I have this code:

                _addIconForDropDownMenu : function() {
                    if (this.getConfig('tabDropdownMenu')) {
                        $(this.$root.find('span.ossui_dropdown_icon'))
                                .closest("li").remove();
                        $(this.menuIconTemplate)
                                .insertAfter(
                                        this.$root
                                                .find(
                                                        ".ossui-pagetabs-nav-bar .ossui-addtab-icon")
                                                .closest('li'));
                        this._createDropdownMenuOnOverflow();
                    }
                },

and i get this checkmarx issue:

The method if embeds untrusted data in generated output with $, at line 4567 of ui.js. This untrusted data is embedded into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the generated web-page. Similarity ID: -2086290339

I didn’t understand what this checkmarx mean and how to solve it.
I tried to use GPT and he changed my method to be like this:

_addIconForDropDownMenu: function() {
    if (this.getConfig('tabDropdownMenu')) {
        // Sanitize or encode the untrusted data before using it with jQuery
        var untrustedData = ''; // Replace this with the source of untrusted data

        // Example of sanitization (assuming untrustedData is a string)
        var sanitizedData = sanitizeFunction(untrustedData);

        // Example of encoding (assuming untrustedData is a string)
        var encodedData = encodeHTML(untrustedData);

        // Example usage with jQuery ($)
        $(sanitizedData).closest("li").remove();
        $(encodedData).insertAfter(
            this.$root.find(".ossui-pagetabs-nav-bar .ossui-addtab-icon").closest('li')
        );

        this._createDropdownMenuOnOverflow();
    }
},

// Example function to sanitize data (sanitizeFunction)
function sanitizeFunction(data) {
    // Implement your sanitization logic here
    // Return sanitized data
}

// Example function to encode HTML entities (encodeHTML)
function encodeHTML(str) {
    return str.replace(/[&<>"']/g, function(match) {
        return {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        }[match];
    });
}

and still i don’t understand what is this checkmarx, where can be injection? and the GPT solution.

Tnx

.chain method won’t work after array mutation with .splice and .slice methods

When I connect an array of Tone.js effects to UserMedia (basically any audio source) and then use .splice and .slice methods on this array that move element of an array from one index to another, effects doesn’t work anymore, and it just connects clean sound to the Destination node.

Here is example of this code:

let mic = new Tone.UserMedia();
let t = [new Tone.Distortion(1).toDestination(), new Tone.FeedbackDelay(0.6).toDestination()];
mic.disconnect().chain(...tt).toDestination();
function moved(array, from, to, on = 1) {
  return array = array.slice(), array.splice(to, 0, ...array.splice(from, on)), array
}
//this can be written as mic.disconnect().chain(...moved(t,0,1), Tone.Destination), but this way it just disconnects all nodes because .chain method doesn't work properly here.
mic.disconnect().chain(...moved(t,0,1)).toDestination();

Though it doesn’t work with splice and slice simultaneously, it works when these methods are used separately but not together on one array. Other methods like push and pop, however, work fine.

  1. Is this .chain method issue, or am I doing something wrong?
  2. Why doesn’t this happen with pop and push, even though they are mutating array too?

Chosen select is not applied when I add rows based on user input

`<script>
'use strict';
$(document).ready(function() {
    $(".chzn-select").chosen();

    $('#example-4').on('click', '.ui-data-table-delete', function() {
        var rowIndex = $(this).closest('tr').index();
        delete_row(rowIndex);
    });

// Delegate the input event to the table body
$('#example-4').on('input', 'tr:last input', function() {
    // Check if all fields in the last row are filled
    var isRowFilled = true;
    $(this).closest('tr').find('input').each(function() {

        if ($(this).val() === '') {
            isRowFilled = false;

            return false; // Exit the loop early if any field is empty
        }
    });

    // If all fields are filled, trigger the add_row function
    if (isRowFilled) {

        add_row();
    }
});


   
});

function add_row() {

    var table = document.getElementById("example-4");
    var t1 = table.rows.length;

    var row = table.insertRow(-1);

    var cell1 = row.insertCell(0);
    cell1.textContent = t1;

    var cell2 = row.insertCell(1);
    var cell3 = row.insertCell(2);
    var cell4 = row.insertCell(3);
    var cell5 = row.insertCell(4);

    cell4.className = 'abc';
    cell3.className = 'abc';
    // chzn-select

    var select = $('<select class="chzn-select" style="width:200px" name="item[' + t1 + ']"></select>');
    <?php foreach ($item_data as $value):?>
    select.append('<option value="<?= $value->PKItemID; ?>"><?= $value->ItemName; ?></option>');
    <?php endforeach;?>
    select.appendTo(cell2);
    select.chosen();

    $('<input class="tabledit-input form-control input-sm" type="number" min="1" name="qty['+t1+']">').appendTo(cell3);
    $('<input class="tabledit-input form-control input-sm" type="text" name="manufactureID['+t1+']">').appendTo(cell4);
    $('<a href="#" class="btn btn-sm btn-danger ui-data-table-delete"><i class="feather icon-trash"></i></a>').appendTo(cell5);
 
}

function delete_row(rowIndex) {
    var table = document.getElementById("example-4");
    if (rowIndex >= 0 && rowIndex < table.rows.length) {
        table.deleteRow(rowIndex);
        // (rowIndex < table.rows.length) , Yeah well this ensures that 
        // the header row is not deleted.
        // Adjust index numbers after deleting row
        for (var i = rowIndex; i < table.rows.length; i++) {
            console.log(i);
            table.rows[i].cells[0].textContent = i; 
            // The hidden index is maintained well by the in 
            // built deleteRow function.
            // We are just making the visible index and the hidden 
            // the same.
        }
    } else {
        console.error('Invalid row index:', rowIndex);
    }


}
</script>

The chosen select is fine when I don’t include the add row functionality based on whether the last row is filled or not. But when I include it chosen is not working. The other thing I noticed that sometimes chosen is applied but then add row based on user input doesn’t work. I do have a separate add_row button to add rows.

I tried using select2 library but it is messing with the css of the template.

How to dispatch event in threejs using typescript

I just started using Typescript and ran into a problem when working with EventEmitter from the ThreeJS library.

When I try to dispatch an event:

const event: THREE.EventDispatcher = new THREE.EventDispatcher();
event.addEventListener('test', () => console.log(1));
event.dispatchEvent({ type: 'test' }); // <-- error

Image

I get an error:

TS2345: Argument of type '{ type: string; }' is not assignable to parameter of type 'never'.

Image

But it works if I do it like this:

const event: THREE.EventDispatcher = new THREE.EventDispatcher();
event.addEventListener('test', () => console.log(1));
event.dispatchEvent<any>({ type: 'test' }); // <-- ignored error by any

Image

But it seems to me that this is a bad solution, could you show me how to do it correctly with explanations

undefined in const in console

hello

I have a problem with console says undefined. here is picture. I expect these parameters show value true but as you see just number and uppercase are true.
[enter image description here] (https://i.stack.imgur.com/QZAGL.png)

Then I tried debugging but it still doesn't` change. and I can`t realize where the problem is. but I     guess     it is related to the arrays and for condition. I wish you help me. here are all pictures of my     project.
[enter image description here] (https://i.stack.imgur.com/7dk8h.png)
[enter image description here] (https://i.stack.imgur.com/I3CVT.png)
[enter image description here] (https://i.stack.imgur.com/ag2F1.png)

I want to use GAS to determine if nothing is entered in a cell, but I don’t know how to handle `0`

I would like to implement a function that allows characters and numbers to be entered into a spreadsheet, and if nothing is entered using GAS, a message box will be displayed.
Therefore, I would like to use the following function to determine whether information has been entered in the cell. However, if the number 0 is entered in the cell, the number 0 will be determined as an empty character. As a result, it is determined that nothing has been entered even though 0 has been entered.

function isEmpty(value) {
  return value == null;
}

I would like to return false when the number 0 is input, but how can I do that?

By the way, when I asked ChatGPT, they presented the following code, but with this code, even if a number is entered in the cell, it is determined that it is not, and true is returned.

function isEmpty(value) {
  return value === null || 
         typeof value === 'undefined' || 
         (typeof value === 'string' && value.trim() === '') ||
         (typeof value === 'number' && value !== 0);
}