Mapbox/MapLibre how to save the latest location.hash updates

While the camera is moving around the map, the hash that is in the URL is updated, I need to save this value so that when I return to the map I will be in the same place as before I left

I used this code, the latest changes are saved in sessionStorage, but when switching to another address of my application and returning, sessionStorage was updated to the initial value, and did not accept the necessary past saves

    function initLocationHash () {
        let newHash = window.location.hash
        sessionStorage.setItem('locationHash', JSON.stringify(newHash))
    }

    window.addEventListener('DOMContentLoaded', function () {
        let storedHash = JSON.parse(sessionStorage.getItem('locationHash'));

        if (storedHash) {
            window.location.hash = storedHash
        }
        console.log(storedHash, 'storedHash')
    })

    setInterval(function () {
        let storedHash = JSON.parse(sessionStorage.getItem('locationHash'));
        let currentHash = window.location.hash
        if (currentHash !== storedHash) {

            initLocationHash()
        }
    }, 100)

Http call is called only one time, then it’s not being called anymore

I’m working on Angular 14 app and I have 3 separated forms in the same component, every form has a field named “rut”. So when user types some data on rut field on any of this 3 forms, I have to perfom http call to one service to bring data back.

listenForRutChanges() {
    const opRutControl = this.operationsFormGroup.get('rut')!;
    const legalRutControl = this.legalFormGroup.get('rut')!;
    const invoiceRutControl = this.invoiceFormGroup.get('rut')!;

    opRutControl?.valueChanges
      .pipe(
        debounceTime(300),
        filter(() => opRutControl.valid),
      )
      .subscribe((value) => {
        this.rutSubject.next({ value, formGroup: this.operationsFormGroup });
      });

    legalRutControl?.valueChanges
      .pipe(
        debounceTime(300),
        filter(() => legalRutControl.valid),
      )
      .subscribe((value) => {
        this.rutSubject.next({ value, formGroup: this.legalFormGroup });
      });

    invoiceRutControl?.valueChanges
      .pipe(
        debounceTime(300),
        filter(() => invoiceRutControl.valid),
      )
      .subscribe((value) => {
        this.rutSubject.next({ value, formGroup: this.invoiceFormGroup });
      });
  }

So as you see, I grab the form field for this 3 distinct forms, on valuechanges I wait a time and then I have a behaviourSubject. BehaviourSubject implementation is this:

rutSearch() {
    this.searchSubs = this.rutSubject
      .pipe(
        filter(({ value }) => value !== ''),
        distinctUntilChanged(),
        switchMap(({ value, formGroup }) =>
          this.clientService.getDetailsByRut(value).pipe(
            map((clientResponse) => ({ clientResponse, formGroup })),
            catchError(() => of()),
          ),
        ),
      )
      .subscribe(({ clientResponse, formGroup }) => {
        const { clientInfo } = clientResponse.data[0];

        const { email, fullName: name, phoneNumber: phone } = clientInfo;

        formGroup!.patchValue({ name, email, phone }, { emitEvent: false });
      });
  }

The problem is that the service is called once. Then even though I detect that other form field has distinct info, the service is not called anymore. Any ideas? Also if you see something that could be refactored please tell me.

Thanks in advance.

I tried instead of making a behavior subject, to call a normal function with http call. But didn’t work.

JWT with RS256 won’t accept private key

I am trying to use ‘jsonwebtoken’ to create a JWT with RS256. I have created the keys with this command:

ssh-keygen -t rsa -b 4096 -m PEM -f <filename>

The output for the private key looks like this:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,3EA25EB113F5940340B4995D7B29B4F7

bQ4mTHOuQgGobjCKwfgOAml1BIa8Qs7VMuGTRYDyXFCNjx+5gdz687z1GdwEQlFu
GYbD15...
-----END RSA PRIVATE KEY-----

I read in the private key with ‘fs’ and pass it to jsonwebtoken with:

jwt.sign(myData, privateKey, options)

However, I am getting this error every time:

Error: secretOrPrivateKey must be an asymmetric key when using RS256

I have looked it up and others with the same issue have solved it by putting it in the format that I have. It seems to be in the correct format to me, but jsonwebtoken refuses to encrypt it.

I tried remove the 2 header lines (Proc-Type and DEK-Info) but that doesn’t help at all. Why is it claiming that my key is incorrect? How do I create the correct key for it if this is not it?

How to match everything except single character but not inside double quoted string

