Isolate container div from website’s styles without iframe

I have a simple textarea and a preview modal which shows me how the content of the textarea looks like in an email (so basically loads and shows the content as HTML).

Now, this preview is affected by my website’s styles and I want to isolate it, so that it’s as plain and exact as it would show when sent as email. I don’t want to use iframe as it’s not responsive, are there better ways to do it?

I’m using VueJS, but ideally I would like a solution that doesn’t require installing a plugin just for this. The solution I’m looking for is either in CSS, or vanilla javascript, or built-in Vue functionality

Create embroidery images from png or text [closed]

I am creating a canvas in javascript. I am loading an image to the canvas and displaying an image on the canvas, I want this image to be converted to an embroidery filter view.

I can use python nodejs php as a backend. How can I do this, is there a library or function to do this?

I have been searching for 4 days and I can’t find anything

I want a library that I can use to convert images or text to an embroidery filter view.

How to make node.js ignore css files

I can’t run the tests with Mocha in my vanilla javascript project when I have a CSS file import because I can’t get Node to ignore that specific extension.

I get this error:

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension “.css”
at new NodeError (node:internal/errors:405:5)
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
at defaultGetFormat (node:internal/modules/esm/get_format:124:36)
at defaultLoad (node:internal/modules/esm/load:84:20)
at nextLoad (node:internal/modules/esm/loader:163:28)
at ESMLoader.load (node:internal/modules/esm/loader:603:26)
at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
at new ModuleJob (node:internal/modules/esm/module_job:64:26)
at #createModuleJob (node:internal/modules/esm/loader:480:17)
at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34)
at async ModuleWrap. (node:internal/modules/esm/module_job:79:21)

Here is a sample repository to replicate the issue, hoping it will be helpful:

https://github.com/Marco0491/mocha-issue-simulation

Everything I’ve found so far is outdated and doesn’t work in my case.

Navigation in external URLs within TMA (Telegram Mini App)

Inside of my Telegram Mini App, say I have an anchor tag <a href="google.com">External URL</a>, which then opens inside of the telegram app itself. As is, there is no way to navigate back to the original app, except clicking the ‘Close’ button in the top left and then opening the TMA again from the bot main button.

I can enable the ‘Back’ button with window.Telegram.WebApp.BackButton.show();, which visually changes the ‘Close’ button to a ‘< Back’ button but which does nothing on click. I’ve tried to bind it to navigate back like so:

window.Telegram.WebApp.BackButton.onClick(() => {
  alert("Navigated back!");
  history.back();
});

While the alert fires when inside the original app, once the user clicks into the external link, the back button no longer works (and the alert no longer fires). As such I can guess that the function is only bound to the button when in the original app, which is not helpful to me as I’m trying to allow the user to navigate back to the app after viewing an external file. How can I permanently bind the function to the back button or, failing that, achieve some way to allow the users to navigate back to the original app after viewing an external file?

How to detect right click while mouse is moving?

Is there a way to detect a right click when moving the mouse?

It is easy to detect left click when moving mouse but I can’t detect right click

document.addEventListener('mousemove', e => console.log(e.buttons || e.button))

And also window.oncontextmenu does not fires when mouse is moving

Prevent validateOnChange using custom fields in VeeValidate

In my VueJs app, I’ve got the following custom field component in VeeValidate:

<template>
  <input v-model="value" type="text" />
</template>

<script setup>
  import { useField } from 'vee-validate'

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

  const { value } = useField(props.name)
</script>

My form is set with the following configurations:

  configure({
    validateOnBlur: false,
    validateOnChange: false
  })

But my custom field component is still validating on Change and on Blur. How can I make the custom field work like any other field and respect my form configurations?

CSRF token for AJAX call in attached javascript file

I’m working in Codeigniter 4 with CSRF protection enabled. I have an AJAX call in an attached js file, and I can’t figure out how to generate the CSRF token. Previously, I have done it in php files with embedded js, but in the attached js file I can’t run php.

In the attached js file I have:

