?? null coalesce for Chrome V79

We use embedded chrome in our application which is tied to V79.

However the application loads GoogleMaps API using

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    defer></script>

This is posing a challenge with new operators like ?? coalesce of ES not supported with the version of the browser.
Can there be a simple approach at all

  1. Javscript does not support for me to provide a global operator, I believe
  2. Search replace for evaluations would error prone
  3. Parsing and rewriting whole JS loaded would be complex
<!DOCTYPE html>
<html>
  <head>
    <title>Display Google Maps API Version</title>
  </head>
  <body>
    <script>
      function initMap() {
        // Add your map here.
        console.log('Google Maps API version: ' + google.maps.version);
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
    defer></script>
  </body>

</html>

TagInput React Component

TagInput React Component

TagInput is a reusable React component that allows users to input and manage tags. It is designed to be easily integrated into your React applications. This README provides information on how to use the TagInput component in your project.

Installation

You can install the TagInput component as a package using npm or yarn:

npm install tag-input-reactjs

or

yarn add tag-input-reactjs

Usage

enter image description here

Once you’ve installed the package, you can import the TagInput component into your React application and use it as follows:

import React, { useState } from "react";
import TagInput from "tag-input-reactjs";

function YourComponent() {
  const [tags, setTags] = useState({ yourTagType: [] });

  return (
    <div>
      <TagInput tags={tags?.yourTagType} setTags={setTags} name="yourTagType" error={false} />
    </div>
  );
}

export default YourComponent;

Make sure to replace "yourTagType" with the appropriate tag type you want to manage.

Props

The TagInput component accepts the following props:

  • tags (object): An object that contains the tags to be displayed and managed. The structure should be { [tagType]: [tags] }.

  • name (string): The type of tags to manage. This should correspond to the key in the tags object.

  • setTags (function): A function to update the tags when they are modified. It should accept the updated tags in the same format as the tags prop.

  • error (boolean, optional): A boolean value that can be used to indicate an error state. If set to true, the component will display a red border.

Functionality

The TagInput component provides the following functionality:

  • Tags can be added by typing text in the input field and pressing Enter or by separating tags with a comma.

  • Existing tags can be removed by clicking the “×” button next to the tag.

  • The component can display an optional error state with a red border when the error prop is set to true.

Styling

You can customize the styling of the TagInput component by modifying the CSS in your project. The component itself uses the “tagInputContainer” class for the main container and relies on CSS for styling.

“Post / HTTP/1.1” 400 78 Bad Request for POST requst from React to Django

I am trying to connect React js with Django backend and trying to send information from the form with 2 fields “name” and “description” to django.

NewSpace.js

function NewSpace() {
  const navigate = useNavigate();

  const { mutate } = useMutation({
    mutationFn: createNewSpace,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["events"] });
      navigate("/events");
    },
  });

  function handleSubmit(formData) {
    mutate({ event: formData });
  }

  return (
    <Modal>
      <EventForm onuubmit={handleSubmit}>
        <Link to="../" className="button-text">
          Cancel
        </Link>
        <button type="submit" className="button">
          Create
        </button>
      </EventForm>
    </Modal>
  );
}
export default NewSpace;

EventForm.js

export default function EventForm({ onuubmit, children }) {
  

  function handleSubmit(event) {
    event.preventDefault();

    const formData = new FormData(event.target);
    const data = Object.fromEntries(formData);

    onuubmit(data);
  }

  return (
    <form id="event-form" onSubmit={handleSubmit}>
      <p className="control">
        <label htmlFor="name">Name</label>
        <input
          type="text"
          id="name"
          name="name"
        />
      </p>

      <p className="control">
        <label htmlFor="description">Description</label>
        <textarea
          id="description"
          name="description"
        />
      </p>

      <p className="form-actions">{children}</p>
    </form>
  );
}

I have a POST view where i am trying to get the value and save it.

    def post(self,request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)

But i am recieving below error

Bad Request: /
[10/Dec/2023 11:19:35] "POST / HTTP/1.1" 400 78

I am really new to both django and react, not sure wheather the error is in the backend or the front end.
Please let me know.
Thank you

Navigating between sections with Next & Previous

I have simply

<section id="div_1">
 <a href="#">Next</a>