I’m not able to find a similar question. I have a regex like this:

const re = /(${([^}]+)})/

I’m trying to add better regex for string interpolation into my Scheme based lisp interpreter, it should work like JavaScript template literals ${...}. I want to match everything that is not "}" but not inside double quotes.
I use String::split() on a bigger string, so I need to extract all the matches.

Example expressions that should match:

  • ${(string-append "{" "hello" "}")}
  • ${(+ 1 2)}

Example of a full string:

  • "x = ${(+ 1 2)}; y = ${(+ 2 3)}; s = ${(string-append "{" "hello" "}")}"

Can you do this with a single regex? Or do I need to have a small parser for it?

Why calling public function from resources/js/app.js raised error?

On laravel/livewire site I call js setAppTitle function, which declared in resources/js/app.js :

import './bootstrap';

import Alpine from 'alpinejs';

window.Alpine = Alpine;

import focus from '@alpinejs/focus'

Alpine.plugin(focus)
Alpine.start();


function setAppTitle (site_name, page_title, bus) {
    console.log('setAppTitle site_name::')
    console.log(site_name)

    if (typeof page_title !== 'undefined' && page_title !== '' && site_name !== 'undefined' && site_name != '') {
        if (document.getElementById("app_title")) {
            document.getElementById("app_title").innerHTML = page_title + ' in ' + site_name
        }
    }
}

console.log('resources/js/app.js::')

from blade page resources/views/admin/app-images/crud-app-images.blade.php :

