How to prevent JQuery Datepicker from changing the current month when minDate is set?

I have an inline JQuery datepicker with 2 months, when selecting a Date that date is set as the minDate, I have code to select more dates but the month changes.

If I select 12 of February:

enter image description here

The calendar will move a month, to show February and March:

enter image description here

I understand that since the minDate is 12 of February, there is no reason to show January, but if I want to select February 12 then February 14 and so on, the month changes and the user has to go to the left. The idea of setting the minDate is that the subsequent dates after the first one are always greater than the first one.

Thinking about it, I will just have to use beforeShowDay and create my own minDate logic (feels overkill thought).

Here is a reproducible example

Firestore return 2 collection event instead the one specified in the OnDocumentCreated function

I have a structure with 2 collections course and partial_ingredients.
I deployed the function that when a new document is created in the course collection, it will take the partial information and do some updates in a thrid collection aggregate_ingredient.
The problem is that when the function is triggered by a new course created, it receive the events also the creation of the partials…. I specified in the function the path course/{courseID}, but is seems not working. Can someone can help me? Seems I need to filter out only the course creations events…

Here my code:

exports.createAggrIngr = onDocumentCreated("course/{courseID}",async  (event) => {
  // Save the data after the update/creation courseid
  const v_courseid=event.params.courseID;
  console.log("v_courseid created: "+v_courseid);

  return; 
});

Why does Roblox’s Quick Login API return a 403 error when checking login status?

When I scan the qr from the quick-login code, and successfuly login, then send a post to the status endpoint, the response reflects that I’m not logged in.

code:

// sending post to create endpoint to generate qr code and login code
app.post('/login/create', async (req, res) => {
    console.log('Creating login session...');
    try {
        const response = await axios.post('https://apis.roblox.com/auth-token-service/v1/login/create', {}, {
            headers: {
                'accept': 'application/json, text/plain, */*',
                'accept-language': 'en-US,en;q=0.9',
                'cookie': req.headers.cookie,
                'x-csrf-token': req.headers['x-csrf-token'],
            }
        });

        const { code, imagePath, privateKey } = response.data;
        const qrCodeUrl = `https://apis.roblox.com/auth-token-service${imagePath}`;

        console.log('Login session created successfully:', { code, qrCodeUrl, privateKey });
        res.json({ code, qrCodeUrl, privateKey });
    } catch (error) {
        console.error('Error creating login session:', error.message);
        res.status(500).json({ error: error.message });
    }
});
//login status once I scan the qr code and approve the login
app.post('/login/status', async (req, res) => {
    const { code, privateKey } = req.body;
    console.log('Checking login status for code:', code);
    try {
        const response = await axios.post('https://apis.roblox.com/auth-token-service/v1/login/status', {
            code,
            privateKey
        }, {
            headers: {
                'accept': 'application/json, text/plain, */*',
                'accept-language': 'en-US,en;q=0.9',
                'content-type': 'application/json;charset=UTF-8',
                'x-csrf-token': req.headers['x-csrf-token'],
            }
        });
        console.log('Login status response:', response.data);
        res.json(response.data);
    } catch (error) {
        console.error('Error checking login status:', error.message);
        res.status(500).json({ error: error.message });
    }
});

But it still returns:

Checking login status for code: B8VHPW
Error checking login status: Request failed with status code 403

What am I missing?

How to bypass browser popup blocker for opening in a new tab [duplicate]

I have a script which uses AJAX to receive PDF contents and open it in a new browser tab without downloading it. However, if I attempt to simulate a mouse click event to open it in new tab, it will always be blocked by popup blocker:

var filename = "My PDF File.pdf";
var type = 'application/pdf';
var blob =  new File([response.data], filename, { type: type });
var exportUrl = URL.createObjectURL(blob);
var a = document.createElement("a");
a.setAttribute('target', '_blank');
a.href = exportUrl;
document.body.appendChild(a);
a.click();

I tried many different ways to simulate the mouse click events, such as creating a new MouseEvent object and dispatch it, and it did not work either. Does anyone know how I can bypass the popup blocker for this use case?

How do I efficiently useContext() so that it doesn’t re-render/re-fetch when user navigates pages?

I am creating a React project where I need an efficient way to fetch profile information when my site is initially loaded or refreshed (NOT when the user navigates via react-router-dom routes).

I decided to use a global context to store the Profile object. However, it re-renders and therefore re-fetches data whenever you navigate to a new page on the site. So, it defeats the purpose of the global context since it re-fetches every time anyways.

Here is my context file:


import { createContext, ReactNode, useState, useContext, useEffect } from "react";
import { Profile } from "../../types/profile";
import getProfile from "../services/getProfile";
import getUserSession from "../services/getUserSession";

interface MyProfileContextType {
  profile: Profile | null;
  fetchMyProfile: (id: string) => Promise<void>;
  loading: boolean;
}

const MyProfileContext = createContext<MyProfileContextType | undefined>(undefined);