</section>

<section id="div_2">
 <a href="#">Next</a>
 <a href="#">Previous</a>
</section>

<section id="div_3">
 <a href="#">Previous</a>
</section>

I need simpy to navigate to these section when the <a> is clicked but cannot provide the href="#"value since that can be any value. I can not hard code the id. Simply just navigate to the section with the next id or previous id

get data from QR code to controller mvc core 5 c#

I need to pass data from js script to controller when web read a code
(scan.content)

           <section class="scans">
                    <h2>Scans</h2>
                    <ul v-if="scans.length === 0">
                        <li class="empty">No scans yet</li>
                    </ul>
                    <ul v-if="scans.length != 0">
                        <transition-group name="scans" tag="ul">

            <li v-for="scan in scans" :key="scan.date" :title="scan.content">{{ scan.content }}</li>

                        </transition-group>
                    </ul>
                </section>

Can we run multiple websites on a single domain name?

Let suppose we have 4 websites, more clearly 4 versions of website, one of them is developed in simple html, CSS and JS and all the others are in Angular, so they have different approaches to compile the code and create a deployment build.

Now, I want my domain, lets say, https://example.com to randomly load 1 version of the website and on the website there is a dropdown from where a user can select a version and the website reloads with that specific version.

So, we can assume, initially it loads version 2 then user selects version 4, the website reloads with version 4 without changing the domain name, it should always stay as https://example.com. Then again he can choose version 3 and same thing happens again without changing the domain name.

I know certain issues in this approach but want to explore scenarios and ways in which we can materialize our ideas into reality. lets see some of them:

  1. I know that if we nudge .htaccess on hosting service or server, it will entirely change the website for everyone at once, causing issues.
  2. We can use iFrames but then we have to use different domain names for different versions and the iframes will get restricted access
  3. We can serve website on same domain within folders or subdomains to make iframe see them in its parent domain but then those URLS should not open in main browser windows, if aybody can open them in different tab then it defeats the purpose of the idea.

Any other idea which can work in this scenario is welcome.

I found some library which can do something like my use case from here => Can I use multiple frameworks on a single website page?

But I would like to discuss more. Lets try to build something to be proud of.

JavaScript Encrypt and Decrypt message using RSA Public Key

I generated a RSA key pair based this command:

openssl genrsa -out key_pair.pem 2048
openssl pkcs8 -topk8 -inform PEM -outform PEM -in key_pair.pem  -out private.pem
openssl rsa -in key_pair.pem -pubout -outform PEM -out public.pem

then I wrote this codes to make a server-side program that used above private key to generate encrypt/decrypt message that send/receive to/from client side application.

public static String encryptByPrivate(String strToEncrypt) {
    try {
        var inputStream = EncryptDecryptHelper.class.getResourceAsStream(PRIVATE_KEY_PATH);
        byte[] privateKeyBytes = inputStream.readAllBytes();
        KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = privateKeyFactory.generatePrivate(privateKeySpec);

        Cipher encryptCipher = Cipher.getInstance("RSA");
        encryptCipher.init(Cipher.ENCRYPT_MODE, privateKey);


        byte[] secretMessageBytes = strToEncrypt.getBytes(StandardCharsets.UTF_8);
        byte[] encrypted = encryptCipher.doFinal(secretMessageBytes);
        String encryptedText = Base64.getEncoder().encodeToString(encrypted);
        return encryptedText;

    } catch (Exception e) {
        e.printStackTrace();
        throw new EncryptBodyFailException("Encoding error, please contact the system administrator.");
    }
}

public static String decryptByPrivate(String strToDecrypt) {
    try {
        var inputStream = EncryptDecryptHelper.class.getResourceAsStream(PRIVATE_KEY_PATH);
        byte[] privateKeyBytes = inputStream.readAllBytes();
        KeyFactory privateKeyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = privateKeyFactory.generatePrivate(privateKeySpec);

        Cipher decryptCipher = Cipher.getInstance("RSA");
        decryptCipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedMessageBytes = decryptCipher.doFinal(Base64.getDecoder().decode(strToDecrypt));
        return new String(decryptedMessageBytes, StandardCharsets.UTF_8);
    } catch (Exception e) {
        e.printStackTrace();
        throw new DecryptBodyFailException("Decoding error, please contact the system administrator.");
    }
}