//makes a tooltip with description of analysis (header)
    $('.tbl-header').each(function () {
        makeHeaderInfo($(this))
    })

function makeHeaderInfo(header) {
        var analysis = header.hasClass('seed') ? 'Seedling ' + header.text().toLowerCase() : 'Sapling ' + header.text().toLowerCase();
        var posturl = baseURL + "forest_regen/getAnalysisDetails";
        var data = {};
        data['analysis'] = analysis;
//This is what I would do in a php file...
//       var csrfName = '<?= csrf_token() ?>'; 
//       var csrfHash = '<?= csrf_hash() ?>';   
//       data[csrfName]=csrfHash;
        $.when($.ajax({type: "POST", url: posturl, data: data, dataType: 'json'})).done(function (result) {
            var description = (result.fldDescription == null) ? 'No description for this analysis yet' : result.fldDescription
            header.children('.header-info').attr('title', description)
                    .tooltip({
                        trigger: 'click hover',
                        placement: 'top',
                        container: 'body'
                    })
        })
    }
    ;

I tried defining the variables in the php file which has this js file attached, but I get “csrfName is not defined.” I’m not sure how to pass the variables to the js file?

Is there a way to generate the csrfName and csrfHash in javascript or jquery? Or another way to accomplish this?

Thank you!

InvalidKeyMapError in Google Javascript API

I have been facing this error in my React project whenever I use Maps JavaScript API along with Google places API.
Maps JavaScript API error: InvalidKeyMapError

Here’s the code:

