Extending VSCode Markdown syntax highlighting to match nested Javascript code

I am trying to extend VSCode’s Markdown syntax highlighter in order to highlight some nested Javascript wrapped in a custom syntax. For example, the following Markdown file

# Example

@@$ var value = 10;

The result is @@{value}.

would be converted to

# Example

The result is 10.

I would like the following to be highlighted as Javascript in VSCode, as if they were wrapped in a fenced code block:

  • The contents of a line starting with @@$.

  • The contents wrapped between @@{ and }.

I tried modifying markdown.tmLanguage.json to add these:

"fenced_code_block_majsdown2": {
    "begin": "(^|\G)(@@$)",
    "name": "markup.fenced_code.block.markdown",
    "end": "(^|\G)(\r\n|\r|\n)\s*$",
    "patterns": [{ "include": "source.js" }]
},
"fenced_code_block_majsdown": {
    "begin": "(^|\G)(@@{)",
    "name": "markup.fenced_code.block.markdown",
    "end": "(^|\G)(})\s*$",
    "patterns": [{ "include": "source.js" }]
},

The code gets highlighted properly, but it seems that the "end" bit is ignored and I don’t understand why — starting from either a @@$ or @@{, the entire document is highlighted as Javascript. I’ve tried several combinations of regexes, and tried removing the initial part ((^|\G)), but I couldn’t figure out why the highlighter is so greedy.

How can I achieve my desired goal?

how to connect phantom wallet and send transactions?

hello everyone if someone can write code even on codepen and send it to me where you connected the phantom wallet and you can send the transaction by just pressing a button and you will have a connection to the wallet and then the transaction.

of course if you do everything I will write to you and drop up to $ 50 on the card)

please help very much needed

Word font family variations

An introduction. My teacher from university is kind of weird. She wants all essays handwritten by students and this is is a bit exaggerated given the fact the we live in computers era. I created a font family that resembles my handwriting and saved is as .ttf and installed it on windows and use it in word. It doesn’t seem convincing, so I was wondering: If I create 100 ttf each with slight variations of a letter, is there a way in word, when you type a letter, to chose randomly from those 100 ttf files to make the writing seem more organic, because I’m not a callighraphist, I can’t write a letter twice exactly the same way, so a slight variation would make it more convincing.

If it is not possible I have a way using HTML + JS:

document.getElementById("randomize").disabled=true;
function setupFonts(){

   var handwritten = document.getElementsByTagName("handwritten")[0];
   var raw_text = handwritten.innerHTML; //no tags in handwritten tag body
   var taggedText = "";
   var fontTag = "</font><font>";
   for(var i = 0; i < raw_text.length;i++){
      if((/[a-zA-Z]/).test(raw_text.charAt(i))){
         taggedText = taggedText.concat("<font>", raw_text.charAt(i), "</font>");
      }
      else{
         taggedText = taggedText.concat(raw_text.charAt(i));
      }
   }
   handwritten.innerHTML = taggedText;
   document.getElementById("randomize").disabled=false;
}
function randomizeFonts(){
   var fontNames = ['Arial', 'Verdana', 'Consolas']; //here will be listed the variations
   var fontsArray = document.getElementsByTagName("font");
   for(var i = 0; i < fontsArray.length;i++){
      fontsArray[i].setAttribute("face", fontNames[Math.floor(Math.random()*fontNames.length)]);
   }
}
<html>
<body>
<!-- Just 1 handwritten tag allowen on a page -->
<handwritten>
This is a sentence handwritten.
</handwritten>
<br>
<button id="setup" onclick="setupFonts()">Setup Fonts</button>
<button id="randomize" onclick="randomizeFonts()">Randomize Fonts</button>
</body>

<html>

It works, however if this is possible in word it would be better.

Ramda – reduce parentheses nesting on composition

I have array like this:

const arr = [
  ['1 1 1', '', '2 2 2'], 
  ['', '3 3 3', '4 4 4']
]

and my goal is to convert i to this array:

[
  [ [1,1,1], [2,2,2] ],
  [ [3,3,3], [4,4,4] ]
]

I am trying to do that in functional way using function composition. I am also using Ramda.

I have this code

const filterEmpty = filter(o(not, isEmpty));

const getFinalArr = map(
  compose( map(map(parseInt)), map(split(' ')), filterEmpty )
)

console.log(getFinalArr(arr))

It works just fine, but it’s not quite readable. I am wondering if is there way to write it with less map nesting. Something like that would be great:

const getFinalArr = map(
  compose( parseInt, map, map, split(' '), map, filterEmpty )
)

From my point of view it is much more readable. But of course it did not work.