public static String encryptByPublic(String strToEncrypt) {
    try {
        var inputStream = EncryptDecryptHelper.class.getResourceAsStream(PUBLIC_KEY_PATH);
        byte[] publicKeyBytes = inputStream.readAllBytes();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(strToEncrypt.getBytes("UTF-8"));
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        return encryptedText;
    } catch (Exception e) {
        e.printStackTrace();
        throw new EncryptBodyFailException("Encoding error, please contact the system administrator.");
    }
}

public static String decryptByPublic(String strToDecrypt) {
    try {
        var inputStream = EncryptDecryptHelper.class.getResourceAsStream(PUBLIC_KEY_PATH);
        byte[] publicKeyBytes = inputStream.readAllBytes();

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);

        Cipher decryptCipher = Cipher.getInstance("RSA");
        decryptCipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] decryptedMessageBytes = decryptCipher.doFinal(Base64.getDecoder().decode(strToDecrypt));
        return new String(decryptedMessageBytes, StandardCharsets.UTF_8);
    } catch (Exception e) {
        e.printStackTrace();
        throw new DecryptBodyFailException("Decoding error, please contact the system administrator.");
    }
}

Then, we try to wrote javascript app fopr client side. I have a react-js app that use public key to encrypt/decrypt message using Public key that send or receive from server. the java script code is :

const publicKeyPEM = "-----BEGIN PUBLIC KEY-----n" +
    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwFSqIsNbDl/bBhHMQLwAn" +
    ...................
    "OvkGLdI1AR0MtaCRrllE3yO3n5bAqqeZQjMl0C4ZURxjEzE7aTn2Hq3AU2conIwen" +
    "EQIDAQABn" +
    "-----END PUBLIC KEY-----";



const plaintext = "plain text that we want to send...";