export const MyProfileProvider = ({ children }: { children: ReactNode }) => {
  const [profile, setProfile] = useState<Profile | null>(null);
  const [loading, setLoading] = useState<boolean>(false);

  const fetchMyProfile = async (id: string): Promise<void> => {
    if (profile) {
        return;
    }

    setLoading(true);

    try {
      const response = await getProfile(id);

      if (response.error) {
        throw new Error("Could not fetch MyProfile");
      }

      setProfile(response.profile);
    } catch (error: any) {
      console.error(error.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {

    const fetchSessionAndProfile = async () => {
      const sessionResponse = await getUserSession();
  
      if(sessionResponse && sessionResponse.session && sessionResponse.session.user && sessionResponse.session.user.id){
        const id = sessionResponse.session.user.id;
        fetchMyProfile(id);
      }
    }

    if(!profile){
      fetchSessionAndProfile();
    } else {
      setLoading(false);
    }
  }, [profile]);

  return (
    <MyProfileContext.Provider value={{ profile, fetchMyProfile, loading }}>
      {children}
    </MyProfileContext.Provider>
  );
};

export const useMyProfile = () => {
  const context = useContext(MyProfileContext);
  if (!context) {
    throw new Error("useMyProfile must be used within a MyProfileProvider");
  }
  return context;
};

I wrap this around my Router:

function App() {
  return (
    <MyProfileProvider>
      <Router>
        <LoadingProvider>
            <Layout>
              {
                ({ hideNav, showNav }) => (
                  <Routes>
                    <Route path="/" element={<HomePage />} />
                    <Route path="/sign_up" element={<SignUpPage />} />
                    <Route path="/log_in" element={<LogInPage />} />
                    <Route path="/my_stories" element={<MyStoriesPage />} />
                    <Route path="/stories/:id" element={<Story hideNav = {hideNav} showNav = {showNav} />}></Route>
                    <Route path="/success_screen" element={<SuccessPage/>}></Route>
                    <Route path="/my_profile" element = {<MyProfilePage/>}></Route>
                    <Route path="/profile" element = {<ProfilePage/>}></Route>
                  </Routes>
                )
              }
            </Layout>
        </LoadingProvider>
      </Router>
    </MyProfileProvider>
  );
} 

Note: I want to fetch the data to be used on any page because I use profile data in various locations and not just the profile page.

CSP issue on cold load with chrome and Edge but works on refresh. Firefox also always works fine

My Context:

I’m working on a static page served by AWS CloudFront and stored in S3. The page is basic html, css, and js. No frameworks. CSP is implemented with hashes since using nonces is not possible on my static site.

My Problem:

The page loads without issue on Firefox. On Chrome and Edge, I get a CSP error on a umd library inlined by vite (<script inline-source type="application/javascript" src="./js/PageConfiguration.umd.js"></script>) during my build using vite-plugin-inline-source but it loads normally if I refresh.
The Error: Refused to execute inline script because it violates the following Content Security Policy directive:

My Investigation:

The site is static and I double checked with a diff tool to verify the code is identical on the initial load with the csp error and the subsequent loads that work.

The csp header is also identical.

Next Steps?

Given the above, I don’t even know how to proceed. Is this a bug with the chromium engine? Is there a way that I could get a legitimate CSP error even though the correct hash is included in the header? Why would it fail on the initial load (or when the cache is disabled) but not on subsequent loads? Why does it always work on Firefox? It seems like either Firefox is failing to identify a CSP risk, or (more likely in my estimation) Chrome is generating a false positive.

I’m currently experimenting with different configurations to see if I can eliminate the issue but have had no luck.

I would love to understand what is going on here.

The ID token does not contain a tenant identifier

I have that error in an application that uses firebase in which I am trying to log in. Users are now ready

I put the code, of the front with js and of the back with Laravel

JS:

signinUserInFirebase: function () {
    var _signinUserInFirebase = _asyncToGenerator(
    /*#__PURE__*/
    _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee3(context, payload) {
      var email, password;
      return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee3$(_context3) {
        while (1) {
          switch (_context3.prev = _context3.next) {
            case 0:
              email = payload.email, password = payload.password;
              context.commit('loginUser');
              console.log(payload);
              _context3.next = 5;
              return firebase_app__WEBPACK_IMPORTED_MODULE_1__["default"].auth().signInWithEmailAndPassword(email, password).then(function (response) {
                nprogress__WEBPACK_IMPORTED_MODULE_2___default.a.done();
                firebase_app__WEBPACK_IMPORTED_MODULE_1__["default"].auth().currentUser.getIdToken(
                /* forceRefresh */
                true).then(function (idToken) {
                  var tok = {
                    Firebasetoken: idToken
                  };
                  console.log(idToken);
                  WebServices__WEBPACK_IMPORTED_MODULE_3__["default"].post('/auth/firebaselogin', tok, axiosOptions).then(
                  /*#__PURE__*/
                  function () {
                    var _ref = _asyncToGenerator(
                    /*#__PURE__*/
                    _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.mark(function _callee2(r) {
                      var createUser, update;
                      return _babel_runtime_regenerator__WEBPACK_IMPORTED_MODULE_0___default.a.wrap(function _callee2$(_context2) {
                        while (1) {
                          switch (_context2.prev = _context2.next) {
                            case 0:
                              // await this.updatePhotoProfile(response);
                              createUser = window.db;
                              update = createUser.collection('Users').doc(response.user.uid); // Set the "capital" field of the city 'DC'

                              console.log('updateando foto');

                              if (!(response.user.photoURL != r.data.user.photo)) {
                                _context2.next = 7;
                                break;
                              }

                              if (!(response.user.photoURL != r.data.user.photoUrl)) {
                                _context2.next = 7;
                                break;
                              }

                              _context2.next = 7;
                              return update.update({
                                photo: response.user.photoURL,
                                photoUrl: response.user.photoURL
                              }).then(function () {
                                console.log("Document successfully updated!");
                              })["catch"](function (error) {
                                // The document probably doesn't exist.
                                console.error("Error updating document: ", error);
                              });

                            case 7:
                              r.data.user.photo = response.user.photoURL;
                              r.data.user.photoUrl = response.user.photoURL;
                              localStorage.setItem('roles', JSON.stringify([r.data.user.role]));
                              localStorage.setItem('userInfo', JSON.stringify(r.data.user));
                              context.commit('loginUserSuccess', response);

                            case 12:
                            case "end":
                              return _context2.stop();
                          }
                        }
                      }, _callee2);
                    }));

                    return function (_x5) {
                      return _ref.apply(this, arguments);
                    };
                  }())["catch"](function (error) {
                  console.log(tok);
                    nprogress__WEBPACK_IMPORTED_MODULE_2___default.a.done();
                    context.commit('loginUserFailure', error.response.data); // console.log('signInWithLaravelPassport ERROR', error.response);

                    reject(error.response);
                  });
                })["catch"](function (error) {
                  console.log(error);
                });
              })["catch"](function (error) {
                context.commit('loginUserFailure', error);
              });

            case 5:
              return _context3.abrupt("return", _context3.sent);

            case 6:
            case "end":
              return _context3.stop();
          }
        }
      }, _callee3);
    }));

Honestly, the difficulty of the code eats me up a bit, but I understand that the request is made here by sending the token:

 var tok = {
                    Firebasetoken: idToken
                  };
                  console.log(idToken);
                  WebServices__WEBPACK_IMPORTED_MODULE_3__["default"].post('/auth/firebaselogin', tok, axiosOptions).then(

And there is the token that is sent, which comes from there without the tenant ID.

Controller in Laravel:

public function firebaselogin(Request $request)
    {
        // Launch Firebase Auth
        $auth = app('firebase.auth');

        $idTokenString = $request->input('Firebasetoken');


        try { // Try to verify the Firebase credential token with Google

            $verifiedIdToken = $auth->verifyIdToken($idTokenString);


        } catch (InvalidArgumentException $e) { // If the token has the wrong format

            Log::info($e->getMessage());
            
            return response()->json([
                'message' => 'Unauthorized - Can't parse the token: ' . $e->getMessage()
            ], 401);

        } catch (InvalidToken $e) { // If the token is invalid (expired ...)

            return response()->json([
                'message' => 'Unauthorized - Token is invalide: ' . $e->getMessage()
            ], 401);

        }

        // Retrieve the UID (User ID) from the verified Firebase credential's token
        $uid = $verifiedIdToken->getClaim('sub');

        // Retrieve the user model linked with the Firebase UID
        // $user = User::where('firebaseUID',$uid)->first();
        // $user = $this->database->collection('Users')->where('uid', '==' ,$uid)->limit(1)->documents();


        $array = [];
        $doc = $this->database->collection('Users')->document($uid);
        $snapshot = $doc->snapshot();
        if (!$snapshot->exists()) {
            return response()->json(['status' => 'Not Found', 'color' => 'warning', 'message' => 'la cita que desea editar no ha sido encontrado..']);
        }else{
            $d = $snapshot->data();
            $array = $d;
        }

        // foreach ($user as $document) {
        //     if ($document->exists()) {
        //         $d = $document->data();
        //         $array = $d;
        //     } else {
        //     }
        // }
        // Return a JSON object containing the token datas
        // You may format this object to suit your needs
        return response()->json([
            'uid' => $uid,
            'user' => $array,
            'access_token' => $idTokenString,
        ]);
    }

The error occurs here:

catch (InvalidArgumentException $e) { // If the token has the wrong format

            Log::info($e->getMessage());
            
            return response()->json([
                'message' => 'Unauthorized - Can't parse the token: ' . $e->getMessage()
            ], 401);

        } 

What could be happening if the idTokent comes without the Tenant Id from the front, I would imagine that the problem is in the Firebase configuration. But, I don’t know.

How to put the tenant id in the token?

NodeJS + Web3JS – Eip838ExecutionError code: -32000 message – undefined

I am tired of contant getting error below.

Each time I am truing to call a method from a NodeJS app that works on Debian 11, it causes it. I can call this method directly from REMIX and from the frontend with metamask. Please help | hints.PS I tried with HTTP and WSS provider, I can do a curl to INFURA project co I am not blocked. PM2 shows no issues with NodeJS app. except mentioned issue while call. I also tried to create COntract with and without options { from, gas }

    Error call ethAuthorizeAccount: ContractExecutionError: Error happened while trying to execute a function inside a smart contract,
    {
  cause: [Eip838ExecutionError: execution reverted] {
    cause: undefined,
    code: -32000,
    receipt: undefined,
    data: undefined
  },
  code: 310,
  receipt: undefined
}

NodeJS impl:

require('dotenv').config();
const { Web3 } = require('web3');
const contractUtilsABI = require("./abi/latenight-utils_v2-1-0-abi.json");
const apiResponse = require("../helpers/apiResponse");

// Setup Web3
// const web3 = new Web3(new Web3.providers.HttpProvider(process.env.ETH_NODE_INFURA));
const web3WssProvider = new Web3.providers.WebsocketProvider(process.env.ETH_NODE_WSS_INFURA);
const web3 = new Web3(web3WssProvider);
const contractAddressUtils = process.env.CONTRACT_ADDRESS_UTILS;
const key = process.env.ETH_PRIVKEY;
const account = web3.eth.accounts.privateKeyToAccount(key);
const contractUtils = createContract(contractAddressUtils, contractUtilsABI);
contractUtils.defaultHardfork = 'shanghai';

function createContract(_contractAddr, _abi) {
    if (web3.utils.isAddress(_contractAddr) && Array.isArray(_abi)) {
        // const myContract = new web3.eth.Contract(abi, contractAddress);
        console.log('valid contract and abi');
        
        const contract = new web3.eth.Contract(_abi, _contractAddr, {from:account.address, gas: 3000000});
        return contract;
    } else {
        console.error('Invalid contract address or ABI');
    }
}

exports.ethAuthorizeAccount = [
    async (req, res) => {
        const params = req.body;
        try {
            web3.eth.accounts.wallet.add(account);
            const accounts = web3.eth.accounts.wallet;

            if (!accounts.length) { return console.log('no accounts found!'); }

            const address = web3.eth.accounts.wallet[0].address;

            if (web3.utils.isAddress(address)) {
                // The address is valid
                const checksumAddress = web3.utils.toChecksumAddress(address);

                if (address === checksumAddress) {
                    console.log('The address is checksummed correctly');

                    const result = await contractUtils.methods.generateRandomBytes32().call().then(console.log);
                    const block = await web3.eth.getBlockNumber();
                    console.log(`Latest block: ${block}`);

                    console.log('nCALL result: ', result);
                } else {
                    console.error('The address is not checksummed correctly');
                }
            } else {
                console.error('Invalid address');
            }
        } catch (error) {
            console.error(`Error call ethAuthorizeAccount:`, error);
            apiResponse.ErrorResponse(res, error);
        }
    }
]

Soidity Call:

function generateRandomBytes32() external view returns (bytes32) {
// require(_seedNodeCli == seedNodeCli, "access denied");
// Combine block-related data with the sender's address and current timestamp
return keccak256(
    abi.encodePacked(
        block.timestamp,  // Current block timestamp
        block.number,     // Block number
        block.prevrandao, // Block prevrandao (pseudo-randomness)
        msg.sender        // Sender address
        )
    );
}

How to check if a radio button is selected or not?

I use cypress and typescript/javascript for testing web pages. I want to check if a radio button is selected or not. How do I do that?

I found a similar question (see link below), but it checks if a radio button is clickable or not. It does not check if the radio button is selected or not.

How to check the radio button is clickable or not in cypress

Here is what I am trying to do. There is no property called state which has values like disabled or enabled.

  cy.get('[id=input1]')
  .invoke('attr', 'state') 
  .then((state) => { 
    if (state === 'disabled') { 
       console.log('disabled') 
    } 
    else { 
       console.log('enabled') 
    } 
  });

javascript method to extract permitted characters in a regex pattern?

I have a JSON with hundreds of postal regex that are conditionally applied based on a selected country, these are used to ensure the user is entering a correct postal code format for that country.

An example for USA is: "ValidationRegex" : "^[0-9]{5}([ -]{1}[0-9]{5})?$"

The above checks for : 12345 OR 12345 1234 OR 12345-1234

Is there any method or technique that I can use that would allow me to extract permitted characters from the regex? In the above, permitted characters would be ,-,0,1,2,3,4,5,6,7,8,9

It might be easy to just grab all characters inside of [], but not all regex are standardized like that. Some are like:

"ValidationRegex" : "^AD[0-9]{3}$"   // permitted: AD0-9
"ValidationRegex" : "^(BB)?[0-9]{5}$"   //permitted: B0-9
"ValidationRegex" : "^971[0-9]{2}$"   //permitted: 0-9

…and a few other variations.

Dynamic Components Not Rendering from the Database

I am trying to integrate dynamic components inside my Vue 3 blog articles stored in MongoDB to reduce the work of specifying image details every time. However, the image component is not being rendered. Below is the content data and the code I am using to parse and render the HTML content with dynamic components.

From this

`<a class='image' href='https://cdn.example.com/images/2024-03-09-00048/fit=contain,width=1280,sharpen=100' title='2024'><img  src='https://cdn.example.com/images/2024-03-09-00048/fit=contain,width=1280,sharpen=100' title='2024' alt='Photo alt'/></a>`

to this

`<ImageComponent _id='2024-03-09-00048' alt='Photo alt text' title='2024 ⋅ New York, US' flag='US'/></ImageComponent>"`

Article.vue:

  <section aria-labelledby="article-title" class="article-content">
      <dynamicContent :htmlContent="String(state.article.content)" />
    </section>

dynamic-content:

`<script setup>
import { onMounted, ref } from "vue";
import "https://cdn.jsdelivr.net/npm/lite-vimeo-embed/+esm";

const props = defineProps({
  htmlContent: {
    type: String,
    required: true,
  },
});

const content = ref(null);

onMounted(() => {
  if (content.value) {
    content.value.innerHTML = props.htmlContent;

    // Add 'reveal' class to all child elements
    const elements = content.value.querySelectorAll("*");
    elements.forEach((element) => {
      element.classList.add("reveal");
    });
  }
});
</script>

<template>
  <div ref="content"></div>
</template>
`

The dynamic components should be rendered correctly within the blog article content. Currently, the dynamic components are not rendered, and only the static HTML content is displayed.

Maybe this is not the right approach – inserting dynamic components directly inside the database but what would be the right approach to leverage from dynamic components and having some freedom around? An alternative more opinionated approach I thought about was to break the article down into smaller chunks of text and images that would be like a template.

My Sprite clones when he moves. How do you fix it?

I am trying to produce an 8-bit game that is an RPG and i have run into a problem.
Whenever my character moves, he produces clones of himself that multiply as he moves.

`e`num RadioMessage {
    message1 = 49434,
    start = 56380
}
sprites.onCreated(SpriteKind.Player, function (sprite) {
    controller.moveSprite(mySprite)
    characterAnimations.loopFrames(
    mySprite,`
    [img`
      ` . . . . . . f f f f . . . . . . 
        . . . . f f f 2 2 f f f . . . . 
        . . . f f f 2 2 2 2 f f f . . . 
        . . f f f e e e e e e f f f . . 
        . . f f e 2 2 2 2 2 2 e e f . . 
        . . f e 2 f f f f f f 2 e f . . 
        . . f f f f e e e e f f f f . . 
        . f f e f b f 4 4 f b f e f f . 
        . f e e 4 1 f d d f 1 4 e e f . 
        . . f e e d d d d d d e e f . . 
        . . . f e e 4 4 4 4 e e f . . . 
        . . e 4 f 2 2 2 2 2 2 f 4 e . . 
        . . 4 d f 2 2 2 2 2 2 f d 4 . . 
        . . 4 4 f 4 4 5 5 4 4 f 4 4 . . 
        . . . . . f f f f f f . . . . . 
        . . . . . f f . . f f . . . . . 
        `,img`
        . . . . . . . . . . . . . . . . 
        . . . . . . f f f f . . . . . . 
        . . . . f f f 2 2 f f f . . . . 
        . . . f f f 2 2 2 2 f f f . . . 
        . . f f f e e e e e e f f f . . 
        . . f f e 2 2 2 2 2 2 e e f . . 
        . f f e 2 f f f f f f 2 e f f . 
        . f f f f f e e e e f f f f f . 
        . . f e f b f 4 4 f b f e f . . 
        . . f e 4 1 f d d f 1 4 e f . . 
        . . . f e 4 d d d d 4 e f e . . 
        . . f e f 2 2 2 2 e d d 4 e . . 
        . . e 4 f 2 2 2 2 e d d e . . . 
        . . . . f 4 4 5 5 f e e . . . . 
        . . . . f f f f f f f . . . . . 
        . . . . f f f . . . . . . . . . 
        `,img`
        . . . . . . f f f f . . . . . . 
        . . . . f f f 2 2 f f f . . . . 
        . . . f f f 2 2 2 2 f f f . . . 
        . . f f f e e e e e e f f f . . 
        . . f f e 2 2 2 2 2 2 e e f . . 
        . . f e 2 f f f f f f 2 e f . . 
        . . f f f f e e e e f f f f . . 
        . f f e f b f 4 4 f b f e f f . 
        . f e e 4 1 f d d f 1 4 e e f . 
        . . f e e d d d d d d e e f . . 
        . . . f e e 4 4 4 4 e e f . . . 
        . . e 4 f 2 2 2 2 2 2 f 4 e . . 
        . . 4 d f 2 2 2 2 2 2 f d 4 . . 
        . . 4 4 f 4 4 5 5 4 4 f 4 4 . . 
        . . . . . f f f f f f . . . . . 
        . . . . . f f . . f f . . . . . 
        `,img`
        . . . . . . . . . . . . . . . . 
        . . . . . . f f f f . . . . . . 
        . . . . f f f 2 2 f f f . . . . 
        . . . f f f 2 2 2 2 f f f . . . 
        . . f f f e e e e e e f f f . . 
        . . f e e 2 2 2 2 2 2 e f f . . 
        . f f e 2 f f f f f f 2 e f f . 
        . f f f f f e e e e f f f f f . 
        . . f e f b f 4 4 f b f e f . . 
        . . f e 4 1 f d d f 1 4 e f . . 
        . . e f e 4 d d d d 4 e f . . . 
        . . e 4 d d e 2 2 2 2 f e f . . 
        . . . e d d e 2 2 2 2 f 4 e . . 
        . . . . e e f 5 5 4 4 f . . . . 
        . . . . . f f f f f f f . . . . 
        . . . . . . . . . f f f . . . . 
        `],
    2000,
    characterAnimations.rule(Predicate.MovingDown, Predicate.FacingDown)
    )
    characterAnimations.loopFrames(
    mySprite,
    [img`
        . . . . . . f f f f . . . . . . 
        . . . . f f e e e e f f . . . . 
        . . . f e e e f f e e e f . . . 
        . . f f f f f 2 2 f f f f f . . 
        . . f f e 2 e 2 2 e 2 e f f . . 
        . . f e 2 f 2 f f 2 f 2 e f . . 
        . . f f f 2 2 e e 2 2 f f f . . 
        . f f e f 2 f e e f 2 f e f f . 
        . f e e f f e e e e f e e e f . 
        . . f e e e e e e e e e e f . . 
        . . . f e e e e e e e e f . . . 
        . . e 4 f f f f f f f f 4 e . . 
        . . 4 d f 2 2 2 2 2 2 f d 4 . . 
        . . 4 4 f 4 4 4 4 4 4 f 4 4 . . 
        . . . . . f f f f f f . . . . . 
        . . . . . f f . . f f . . . . . 
        `,img`
        . . . . . . . . . . . . . . . . 
        . . . . . . f f f f . . . . . . 
        . . . . f f e e e e f f . . . . 
        . . . f e e e f f e e e f . . . 
        . . . f f f f 2 2 f f f f . . . 
        . . f f e 2 e 2 2 e 2 e f f . . 
        . . f e 2 f 2 f f f 2 f e f . . 
        . . f f f 2 f e e 2 2 f f f . . 
        . . f e 2 f f e e 2 f e e f . . 
        . f f e f f e e e f e e e f f . 
        . f f e e e e e e e e e e f f . 
        . . . f e e e e e e e e f . . . 
        . . . e f f f f f f f f 4 e . . 
        . . . 4 f 2 2 2 2 2 e d d 4 . . 
        . . . e f f f f f f e e 4 . . . 
        . . . . f f f . . . . . . . . . 
        `,img`
        . . . . . . f f f f . . . . . . 
        . . . . f f e e e e f f . . . . 
        . . . f e e e f f e e e f . . . 
        . . f f f f f 2 2 f f f f f . . 
        . . f f e 2 e 2 2 e 2 e f f . . 
        . . f e 2 f 2 f f 2 f 2 e f . . 
        . . f f f 2 2 e e 2 2 f f f . . 
        . f f e f 2 f e e f 2 f e f f . 
        . f e e f f e e e e f e e e f . 
        . . f e e e e e e e e e e f . . 
        . . . f e e e e e e e e f . . . 
        . . e 4 f f f f f f f f 4 e . . 
        . . 4 d f 2 2 2 2 2 2 f d 4 . . 
        . . 4 4 f 4 4 4 4 4 4 f 4 4 . . 
        . . . . . f f f f f f . . . . . 
        . . . . . f f . . f f . . . . . 
        `,img`
        . . . . . . . . . . . . . . . . 
        . . . . . . f f f f . . . . . . 
        . . . . f f e e e e f f . . . . 
        . . . f e e e f f e e e f . . . 
        . . . f f f f 2 2 f f f f . . . 
        . . f f e 2 e 2 2 e 2 e f f . . 
        . . f e f 2 f f f 2 f 2 e f . . 
        . . f f f 2 2 e e f 2 f f f . . 
        . . f e e f 2 e e f f 2 e f . . 
        . f f e e e f e e e f f e f f . 
        . f f e e e e e e e e e e f f . 
        . . . f e e e e e e e e f . . . 
        . . e 4 f f f f f f f f e . . . 
        . . 4 d d e 2 2 2 2 2 f 4 . . . 
        . . . 4 e e f f f f f f e . . . 
        . . . . . . . . . f f f . . . . 
        `],
    2000,
    characterAnimations.rule(Predicate.MovingUp)
    )
    characterAnimations.loopFrames(
    mySprite,
    [img`
        . . . . . . f f f f f f . . . . 
        . . . . f f e e e e f 2 f . . . 
        . . . f f e e e e f 2 2 2 f . . 
        . . . f e e e f f e e e e f . . 
        . . . f f f f e e 2 2 2 2 e f . 
        . . . f e 2 2 2 f f f f e 2 f . 
        . . f f f f f f f e e e f f f . 
        . . f f e 4 4 e b f 4 4 e e f . 
        . . f e e 4 d 4 1 f d d e f . . 
        . . . f e e e 4 d d d d f . . . 
        . . . . f f e e 4 4 4 e f . . . 
        . . . . . 4 d d e 2 2 2 f . . . 
        . . . . . e d d e 2 2 2 f . . . 
        . . . . . f e e f 4 5 5 f . . . 
        . . . . . . f f f f f f . . . . 
        . . . . . . . f f f . . . . . . 
        `,img`
        . . . . . . . . . . . . . . . . 
        . . . . . . f f f f f f . . . . 
        . . . . f f e e e e f 2 f . . . 
        . . . f f e e e e f 2 2 2 f . . 
        . . . f e e e f f e e e e f . . 
        . . . f f f f e e 2 2 2 2 e f . 
        . . . f e 2 2 2 f f f f e 2 f . 
        . . f f f f f f f e e e f f f . 
        . . f f e 4 4 e b f 4 4 e e f . 
        . . f e e 4 d 4 1 f d d e f . . 
        . . . f e e e e e d d d f . . . 
        . . . . . f 4 d d e 4 e f . . . 
        . . . . . f e d d e 2 2 f . . . 
        . . . . f f f e e f 5 5 f f . . 
        . . . . f f f f f f f f f f . . 
        . . . . . f f . . . f f f . . . 
        `,img`
        . . . . . . f f f f f f . . . . 
        . . . . f f e e e e f 2 f . . . 
        . . . f f e e e e f 2 2 2 f . . 
        . . . f e e e f f e e e e f . . 
        . . . f f f f e e 2 2 2 2 e f . 
        . . . f e 2 2 2 f f f f e 2 f . 
        . . f f f f f f f e e e f f f . 
        . . f f e 4 4 e b f 4 4 e e f . 
        . . f e e 4 d 4 1 f d d e f . . 
        . . . f e e e 4 d d d d f . . . 
        . . . . f f e e 4 4 4 e f . . . 
        . . . . . 4 d d e 2 2 2 f . . . 
        . . . . . e d d e 2 2 2 f . . . 
        . . . . . f e e f 4 5 5 f . . . 
        . . . . . . f f f f f f . . . . 
        . . . . . . . f f f . . . . . . 
        `,img`
        . . . . . . . . . . . . . . . . 
        . . . . . . f f f f f f . . . . 
        . . . . f f e e e e f 2 f . . . 
        . . . f f e e e e f 2 2 2 f . . 
        . . . f e e e f f e e e e f . . 
        . . . f f f f e e 2 2 2 2 e f . 
        . . . f e 2 2 2 f f f f e 2 f . 
        . . f f f f f f f e e e f f f . 
        . . f f e 4 4 e b f 4 4 e e f . 
        . . f e e 4 d 4 1 f d d e f . . 
        . . . f e e e 4 d d d d f . . . 
        . . . . 4 d d e 4 4 4 e f . . . 
        . . . . e d d e 2 2 2 2 f . . . 
        . . . . f e e f 4 4 5 5 f f . . 
        . . . . f f f f f f f f f f . . 
        . . . . . f f . . . f f f . . . 
        `],
    500,
    characterAnimations.rule(Predicate.MovingRight)
    )
    characterAnimations.loopFrames(
    mySprite,
    [img`
        . . . . f f f f f f . . . . . . 
        . . . f 2 f e e e e f f . . . . 
        . . f 2 2 2 f e e e e f f . . . 
        . . f e e e e f f e e e f . . . 
        . f e 2 2 2 2 e e f f f f . . . `
        . f 2 e f f f f 2 2 2 e f . . . 
       ` . f f f e e e f f f f f f f . . 
        . f e e 4 4 f b e 4 4 e f f . . 
        . . f e d d f 1 4 d 4 e e f . . 
        . . . f d d d d 4 e e e f . . . 
        . . . f e 4 4 4 e e f f . . . . 
        . . . f 2 2 2 e d d 4 . . . . . 
        . . . f 2 2 2 e d d e . . . . . 
        . . . f 5 5 4 f e e f . . . . . 
        . . . . f f f f f f . . . . . . 
        . . . . . . f f f . . . . . . . 
        `,img`
        . . . . . . . . . . . . . . . . 
        . . . . f f f f f f . . . . . . 
        . . . f 2 f e e e e f f . . . . 
        . . f 2 2 2 f e e e e f f . . . 
        . . f e e e e f f e e e f . . . 
        . f e 2 2 2 2 e e f f f f . . . 
        . f 2 e f f f f 2 2 2 e f . . . 
        . f f f e e e f f f f f f f . . 
        . f e e 4 4 f b e 4 4 e f f . . 
        . . f e d d f 1 4 d 4 e e f . . 
        . . . f d d d e e e e e f . . . 
        . . . f e 4 e d d 4 f . . . . . 
        . . . f 2 2 e d d e f . . . . . 
        . . f f 5 5 f e e f f f . . . . 
        . . f f f f f f f f f f . . . . 
        . . . f f f . . . f f . . . . . 
        `,img`
        . . . . f f f f f f . . . . . . 
        . . . f 2 f e e e e f f . . . . 
        . . f 2 2 2 f e e e e f f . . . 
        . . f e e e e f f e e e f . . . 
        . f e 2 2 2 2 e e f f f f . . . 
        . f 2 e f f f f 2 2 2 e f . . . 
        . f f f e e e f f f f f f f . . 
        . f e e 4 4 f b e 4 4 e f f . . 
        . . f e d d f 1 4 d 4 e e f . . 
        . . . f d d d d 4 e e e f . . . 
        . . . f e 4 4 4 e e f f . . . . 
        . . . f 2 2 2 e d d 4 . . . . . 
        . . . f 2 2 2 e d d e . . . . . 
        . . . f 5 5 4 f e e f . . . . . 
        . . . . f f f f f f . . . . . . 
        . . . . . . f f f . . . . . . . 
        `,img`
        . . . . . . . . . . . . . . . . 
        . . . . f f f f f f . . . . . . 
        . . . f 2 f e e e e f f . . . . 
        . . f 2 2 2 f e e e e f f . . . 
        . . f e e e e f f e e e f . . . 
        . f e 2 2 2 2 e e f f f f . . . 
        . f 2 e f f f f 2 2 2 e f . . . 
        . f f f e e e f f f f f f f . . 
        . f e e 4 4 f b e 4 4 e f f . . 
        . . f e d d f 1 4 d 4 e e f . . 
        . . . f d d d d 4 e e e f . . . 
        . . . f e 4 4 4 e d d 4 . . . . 
        . . . f 2 2 2 2 e d d e . . . . 
        . . f f 5 5 4 4 f e e f . . . . 
        . . f f f f f f f f f f . . . . 
        . . . f f f . . . f f . . . . . 
        `],
    500,
    characterAnimations.rule(Predicate.MovingLeft)
    )
`})


game.onUpdateInterval(500, function () {
    if (controller.anyButton.isPressed()) {
        music.stopAllSounds()
        tiles.setCurrentTilemap(tilemap`level 1 stage 1`)
        mySprite = sprites.create(assets.image`mattHead`, SpriteKind.Player)
        characterAnimations.setCharacterAnimationsEnabled(mySprite, true)
        scaling.scaleByPixels(mySprite, 10, ScaleDirection.Uniformly, ScaleAnchor.Middle)
        scroller.scrollBackgroundWithCamera(scroller.CameraScrollMode.BothDirections)
    } else {
        
    }
})

I was trying to enable my character to move left,right,up, and down. (top-down game style) instead of animating the character and him moving, he stays still and produces a clone of himself that moves. if you keep moving him, he makes more clones.

This is what it looks like when you move.

Can’t connect securely (wss) to AWS Kurento to get Remote Stream in “Hello World” node.js tutorial

I’m testing locally on Windows 11. I’m able to get the remote stream if using http://localhost and ws://47.128.254.233:8888/kurento

but, after several attempts, still don’t know how to get this working in https with wss.

The keys included with the node project don’t work, but I generated some new ones with mkcert which do and allow me to run localhost as https:

var options =
{
   //key:  fs.readFileSync('keys/server.key'),
   //cert: fs.readFileSync('keys/server.crt')
    key: fs.readFileSync('keys/localhost+2-key.pem'),
    cert: fs.readFileSync('keys/localhost+2.pem')
};

…though https://localhost doesn’t work with ws, which is probably normal.

In the AWS console, I’ve got the following Inbound Rules for my Kurento Instance’s Security Group:

IP Version | Type      | Protocol | Port Range | Source
IPv4       | SSH       | TCP      | 22         | 0.0.0.0/0
IPv4       | All UDP   | UDP      | 0-65535    | 0.0.0.0/0
IPv6       | Custom TCP| TCP      | 8433       | ::/0
IPv4       | All TCP   | TCP      | 0-65535    | 0.0.0.0/0
IPv4       | Custom TCP| TCP      | 8888       | 0.0.0.0/0
IPv4       | Custom TCP| TCP      | 8433       | 0.0.0.0/0

The Instance has been auto-assigned an IPv6 uri: 2406:da18:3ae:d570:72fa:2620:b08e:6c37.

Connecting to the AWS Kurento Instance via SSH, I can run sudo netstat -tulnp | grep kurento and I get:

tcp6       0      0 :::8433                 :::*                    LISTEN      2299/kurento-media-
tcp6       0      0 :::8888                 :::*                    LISTEN      2299/kurento-media-

In the tutorial’s server.js, I’ve tried setting the ws_uri in different ways:

var argv = minimist(process.argv.slice(2), {
    default: {
        as_uri: 'https://localhost:8443/', // Local Node.js tutorial server
        ws_uri: 'wss://47.128.254.233:8433/kurento' // AWS Kurento Media Server
        //ws_uri: 'wss://[2406:da18:3ae:d570:72fa:2620:b08e:6c37]:8433/kurento'
    }
});

but it doesn’t work. Furthermore, checking the wss uri in PieHost or running Test-NetConnection -ComputerName 2406:da18:3ae:d570:72fa:2620:b08e:6c37 -Port 8433 fails.

Copilot suggested I’d need to make openSSL key and certificate on the AWS computer and reference them in kurento.conf.json. I tried this with self-signed openSSL key and cert and it didn’t help. There seems to be an issue with checking the key using: openssl rsa -noout -modulus -in /etc/kurento/kurento-key-no-pass.pem | openssl md5 where permission is denied unless you prepend that command with sudo. But attempts to lower its protection or move it to another directory didn’t help.

I tried to install coturn on the AWS server but it was already installed with the correct external-ip address already set in etc/turnserver.conf. I didn’t see a WebRtcEndpoint.conf.ini in the etc folder, so I made one and filled it this way:

stunServerAddress=stun.l.google.com
stunServerPort=19302
turnURL=kurento:[email protected]:3478

and the Trickle ICE test seems to return good results:

0.006   host    2299836197  udp d0e51d97-6cff-4c2d-ada1-11cf46d06144.local  62880   126 | 30 | 255      
0.576   srflx   4082115708  udp 84.239.6.141    62880   100 | 30 | 255  stun:47.128.254.233:3478    
1.193   relay   1139691178  udp 47.128.254.233  62384   2 | 31 | 255    turn:47.128.254.233:3478?transport=udp  udp

…but the Remote stream still doesn’t connect and I get the WebSocket is already in CLOSING or CLOSED state. error message in the Edge dev console.

Not sure what to try next. At this point, I’ve probably tried TOO many things that are possibly interfering each other, so any hints are appreciated.

Communicating with REST service using Python/Flask, javascript and ajax

I have a web application fetching data from database behind a REST service creating output in form of a table:

Output of Flask/javascript code generating table with data.

As you see, there are two buttons (Collect/Archive) in each row of the table allowing the user to update the database via another REST service which accepts data via html PUT.

The click action(s) of the buttons is implemented in javascript. When a button is clicked the following code is executed:

function updateSourceState(sourceTypeId, sourceId, dataForUpdate) {
    $.ajax({
            url: '/update',
            data: {source_type_id: sourceTypeId, source_id: sourceId, data_for_update: dataForUpdate},
            dataType: 'json',
            type: 'PUT',
            success: function (data) {
                console.log('Data updated successfully');
            },
            error: function(data) {
                console.log('Data update failed. Response: ' + data);
            }
        }).done(function() {
            console.log('DONE: data updated successfully');
        }).fail(function(msg) {
            console.log('FAIL: data update failed: ' + msg);
        }).always(function(msg) {
            console.log('ALWAYS message: ' + dataForUpdate + ', url: ' + url);
        });
}

The communication with the REST service is implemented using Python-Flask and javascript. The main program (WebViewer.py) defines routes like this:

@bp.route('/update')
def update_source_state():
    app.logger.debug('[DEBUG] entering update_source_state()')

    source_id = request.args.get('source_id')
    source_type = request.args.get('source_type_id')
    dataForUpdate = request.args.get('data_for_update')

    url = '{0}/{1}/source/{2}'.format(ARCHIVE_CONFIG_BASE_URL, source_type, source_id)
    response = requests.put( url=url
                            , data=dataForUpdate
                            , headers={'Content-Type': 'application/json', 'accept': 'application/json'}
                            )

    if response.status_code == 200:
        return jsonify({'status': 'success'}), 200
    elif response.status_code == 405:
        return jsonify({'status': 'method not allowed'}), 405
    elif response.status_code == 500:
        return jsonify({'status': 'server error'}), 500
    else:
        return jsonify({'status': 'failed'}), 600

I see in the browser debugger that javascript updateSourceState() is called and the variables are filled. However, I never see that the output of app.logger.debug(...) appears in the log file. The server responds with state 405. As it seems, the method update_source_state() is not called (but I am not sure).

What is the right syntax to perform a PUT request to the REST service in this setup? Any help appreciated.

How to call methods through references in React19? I can’t pass methods by reference like it’s done in the book

I’m reading a book about React, but it’s out of date and it’s from React16. The book is Progressive Web Apps. I managed to update most of the things to React19, but I can’t pass methods by reference like it’s done in the book. From what I’ve seen, React removed ‘refs’ and is using useRef or createRef, but I’m not able to do it according to the book.

This is the reference by refs through react16

import React from 'react';
import './App.css';
import Header from './components/Header/Header.tsx';
import NovoUsuario from './components/NovoUsuário/NovoUsuario.tsx';
import Toast from './components/Toast/Toast.tsx'

function App() {
  return (
    <div>
      <Header />
      <NovoUsuario erro={msg => this.refs.toast.erro(msg)} />
      <Toast />
    </div>
  );
}

export default App;

The erro() component comes from the NovoUsuario class which is inside the validate(e) function.

validar(e) {
e.preventDefault()
let usuario = this.state.usuario
let validacao = this.state.validacao
validacao.nomeInvalido = ! usuario.validarNome()
validacao.generoInvalido = ! usuario.validarGenero()

let mensagem = ''
let primeiraVisaoCompleta = false
if(validacao.nomeInvalido && validacao.generoInvalido) {
    mensagem = 'Os campos nome e gênero estão inválidos!'
} else if (validacao.nomeInvalido) {
    mensagem = 'Seu nome está inválido!'
} else if (validacao.generoInvalido) {
    mensagem = 'Selecione seu gênero!'
} else {
    primeiraVisaoCompleta = true
}
if (!primeiraVisaoCompleta) {
    this.props.erro(mensagem)
}

this.setState({
    validacao: validacao,
    primeiraVisaoCompleta: primeiraVisaoCompleta
})

}

I tried using ref useRef useContext and it didn’t work, what would be the easiest way to access the function by reference in another component?