<div class="admin_page_container" id="app_image_admin_page_container">

    <div class="editor_listing_wrapper_bix_width" x-data="adminAppImageComponent()" x-init="[onAdminAppImageComponentInit() ]" x-cloak>
        ...

        function adminAppImageComponent() {
            return {
                ...

                onAdminAppImageComponentInit: function () {
                    console.log('onAdminAppImageComponentInit from resources/views/admin/app-images/crud-app-images.blade.php::')
                        ...
                    setAppTitle('{{ readSettingsValue("site_name") }}', 'App images listing')

Looking at browser’s console I see that firstly console message from crud-app-images.blade.php is shown and from resources/js/app.js after that I got error :

alpinejs.js?v=49a5ab3b:537 Uncaught ReferenceError: setAppTitle is not defined

In resources/views/components/admin.blade.php I have js/app.js called before @livewireStyles :

<!DOCTYPE html>

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title id="app_title">{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap">

    <!-- Styles -->

    @vite(['resources/css/app.css', 'resources/js/app.js'])

    @livewireStyles

    <!-- Scripts -->
</head>

<!-- for https://github.com/tailwindlabs/tailwindcss/discussions/3878 -->

<body class="flex flex-col min-h-screen">
...

Which is valid flow for this issue with public function ?

    "laravel/framework": "^10.43.0",
    "livewire/livewire": "^3.4"

Thanks in advance!

How do i add a custom delimiter to this context menu search?

I’m using the extension “Custom right-click menu” to add a custom site search
When i use the context menu, it adds spaces to the search term. i need it to have a +.

var search = crmAPI.getSelection() || prompt('Please enter a search query'); var url = 'https://www.subetalodge.us/list_all/search/%s/mode/name'; var toOpen = url.replace(/%s/g,search); window.open(toOpen, '_blank');

I’m a noob and i have literally no idea what im doing

get data of the user logged in to discord with next-auth

How can I pull the banner, id, etc. of the logged in user? next@12 [email protected]
When I log the profile part at the bottom, all the information comes out, but when I try to do it in the frontend part, I can’t pull it in a way I don’t understand. I just started next.js. I couldn’t use next-auth with next.js version 14. 😀

import DiscordProvider from "next-auth/providers/discord";

export const authOptions = {
  providers: [
    DiscordProvider({
      clientId: process.env.CLIENT_ID,
      clientSecret: process.env.CLIENT_SECRET,
      authorization: { params: { scope: "identify guilds" } },
      profile(profile) {
        if (profile.avatar === null) {
          const defaultAvatarNumber = parseInt(profile.discriminator) % 5;
          profile.image_url = `https://cdn.discordapp.com/embed/avatars/${defaultAvatarNumber}.png`;
        } else {
          const format = profile.avatar.startsWith("a_") ? "gif" : "png";
          profile.image_url = `https://cdn.discordapp.com/avatars/${profile.id}/${profile.avatar}.${format}`;
        }

        return {
          id: profile.id,
          name: profile.username,
          discriminator: profile.discriminator,
          image: profile.image_url,
          banner: profile.banner,
          accentColor: profile.accentColor,
        };
      },
    }),
  ],

  callbacks: {
    async session({ session, user, token }) {
      if (session) {
        session.accessToken = token.accessToken;
        session.tokenType = token.tokenType;
        session.discordUser = token.profile;
      }

      return session;
    },
    async signIn({ user, account, profile, email, credentials }) {
      if (account.provider != "discord" && !user.id) {
        return;
      }

      return {
        user: {
          name: user.name,
          email: user.email,
          image: user.image,
          banner: profile.banner,
          accentColor: profile.accentColor,
        },
        accessToken: user.accessToken,
        expires: user.expires,
      };
    },

    async jwt({ token, account, profile }) {
      if (account) {
        token.accessToken = account.access_token;
      }

      return token;
    },
  },
  secret: process.env.NEXTAUTH_SECRET,
};

export default NextAuth(authOptions);

How to Retrieve an Element in Express.js by Passing a Token Generated by Laravel 8?

I’m working on two projects simultaneously: one in Laravel 8 and the other in Express.js. In the Laravel project, I generate a token and want to use it to retrieve an element in my Express.js application. How can I pass this token securely from Laravel to Express.js and then use it to fetch the corresponding element?

Here’s what I have in mind:

  1. I generate a token in Laravel.

  2. I send this token to my Express.js application.

  3. In Express.js, I create a route to receive the token and use it to fetch the corresponding element.

Could someone guide me on how to implement this securely and efficiently in both Laravel and Express.js?

Any help or pointers would be greatly appreciated! Thanks in advance!

WP_list_table display text on column with textarea

Friends,

I have implemented the extension of WP_list_table PHP class that I use to render my table in the WordPress site admin plugin. In one of the columns of the WP_list_table I use textarea field for user notes.

function column_notes($item){
    return sprintf(
        '<span><textarea id="%s" ></textarea>', $item['ID']
    );
}

When the user adds some text in the text area, I save it with javascript and jquery to a WP database table column ‘notes’. If I read from the mysql the contents of the ‘notes’ column with PHP how can I display them on the textarea? In the WP_list_table I use function prepare_items to prepare data for the table. For each item that I want to display in table row I define data array:

$data[] =array(
    'ID' => $order->id,
    'date_created' => wc_format_datetime($order->get_date_created()),
    'total'=> wc_price($order->total),
    'notes'=> htmlspecialchars($wpdb->get_var("SELECT notes FROM orders WHERE id = '$order->id'"))
);

Although the query returns the contents of the notes field from DB, its not displayed on the text area. Is it possible to do that with php, or do I need javascript/jquery here again?

Change the appearance of dragged element

my task is to create drag and drop interface, where user drags an element, which changes its appearance during that short amount of time – till it is dropped in its destination.

I would like to do it with native Web API. I have found the event called “dragstart” in MDN Documentation. And prepared this fiddle to demonstrate the behaviour.

const source = document.getElementById("draggable");
source.addEventListener("dragstart", (event) => {
  event.target.classList.add("dragging");
});

source.addEventListener("dragend", (event) => {
  event.target.classList.remove("dragging");
});
body {
  /* Prevent the user from selecting text in the example */
  user-select: none;
}

#container {
  width: 400px;
  height: 20px;
  background: blueviolet;
  padding: 10px;
}

#draggable {
  text-align: center;
  background: white;
}

.dragging {
  width: 422px;
  color: red;
  font-weight: 700;
}
<div id="container">
  <div id="draggable" draggable="true">Drag me</div>
</div>
<div class="dropzone"></div>

However the result is not sufficient. In my task I need the default element to persist its appearance and change only the dragged minimised version of it – ideally it should be narrower and show a little different content than the default element.

If you knew any source, where this task is resolved (anyhow), I’d be glad for your reply.

Shadow DOM | airship-html-prompt-shadow | I’m not able to get in shadow DOM elements to click on buttons

please review the below link that we used in project, To complete test case i need to click on buttons, but right now not able to find any xpath that directly clicks on these two buttons.

Buttons

  1. No, Thanks
  2. Yes, Subscribe me!

https://docs.airship.com/platform/web/plugins/html-prompt/

<div class="airship-html-prompt-shadow">
#shadow-root (open)
<div class="airship-prompt-container" style="display: block;"><div class="airship-alert airship-position-top" data-airship-prompt="">
    <div class="airship-alert-powered airship-hidden"><a data-airship-trigger-goto-airship="">Airship</a></div>
    <div class="airship-alert-body">
      <div class="airship-alert-logo"><img src="/assets/Web/images/logo-top.svg"></div>
      <div>
        <div class="airship-alert-title">Subscribe to our notifications</div>
        <div class="airship-alert-message">Stay tunned to get our best offers by subscribing to our push notifications</div>
      </div>
    </div>
    <div class="airship-alert-buttons">
      <button class="airship-btn airship-btn-deny" data-airship-trigger-deny="">No thanks</button>
      <button class="airship-btn airship-btn-accept" data-airship-trigger-accept="">Yes, Subscribe me!</button>
    </div>
  </div></div>

</div>
[enter image description here](https://i.stack.imgur.com/DwoAb.png)

link of library that used: https://docs.airship.com/platform/web/plugins/html-prompt/

Code that I have executed

      await landingpage.gotolandingscreen()
        await page.waitForLoadState('domcontentloaded');
    
        await page.waitForSelector('div.airship-html-prompt-shadow');
        // Get the element containing the shadow DOM
        const element = await page.locator('div.airship-html-prompt-shadow');
      
        // Use the >> operator to access elements within the shadow DOM
        const button = await element >> locator('button.airship-btn.airship-btn-deny');
      
        // Click the button
        await button.click();

I’m working on playwright Node.js with Javascript.

 await Landigpage.gotolandingscreen()
    await page.waitForLoadState('domcontentloaded');

    await page.waitForSelector('div.airship-html-prompt-shadow');

    // Get the element containing the shadow DOM
    const element = await page.locator('div.airship-html-prompt-shadow');
  
    // Use the >> operator to access elements within the shadow DOM
    const button = await element >> locator('button.airship-btn.airship-btn-deny');
  
    // Click the button
    await button.click();

Set Text Writing Direction when using Lexical js to build text editor app

Im using facebook/lexical to build a custom text editor, im trying to add option to manually change the text writing direction either ltr or rtl

ive tried setDirection(“ltr” or “rtl”) but the code does nothing, i was expecting it to work, and theres not other option i can think of now, i was hoping setDirection() would update the dir attribute of the Element,

how can i get it to to work, such that the dir attribute is updated properly, and i can also get it back when i consume the export from lexical to prefill the editor, when updating the contents

Can’t click a button in WebView via Javascript in Android Studio

I’m creating an Android app with WebView to show a webpage. I want to link a button in my app’s layout (triggerButton) to activate a button (btn1) on the webpage when pressed. However, I’m struggling to figure out how to make this work.

public class MainActivity extends AppCompatActivity {

    WebView myWeb;
    Button triggerButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myWeb = findViewById(R.id.myWeb);
        myWeb.getSettings().setJavaScriptEnabled(true);
        myWeb.getSettings().setDomStorageEnabled(true);
        myWeb.loadUrl("myUrl");

        myWeb.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                triggerButton = findViewById(R.id.triggerButton);
                triggerButton.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View v) {
                        //view.evaluateJavascript("document.getElementById('btn1').style.backgroundColor = 'red';", null); //this works
                        view.evaluateJavascript("document.getElementById('btn1').click();", null); //this doesnt work
                    }
                });
            }
        });

    }

}

I can change the style of btn1 (background color) with this command:

view.evaluateJavascript("document.getElementById('btn1').style.backgroundColor = 'red';", null);

but I can’t seem to press the button with the same format

view.evaluateJavascript("document.getElementById('btn1').click();", null);

I have also tried various different commands inside javascript like creating a seperate function. But none of them have worked

how can i solve this problem on cypress when i tried to select

I’m trying to type a date on ‘my-date-picker’ from angular with cypress but it’s getting this error:

“This element is not visible because it has an effective width and height of: 0 x 0 pixels. Fix this problem, or use {force: true} to disable error checking.”

here’s my code

it('select date picker', ()=>{
    cy.visit('../../src/app/pages/dates.component.html')
    cy.get('#name').type('ana')
    cy.get('#beginDate').type('01/02/2024')
    cy.get('#endDate').type('15/02/2024')
  })

i tried to use .within() but didn’t work since i have two my-data-picker. How can i fix that?