function pemToArrayBuffer(pem) {
    const lines = pem.split('n');
    const base64 = lines.slice(1, lines.length - 1).join('');
    const binaryString = window.atob(base64);
    const bytes = new Uint8Array(binaryString.length);
    for (let i = 0; i < binaryString.length; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}

const publicKey = pemToArrayBuffer(publicKeyPEM);


window.crypto.subtle.importKey(
    "spki",
    publicKey,
    {
        name: "RSA-OAEP",
        hash: { name: "SHA-256" },
    },
    true,
    ["encrypt"]
)
    .then((cryptoKey) => {
        const encodedText = new TextEncoder().encode(plaintext);
        return window.crypto.subtle.encrypt(
            {
                name: "RSA-OAEP"
            },
            cryptoKey,
            encodedText
        );
    })
    .then((encrypted) => {
        const encryptedText = btoa(String.fromCharCode.apply(null, new Uint8Array(encrypted)));
        console.log("encrypted message: ", encryptedText);
    })
    .catch((error) => {
        console.error("error on encrypt: ", error);
    });


const encryptedText = "encrypted base64 string that server side application send to me...";


const encryptedData = new Uint8Array(atob(encryptedText).split('').map((c) => c.charCodeAt(0)));


window.crypto.subtle.importKey(
    "spki",
    publicKey,
    {
        name: "RSA-OAEP",
        hash: { name: "SHA-256" },
    },
    true,
    ["decrypt"]
)
    .then((cryptoKey) => {
        const encryptedData = new Uint8Array(atob(encryptedText).split('').map((c) => c.charCodeAt(0)));
        console.log()
        return window.crypto.subtle.decrypt(
            {
                name: "RSA-OAEP"
            },
            cryptoKey,
            encryptedData
        );
    })
    .then((decrypted) => {
        const decryptedText = new TextDecoder().decode(decrypted);
        console.log("decrypted test:", decryptedText);
    })
    .catch((error) => {
        console.error("error on decrypt :", error);
    });

When a client sending message to server first step encrypt requested message with Public key and server decrypt message with private key. after that server encrypt response message with private key and cleint must can be to decrypt encrypted response message.

when we encrypt message y public in client side every thins is OK. but decryption method return error : DOMException: Data provided to an operation does not meet requirements

I try another library like Crypto-js, Hybid-Crypto-js and NodeRSA. but cannot reach to Goal.

Changing fill and/or stroke color of loaded svg using CSS [duplicate]

In the following example, I’m creating my own list item icons by embedding them as background images to the list item elements and setting background-repeat to no-repeat.

ul
{
padding: 0;
}

li:nth-child(1) {
  list-style: none;
  padding: 10px 30px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='20' viewBox='0 0 24 24' fill='none' stroke='blue' stroke-width='2' stroke-linecap='round' stroke-linejoin='round' class='feather feather-home'%3E%3Cpath d='M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z'%3E%3C/path%3E%3Cpolyline points='9 22 9 12 15 12 15 22'%3E%3C/polyline%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: left center;
  background-size: 20px;
}

li:nth-child(2) {
  list-style: none;
  padding: 10px 30px;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='blue' class='bi bi-linkedin' viewBox='0 0 16 16'%3E%3Cpath d='M0 1.146C0 .513.526 0 1.175 0h13.65C15.474 0 16 .513 16 1.146v13.708c0 .633-.526 1.146-1.175 1.146H1.175C.526 16 0 15.487 0 14.854V1.146zm4.943 12.248V6.169H2.542v7.225h2.401m-1.2-8.212c.837 0 1.358-.554 1.358-1.248-.015-.709-.52-1.248-1.342-1.248-.822 0-1.359.54-1.359 1.248 0 .694.521 1.248 1.327 1.248h.016zm4.908 8.212V9.359c0-.216.016-.432.08-.586.173-.431.568-.878 1.232-.878.869 0 1.216.662 1.216 1.634v3.865h2.401V9.25c0-2.22-1.184-3.252-2.764-3.252-1.274 0-1.845.7-2.165 1.193v.025h-.016a5.54 5.54 0 0 1 .016-.025V6.169h-2.4c.03.678 0 7.225 0 7.225h2.4' /%3E%3C/svg%3E");
  background-repeat: no-repeat;
  background-position: left center;
  background-size: 20px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<ul>
    <li>First item</li>
    <li>Second item</li>
</ul>
</body>
</html>

For one HTML document, I’m OK with having these list markers remain blue as shown above. However, for another document, I’d like to default to another color, for example red.

Applying a filter will not do, because it seems to also affect the text content of the list items. I just need to modify the color of the list item marker.

How can I enforce this behavior using CSS? I.e. how can I get the list markers to look blue in one page and red in another page without duplicating the entire data link in url()?

EDIT

The mentioned duplicate is not a duplicate because it doesn’t address the corner case of loading an SVG using the background-image property. When an SVG is used as a background image, it’s not part of the DOM and therefore can’t be directly manipulated with JavaScript

Ant Design/Reactjs uploader (dragger) stop upload list loading

I’m using Ant-Design uploader/dragger in my reactjs project, I want to upload files after push the button, so I used customRequest, everything works good but I have small problem, it’s more bad ux for user; if you pick a file, list shown but it display small loading, I want to show clipper icon instead of loading icon, because it tell user to wait for upload! but I don’t want upload on select, it should press button for upload.

So here is my code:

<Dragger
                    {...uploadProps}
                >
                    <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                    </p>
                    <p className="ant-upload-text">Click or drag file to this area to upload</p>
                    <p className="ant-upload-hint">
                        Support for a single or bulk upload. Strictly prohibited from uploading company data or other
                        banned files.
                    </p>
                </Dragger>

const uploadProps = {
        name: 'file',
        multiple: true,

        customRequest(file){
            attacheFile(file) // this is my custom request
        }
    }

enter image description here

How can I stop this loading?

And show this instead:

enter image description here

select2 option cannot display selected value with axios query

I have project with reactjs and select. And on this project, i using axios instead of ajax default select2.

Init select2 code :

$(selector).select2({
         placeholder: placeholder,
         query: function (options) {
           // Membuat permintaan Axios secara manual
           axios.get(`${api_uri}/${endpoint}`, {
             params: {
               q: options.term,
             },
             withCredentials: true,
           })
             .then(function (response) {
               // Mengonversi respons ke format yang diharapkan oleh Select2
               var results = $.map(response.data.data.result, function (item) {
                 return {
                  id: item._id,
                  text: item.nama
                 };
               });
       
               // Memanggil fungsi callback success dengan hasil permintaan
               console.log(results);
               options.callback({ results: results });
             })
             .catch(function (error) {
               // Memanggil fungsi callback error jika terjadi kesalahan
               options.callback({ results: [], more: false, errors: [error] });
             });
         },
         processResults: function (data) {
            return {
               results: data.results,
            };
         }
      });

Its showing all of options, but when i click on the options its not selected

How can I store a complete user data in attribute of a collection in appwrite?

I am creating a social media app using react and appwrite for backend. In appwrite I have a collection in database named “users”. I want to store “followings” and “followers” in array as a attribute in user collection.

I am confused how to store user details in followings or followers of all user I am following.
There are two ways in which I can store details:

  1. I can store every users id.
  2. Somehow If I can create a relation between every user in users collection.

If i store ids of all users then to show all my followers on screen I have to get all users by id which requires so much call to database, which I don’t think a good way.

I can not create relations between data of same collection in appwrite.

So, I am stuck how to store other users data in my followes and followings array.

One other way can we to store complete user in array. But we can store the whole data as string, so now I can convert it to string, like JSON.stringify and when I wan data i will JSON.parse every data. But I am also not sure if it is a good way or can create any other problems.

in attribute i also can not store data directly that why I am thinking to convert it to a string.

enter image description here

regex utilities in vscode api?

Are there any set of language-specific utilities (in the vscode extension api) to help find expressions within a script?

Although I have a specific example below, the question above is more general, e.g. how are language parsers built? are they all just a bunch of regular expressions?

My specific example that motivated this question:

I want to find if there are any calls to a method called .getInfo() without any arguments provided, in a javascript document. For example:

/*
Examples of getInfo with and without a callback function.
*/
// foo.getInfo method in a comment. 
foo.getInfo(callback);
foo.getInfo  ();
foo.getInfo
();

foo
.getInfo(
    // single comment
)

foo.getInfo     (
// Testing 
/* Multiline 
comment
*/
);


foo.getInfo(
    print
)

foo.getInfo 
//comment
();

foo.getInfo 
//comment
(
    //testing
);

In this script there are six .getInfo() calls without any arguments, and two calls with arguments (one with callback, and another one with print). I am only interested in finding the ones without arguments.

My naive attempt to solve this with a regex is getting ridiculous. I asked bard for help, but so far none of the solutions match all six cases.

For example, this solution only matches three cases:

const regex = /b.getInfos*((?:s*(?://.*?|/*[sS]*?*/))*s*)/g;

this other solution also matches three cases (but not the same three):

const regex = /b.getInfos*(?://.*?|/*[sS]*?*/)*s*(?s*)/g;

Rather than trying different ridiculously long regular expressions, I wonder if there is a more general API for doing this within vscode api (or maybe a javascript library)? Also looking for other general suggestions for tackling these type of problems.

This is a small working version of extension.ts:

import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand('test.parse', () => {
    const editor = vscode.window.activeTextEditor;
    if (editor) {
        let document = editor.document;
        const documentUri = document.uri;
        if (documentUri.scheme==='file'){
            const regex = /b.getInfos*(?://.*?|/*[sS]*?*/)*s*(?s*)/g;
            const sourceCode = document.getText();
            const matches = sourceCode.match(regex);
            if (matches) {
              console.log(`Found ${matches.length} instances of .getInfo() called without arguments.`);
              console.log(matches);
            } else {
              console.log("No instances of .getInfo() called without arguments found.");
            }
        }
    }
    });
    context.subscriptions.push(disposable);

}
export function deactivate() {}

How to find boundaries and setView of no geographical map~ Leaflet

I try to find a way to insert random images at leaflet map and these images fit properly inside the map, like object-fit: contain .

let map = L.map('mapImage', {
        maxZoom: 1,
        minZoom: 1,
        crs: L.CRS.Simple,
        doubleClickZoom: false,
    }).setView([0, 0], 1);

let bounds :any= [[0,0], [1000,1000]];
     L.imageOverlay(backGroundUrl, 
     bounds).addTo(this.map);

I tried to convert units to pixels for bounds but nothing worked for me. How to deal with setView() and bounds to fit any image to map?
Thank you