Or if you can suggest another way how to easily deal with arrays nested like this. I am curious.

How to process updated object property values with Javascript and React?

I am looking to use Node and React for displaying dynamic table data where one property, `cost’ will be updated via a WebSocket listener and perform some functions, i.e. find highest/lowest, or addition, etc., to all costs within a list of pools (also think of a table with updating live stock values and columns for calculated values):

┌─────────┬─────────┬──────────────────────────────────┐
│ (index) │  name   │              pools               │
├─────────┼─────────┼──────────────────────────────────┤
│    0    │ 'pizza' │      [ [Object], [Object] ]      │ sum(cost), etc.
│    1    │ 'apple' │ [ [Object], [Object], [Object] ] │ sum(cost), etc.
└─────────┴─────────┴──────────────────────────────────┘

// singular pool object
// {Walmart, apple, 1.Wallmart.apple, 1.00}
class Pool {
    constructor(exchangeName, symbols, id, cost) {
        this.exchangeName = exchangeName;
        this.symbols = symbols;
        this.id = id;
        this.cost = cost;
    }
}

// takes in an array of pools
class Pools {
    constructor(poolName, pools) {
        var costCounter = 0;        // add up all costs in pools
        var exchangeList = '';
        for (var poolObj of pools) {
            //costCounter += poolObj.cost        // this works on object initialization but not cost updated property      
            exchangeList += poolObj.exchangeName + " ";
        }

        this.poolName = poolName;
        this.pools = pools;
        //this.costCounter = _costCounter;
        this.exchangeList = exchangeList;
    }

    // perform math functions
    get costCounter() {
        for (var poolObj of pools) {
            _costCounter += poolObj.cost;
        }
        return _costCounter;
    }

}

var arrPools = [];  // array of a symbol's pools

arrPools.push(new Pool("1.exch", "1.symbols", "1.someID", 1.00)),
arrPools.push(new Pool("2.exch", "2.symbols", "2.someID", 2.00)),
arrPools.push(new Pool("3.exch", "3.symbols", "3.someID", 3.00))

var thisPoolResults = new Pools("First Pool", arrPools);

//console.log(arrPools);
console.log(thisPoolResults);

After the initial data is defined, I will want subscribe to a cost event that will update each individual Pool.cost in the collection.

The output table will contain rows of individual pools properties and a calculated total cost, by costCounter.

I am having a difficult time creating a getter to automatically recalculate costs when a cost is updated.

As I am planning to use React (I assume there are similar features to Angular for data updates), what is a recommended way of achieving this?

im.ask.how. add update btn help ??javascript

I ask how add button update **here

>     **
>     
>     
>     var productNameInput = document.getElementById("productName");//input 
>     var productPriceInput = document.getElementById("productPrice");//input saeed
>     var productDescInput = document.getElementById("productDesc");//input k
>     var productCategoryInput = document.getElementById("productCategory");
>     
>     var productsContainer;
>     if (localStorage.getItem("productsList") == null)
>     {
>         productsContainer = [];
>     }
>     else {
>         productsContainer = JSON.parse(localStorage.getItem('productsList'));
>         displayProducts();
>     }
>     function addProduct() {
>     
>     
>         var product = {
>     
>             name: productNameInput.value,
>             price: productPriceInput.value,
>             category: productCategoryInput.value,
>             desc: productDescInput.value
>         }
>         productsContainer.push(product);
>         localStorage.setItem("productsList", JSON.stringify(productsContainer));
>         // clearForm();
>         displayProducts();
>     
>     }
>     
>     function clearForm() {
>         productNameInput.value = "";
>         productPriceInput.value = "";
>         productCategoryInput.value = "";
>         productDescInput.value = "";
>     
>     }
>     
>     
>     
>     function displayProducts() {
>     
>         var cartoona = ``;
>         for (var i = 0; i < productsContainer.length; i++) {//3
>             cartoona += `<tr>
>             <td>${i}</td>
>             <td>${productsContainer[i].name}</td>
>             <td>${productsContainer[i].price}</td>
>             <td>${productsContainer[i].category}</td>
>             <td>${productsContainer[i].desc}</td>
>             <td> <button class="btn btn-outline-warning">update</button></td>
>             <td> <button onclick="deleteProducts(${i})" class="btn btn-outline-danger">delete</button></td>
>         </tr>`;
>         }
>         document.getElementById("tableBody").innerHTML = cartoona;
>     }
>     
>     
>     
>     
>     function searchProducts(term) {
>         var cartoona = ``;
>         for (var i = 0; i < productsContainer.length; i++) {
>     
>             if (productsContainer[i].name.toLowerCase().includes(term.toLowerCase())
> == true) {
>                 cartoona += `<tr>
>                 <td>${i}</td>
>                 <td>${productsContainer[i].name}</td>
>                 <td>${productsContainer[i].price}</td>
>                 <td>${productsContainer[i].category}</td>
>                 <td>${productsContainer[i].desc}</td>
>                 <td> <button class="btn btn-outline-warning">update</button></td>
>                 <td> <button  onclick="deleteProducts(${i})" class="btn btn-outline-danger">delete</button></td>
>             </tr>`;
>             }
>         }
>         document.getElementById("tableBody").innerHTML = cartoona;
>     }
>     
>     
>     function deleteProducts(index) {
>         productsContainer.splice(index , 1);
>         displayProducts();
>         localStorage.setItem("productsList", JSON.stringify(productsContainer));
>       }
>     
>     //    deleteProducts(5);

Is there a way to create a back button in Django that understands a tree structure?

I have a Django website that looks like this:

enter image description here

The arrows represent hyperlinks that take you to the next page. All pages except the Main Page need a “Back” button.

For Page A and Page B, the back button is pretty simple – it always takes you to the Main Page.

For Page C however, there are 2 different ways to get to it (technically 3, if you count the back button on Page D), so it’s no longer obvious where the back button should take you.

The way it should work is this:

  • If the user came from Page A to get to Page C, the Back button should take them back to Page A
  • If the use came from Page B to get to Page C, the Back button should take them back to Page B
  • If the user didn’t come from either Page A or Page B to get to Page C (they could have just entered the URL of Page C into their browser), default to having the Back button take them to Page A

This has been asked before, and none of the answers/suggestions make sense for anything other than the most basic scenario, where Page C is the end node.

The problem:

  • Using a hardcoded url for the back button of Page C won’t work, because there are 2 ways to get to it
  • Using session to keep a single variable that keeps track of whether you last visited Page A or Page B won’t work because multiple browser tabs share the same session variables. If the user has 2 tabs of our website open, navigating around will lead to confusion as both will update the same session variable
  • Using request.META.HTTP_REFERER won’t work, because the user might navigate to Page D, and then back to Page C, so the HTTP_REFERER variable will point to Page D, rather than Page A or Page B
  • Using javascript:history.go(-1) won’t work – same problem as above with HTTP_REFERER

I have come across this issue in multiple projects, and it’s always a pain to deal with. The solution is always hacky. Is this a problem that inherently can’t be handled by Django, and must be handled by something like JavaScript’s sessionStorage?

In Javascript, can a closure share scope with a function return value?

JS n00b here, I’m trying to understand this unexplained code from Eloquent Javascript :

function trackKeys(keys) {
  let down = Object.create(null);
  function track(event) {
    if (keys.includes(event.key)) {
      down[event.key] = event.type == "keydown";
      event.preventDefault();
    }
  }
  window.addEventListener("keydown", track);
  window.addEventListener("keyup", track);
  return down;
}

var arrowKeys =
  trackKeys(["ArrowLeft", "ArrowRight", "ArrowUp"]);

I think I understand how the inner function track will maintain a reference to down and keys because it is a closure, but I’m lost at return down;

Will that return value be a reference to the exact same down the callbacks are accessing? I don’t understand; I thought local variables could only be accessed by inner functions?

Follow-up: what if down were a primitive data type and not an object, would this still work?

Thanks!

error – TypeError: Cannot read properties of undefined (reading ‘drawer’)

I am trying to copy the exact code from Material UI Drawer to add on my own website. The link is https://mui.com/components/drawers/

  import * as React from 'react';
import Box from '@mui/material/Box';
import Drawer from '@mui/material/Drawer';
import Button from '@mui/material/Button';
import List from '@mui/material/List';
import Divider from '@mui/material/Divider';
import ListItem from '@mui/material/ListItem';
import ListItemIcon from '@mui/material/ListItemIcon';
import ListItemText from '@mui/material/ListItemText';
import InboxIcon from '@mui/icons-material/MoveToInbox';
import MailIcon from '@mui/icons-material/Mail';

export default function TemporaryDrawer() {
  const [state, setState] = React.useState({
    top: false,
    left: false,
    bottom: false,
    right: false,
  });

  const toggleDrawer = (anchor, open) => (event) => {
    if (event.type === 'keydown' && (event.key === 'Tab' || event.key === 'Shift')) {
      return;
    }

    setState({ ...state, [anchor]: open });
  };

  const list = (anchor) => (
    <Box
      sx={{ width: anchor === 'top' || anchor === 'bottom' ? 'auto' : 250 }}
      role="presentation"
      onClick={toggleDrawer(anchor, false)}
      onKeyDown={toggleDrawer(anchor, false)}
    >
      <List>
        {['Inbox', 'Starred', 'Send email', 'Drafts'].map((text, index) => (
          <ListItem button key={text}>
            <ListItemIcon>
              {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
            </ListItemIcon>
            <ListItemText primary={text} />
          </ListItem>
        ))}
      </List>
      <Divider />
      <List>
        {['All mail', 'Trash', 'Spam'].map((text, index) => (
          <ListItem button key={text}>
            <ListItemIcon>
              {index % 2 === 0 ? <InboxIcon /> : <MailIcon />}
            </ListItemIcon>
            <ListItemText primary={text} />
          </ListItem>
        ))}
      </List>
    </Box>
  );

  return (
    <div>
      {['left', 'right', 'top', 'bottom'].map((anchor) => (
        <React.Fragment key={anchor}>
          <Button onClick={toggleDrawer(anchor, true)}>{anchor}</Button>
          <Drawer
            anchor={anchor}
            open={state[anchor]}
            onClose={toggleDrawer(anchor, false)}
          >
            {list(anchor)}
          </Drawer>
        </React.Fragment>
      ))}
    </div>
  );
}

I install both @mui/material and @mui/icons-material but it still shows this error.

Error: TypeError: Cannot read properties of undefined (reading ‘drawer’)

Any help will be appreciated.

The command `npx create-react-app my-app` does not create an application file

I want to install react-create-app. I’m using the command: npx create-react-app my-app. I can see the following information in the console:

Installing packages. This might take a couple of minutes. Installing react, react-dom, and react-scripts with cra-template ... added 1374 packages in 4m 163 packages are looking for funding run npm fund for details

and nothing is happening.

node and npm are the newest

In the folder I just created, I can only see node-modules, package, package-lock. I don’t have a file src. How to solve this problem?

How can I make JavaScript calls to scrape data from a website?

I’ll try to explain everything the way I understand it as clearly as possible, so correct me if I’m confused with something.

I was trying to scrape the users from a member list on a website, I used Python and the first thing I did was making a post request to the Request URL with the required headers so I get a response that contains the data I need but this didn’t work, so I tried to find out the reason.

From what I understand now the website uses AJAX to make XHR and JavaScript calls which respond with the content (users).

The JS code is stored on a static website from what Chrome’s developer tool request initiators
tell me (Here is an image for reference), which responds with the HTML that contains the users

The idea is to create a script that runs this static JS script that’s stored online and fetch the data about the users from it. (Image for clarification)

How do I achieve this, I’m using python. What libraries do I need etc.? Any help/advice is greatly appreciated!

HTML: use one nav bar for multiple pages

below i wanted to create one nav bar for multiple html pages for ease of use .. using JS it gives error ..it seems weird to me,also i wanted to use same method for footer as well

Access to XMLHttpRequest at 'file:///C:/Users/saad/Desktop/myhome-real-estate-free-web-template/navbar.html' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https

fetch('navbar.html')
.then(res => res.text())
.then(text => {
    let oldelem = document.querySelector("script#replace_with_navbar");
    let newelem = document.createElement("div");
    newelem.innerHTML = text;
    oldelem.parentNode.replaceChild(newelem,oldelem);
})
<body>
    
    <div id="wrapper" class="home-page">

        <header>
            <div id="nav-placeholder">

            </div>
            
            <script>
            $(function(){
              $("#nav-placeholder").load("navbar.html");
            });
            </script>
        
        </header>
    
    </body>

and my navbar.html code below:

<!DOCTYPE html>
<html lang="en">
<div class="navbar navbar-default navbar-static-top">
    <div class="container">
        <div class="navbar-header">
            <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
            <a class="navbar-brand" href="index.html"></a>
        </div>
        <div class="navbar-collapse collapse ">
            <ul class="nav navbar-nav">
                <li class="active"><a href="index.html">Home</a></li> 
                 <li class="dropdown">
                <a href="#" data-toggle="dropdown" class="dropdown-toggle">About Us <b class="caret"></b></a>
                <ul class="dropdown-menu">
                    <li><a href="about.html">Company</a></li>
                    <li><a href="#">Our Team</a></li>
                    <li><a href="#">News</a></li> 
                    <li><a href="#">Investors</a></li>
                </ul>
            </li> 
                <li><a href="services.html">Services</a></li>
                <li><a href="projects.html">Projects</a></li>
                <li><a href="pricing.html">Pricing</a></li>
                <li><a href="contact.html">Contact</a></li>
            </ul>
        </div>
    </div>
</div>

</html>

is there a way to solve this? cux i can’t figure out the problem
thanks in advance