return (
    <SectionWrapper id={'generate'} header={"Generate your Dream Trip"} title={["Tell us your", "Travel","Preferences"]}>
      <Header index={'01'} title={'Pick a destination'} />
      <GooglePlacesAutocomplete className='bg-slate-950 border border-solid border-orange-400'>
        apiKey={import.meta.env.VITE_GOOGLE_PLACE_API_KEY}
      </GooglePlacesAutocomplete>

And I have added the script tag to my index.html file:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="/logowanderly.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Wanderly</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,100;0,200;0,300;0,400;0,500;0,600;0,700;0,800;0,900;1,100;1,200;1,300;1,400;1,500;1,600;1,700;1,800;1,900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <script src="https://maps.googleapis.com/maps/api/js?key=VITE_GOOGLE_PLACE_API_KEY&libraries=places"></script>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

Need help with this ASAP(PS: the value that I have entered for my key is absolutely correct).

I tried checking my key and making a new key but nothing is helping.

polkit policy, restrict the parameters of an application when running with pkexec

I should be able to restrict the parameters when running an application without asking for password (debian 12, systemd 256, polkit 122-3).
For example:

app foo
app foo ...

should work, but

app bar
app bar ...

should be blocked.

This would be my approach, but it did not work:

polkit.addRule(function(action, subject) {
    var program = action.lookup("program");
    var args = action.lookup("command_line");

    if (action.id == "org.freedesktop.policykit.exec" &&
        subject.isInGroup("some ldap group") &&
        program == "/usr/bin/app" &&
        args[1] == "foo") {
                return polkit.Result.YES;
        }
});

Does anyone have an idea?

How to query in firebase with OR operator, whose query parameters are different?

I am trying to implement OR operator in firebase query. I searched but couldn’t find similar usage that I intend, for example this answer doesn’t apply to mine. I want all occurences to get returned in my query. I am trying to do something like this:

query(collection(db, "users"),
  where("town", "==", user.town) OR
  where("city", "==", user.city) OR
  where("country", "==", user.country), (snapshot) => { ... }

As can be seen, I am trying to return all instances, and the query parameters are not the same. Is there a way to do this in firebase?

Woocommerce – How to setup new order email distribution based upon customer country, state, and zip / postal code

I’m trying to setup a way for new orders in Woocommerce upon submission from my site to be copied on different emails based upon geographic location in addition to the admin email.

For example: For an order submitted from Alabama with a Zip Code of 35976 in the United states, it will email an individual in that region as well as the admin email as usual. This would be similar to other countries as well since we sell globally.

I’m familiar how to do this in Javascript as I’ve done it for Adobe pdf forms but I’m vaguely familiar with PHP.

I would presume, if this is possible, it would be within email-order-details.php

I have been unsuccessful trying to find a plugin to work for what we need.

Any assistance would be welcome and appreciated.

I have not attempted a solution at this time.

Regex for separating strings that include whitespace with commas [duplicate]

I’m trying to achieve something very simple. I’m writing a Tampermonkey script where I want to be able to input Test, test test, Test 1, T.est 2, te#st 3, test 4 and get as a result ["Test", "test test", "Test 1", "T.est 2", "te#st 3", "test 4"], to be used as an array. Ideally it should be compatible letters, numbers, and special characters (that aren’t commas). The result shouldn’t be ["Test", "testtest", "Test1", "T.est2", "te#st3", "test4"].

The current solution I have is

const TESTOUTPUT = 'Test, test test, Test 1, T.est 2, te#st 3, test 4'.match(/[^,s?]+/g);
console.log(TESTOUTPUT);

The output is ["Test", "test", "test", "Test", "1", "T.est", "2", "te#st", "3", "test", "4"], so it’s inserting commas after every word and erasing every whitespace between them.

Other solutions I’ve found (like this one and this one) are separating elements that don’t have any space between them before or after the commas (so their input is Test, testtest, Test1, T.est2, te#st3, test4)

How to render nodes incrementally using cytoscapejs’ layout method?

I am currently using cytoscapejs for my UI to render a graph. I have a big graph that I want to render on-demand or incrementally to avoid performance bottleneck issues. My server sends the graphs in chunks as and when requested.

What I want to do:

  1. Fetch the first chunk from the backend and render it with dagre layout or any layout that is easier for the user to understand. We can call this graph as G0
  2. Fetch the next chunk when the user requests neighbouring subgraph. (Assume that the size of the subgraph is fixed as of now) The fetched graph can be referred as G1
  3. Render G1 with respect to G0 such that the overall result is consistent and looks like as if both G1 and G0 were rendered together.

What is happening:

When I render the G1 graph using the answer given on this page: Cytoscape: apply layout only to newly added nodes
the new nodes overlap the nodes of G0. In other words, the layout function is not taking the previously rendered graph G0 into consideration.

What have I tried:

I looked around and came across this library: https://github.com/iVis-at-Bilkent/cytoscape.js-layout-utilities?tab=readme-ov-file which has been developed for the exact same purpose (incrementing layout adjustments). But when I tried this library (by referencing demo.html, I did not get the expected results. The nodes of G1 still overlap G0 nodes. Here is the snippets of my code:

  1. The api initialisation:
 api = cy.layoutUtilities({
                desiredAspectRatio: 1.0,
                polyominoGridSizeFactor: 1.0,
                utilityFunction: 1,
                componentSpacing: 80
            })
  1. Rendering the initial chunks (3 chunks):
        async function loadInitialChunks() {
            for (let i = 0; i < 3; i++) {
                // this function fetches an object containing two arrays
                // {nodes, edges} and stores it in a variable `preloadedchunks`
                await getChunk(chunkIndex++, chunkSize); 
            }
            renderChunks();
        }

        function renderChunks() {

            preloadedChunks.forEach(chunk => {
                chunk.nodes.forEach(node => {
                    cy.add({
                        group: 'nodes',
                        data: node.data,
                        position: node.position
                    });
                });
                cy.add(chunk.edges);
            });

           // This code has been referred from the demo.html file I mentioned above
           // More specifically, this code is present at line 299 in demo.html 
            var subgraphs = []
            cy.$().forEach(chunk => {
                var subgraph = {}
                subgraph.nodes = []
                subgraph.edges = []
                chunk.nodes().forEach(node => {
                    var boundingBox = node.boundingBox();
                    subgraph.nodes.push({
                        x: boundingBox.x1,
                        y: boundingBox.y1,
                        width: boundingBox.w,
                        height: boundingBox.h
                    })
                });

                chunk.edges().forEach(edge => {
                    subgraph.edges.push({
                        startX: edge.sourceEndpoint().x,
                        startY: edge.sourceEndpoint().y,
                        endX: edge.targetEndpoint().x,
                        endY: edge.targetEndpoint().y
                    })
                });
                subgraphs.push(subgraph);
            })

            var result = api.packComponents(subgraphs, true);
            cy.$().forEach((component, index) => {
                component.nodes().layout({
                    name: 'fcose',
                    animate: 'true',
                    fit: false,
                    transform: (node) => {
                        let position = {};
                        position.x = node.position('x') + result.shifts[index].dx;
                        position.y = node.position('y') + result.shifts[index].dy;
                        return position;
                    }
                }).run();
            });

            let currentZoom = cy.zoom();
            let currentPan = cy.pan();

            const layout = cy.layout({
                name: 'fcose',
                avoidOverlap: true,
                nodeDimensionsIncludeLabels: true
            });
            layout.run();

        }    

  1. Requesting additional chunks:
function renderAdditionalChunks(chunk, chunkIndex) {
            try {
                // This approach is given at line #398 in the demo.html file
                var newNodes = cy.collection();
                chunk.nodes.forEach(node => {
                    if (!loadedNodes.has(node.data.id)) {
                        node.data.chunkId = chunkIndex
                        var newEles = cy.add({
                            group: 'nodes',
                            data: node.data,
                        });
                        newNodes.merge(newEles.nodes());
                        loadedNodes.add(node.data.id);

                    }
                });

                chunk.edges.forEach(edge => {
                    edge.data.chunkId = chunkIndex
                    cy.add({
                        group: 'edges',
                        data: edge.data,

                    });
                });
                let elementF = cy.elements("node[chunkId=" + chunkIndex + "],edge[chunkId=" + chunkIndex + "]");
                console.log("Elements filtered out: ", elementF)

                elementF.layout({
                    name: 'fcose',
                    // fit: false,
                    animate: true,
                    avoidOverlap: true,
                    nodeDimensionsIncludeLabels: true
                }).run();

                api.placeNewNodes(newNodes);

                cy.zoom(currentZoom);
                cy.pan(currentPan);

            } catch (error) {
                console.log(chunk)
                console.error('Error:', error);
            }

        }

It would be really great if anyone can help me figure out what am I missing here or if there are any other better alternatives to do so. Thanks.

File upload service with moleculer

I have a service file, and I’m sending a file to the http://localhost:4000/uploads URL using the “file” field via POST in Postman. However, in my code, context.meta.$multipart is coming out as undefined, and the file is not being saved to the public directory.

api.service
`

const ApiGateway = require("moleculer-web");

module.exports = {
  name: "api",
  version: 1,
  mixins: [ApiGateway],

  settings: {
    port: 8080,
    path: "/upload",
    routes: [
      {
        path: "",
 
        bodyParsers: {
          json: false,
          urlencoded: false
        },

        mappingPolicy: "restrict",
        aliases: {
         
          "POST /multi": {
            type: "multipart",
            // Action level busboy config
            busboyConfig: {
              limits: {
                files: 3
              }
            },
            action: "v1.assets.upload"
          },
          // File upload from HTML multipart form
          "POST /": "multipart:v1.assets.upload",

          // File upload from AJAX or cURL
          "PUT /": "stream:v1.assets.upload"
        },
        // Route level busboy config.
    
        busboyConfig: {
          limits: {
            files: 1
          }
        }
      }
    ],

    assets: {
      folder: "./public"
    }
  }
};

`

assets.service.js
`

module.exports = {
    name: "assets",
    version: 1,
    actions: {
      upload: {
        handler(context) {
          console.log("params", context.params.meta);
          console.log("context.meta.$multipart", context.meta.$multipart);
        }
      }
    }
  };

`

I tried both POST and PUT, and even tested it by creating a website, but I still couldn’t resolve the error. It returns 200 OK in Postman, but the file is not uploaded, and both console.log statements in the assets.service.js file are returning undefined.