regex replace for multiple string array javascript

I have a array of string and the patterns like #number-number

If the # and single digit number before by hyphen then replace # and add 0

If the # and two or more digit number before by hyphen then replace remove #

I got stuck and how to do in javascript

In #number,

if # and number is two or more digits before hyphen(-) remove # only 
eg
#162-7878 should be 162-7878, #12-4598866 should be 12-4598866)


if # and number is single digit before hyphen(-) remove # and add 0 
eg
#1-7878 should be 01-7878

let arrstr=["#12-1676","#02-8989898","#676-98908098","12-232","02-898988","676-98098","2-898988"]

for(let st of arrstr)
 console.log(st.replace(/#?(d)?(d-)/g ,replacer))
 
 function replacer(match, p1, p2, offset, string){
  let replaceSubString = p1 || "0";
  replaceSubString += p2;
  return replaceSubString;
 }

Make HTTP request from chrome:// URL in JavaScript

I am trying to process a bunch of data on a URL prefixed with chrome://, it being chrome://webrtc-internals/. To do this, I am sending it to a server via AJAX request from code I ran manually in the inspect tool.

But I assume for security purposes, any requests to outside URLs (ones that don’t start with chrome://) fail, and I don’t even see them in Wireshark.

const req = new XMLHttpRequest();
req.open("POST", "https://example.com", true);
req.send();

enter image description here

Is there any way I can disable this so I can make requests to other URLs?

Is it a good idea to create a programming language in Perl [closed]

I’ve been creating my own programming language for fun, and I’m using JavaScript (NodeJS).
However, as my code gets complicated, my language gets slower. So, I’m considering to convert what I have written in JavaScript to Perl (I’m not very good at C++, C, and other lower-level languages). And I have read that Perl is good at parsing and quite fast.

My question is that if it’s a good idea to write a programming language in Perl.

Why is AWSAppSyncClient IAM throwing IncompleteSignatureException error

i’m trying to implement an unauthenticated graphql request using IAM
i’m using AWSAppSyncClient from https://www.npmjs.com/package/aws-appsync

import Auth from '@aws-amplify/auth'
import AWSAppSyncClient from 'aws-appsync'
new AWSAppSyncClient({
  // @ts-ignore
  url: API_URL,
  // @ts-ignore
  region: process.env.aws_s3_region,
  // @ts-ignore
  auth: {
    type: AUTH_TYPE.AWS_IAM,
    credentials: () => Auth.currentCredentials(),
  },
  // Uses Amazon IAM credentials to authorize requests to S3.
  complexObjectsCredentials: () => Auth.currentCredentials(),
  disableOffline: true,
})

i’ve already setup unauthenticated access to AWS AppSync and configured the unauthenticated role being used.

when i tried to do a request the response was 403

{
  "errors" : [ {
    "errorType" : "IncompleteSignatureException",
    "message" : "'accept' is named as a SignedHeader, but it does not exist in the HTTP request."
  } ]
}

Request Headers:

:authority: <URL>
:method: POST
:path: /graphql
:scheme: https
accept: */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
authorization: AWS4-HMAC-SHA256 Credential=<KEY>/20220114/eu-central-1/appsync/aws4_request, SignedHeaders=accept;content-type;host;x-amz-date;x-amz-security-token, Signature=87b4a4bf3db5d7a0084491f3947bc4414890887f5cd600b2bc14612e608db5d4
cache-control: no-cache
content-length: 374
content-type: application/json; charset=UTF-8
origin: http://localhost:3001
pragma: no-cache
referer: http://localhost:3001/
sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
x-amz-date: 20220114T013513Z
x-amz-security-token: <TOKEN>
x-amz-user-agent: aws-amplify/1.8.1

Based on the error response it says that i’m not sending accept as a header but based on the headers accept is sent in the headers

How do I end the inner part of this nested loop but have the larger overall nested loop continue?

I’m working on a part of a minimax AI for a Connect Four board.

I have a parallel gameboard to test that looks like this:

let parallelBoard = [
[1,2,3,4,5,6,7],
[8,9,10,11,12,13,14],
[15,16,17,18,19,20,21],
[22,23,24,25,26,27,28],
[29,30,31,32,33,34,35],
[36,37,38,39,40,41,42]
];

The findAvailableSpots(board) function gives me an array consisting of the numbers in the first row that are still available for play. I use the first row to determine this because I splice “Red” or “Yellow” into the array whenever a spot is taken, and if the first row for that column is occupied, it cannot be selected anymore.

Then I loop through the length of available spots, and take each one as the index of the column I want to put a marker into and test.

Next, for each one of these available spots, I loop upwards from the bottom or sixth row to place the token where there is no “red” or “yellow” string in that spot.

I would like it to stop once it finds a spot and move on to the next number in the parallelAvailable array.

But if I don’t put in a return, it puts a token in every row of that column.

If I do put in a return, it breaks after splicing [parallelAvailable][0].

I would like it to run the i loop to see which row it can put a token into, and then move on to the next in [parallelAvailable][s].

What should I do? Am I placing the return in the wrong place, or is there a better way to do this altogether, maybe with another if condition?

function pickBestMove() {
//     let bestScore
//     let bestColumn

 let parallelAvailable = findAvailableSpots(parallelBoard)
 console.log(parallelAvailable)

 for (s=0; s<parallelAvailable.length; s++) {
    let i;
    let j = parseInt(parallelAvailable[s] - 1)
    console.log(j)
    for (i = 5; i > -1; i--) 
        {if (Number.isInteger(parallelBoard[i][j])) {
            parallelBoard[i].splice((j), 1, currentPlayer)
            }

    //         let positionScore = scorePosition (parallelBoard, currentPlayer)
    //         console.log(gameboard[i][j] + " gets " + positionScore)
    //         parallelBoard[i].splice((indexPick), 1, gameboard[i][j])
            
    //             if (positionScore > bestScore) {
    //                 bestScore = score
    //                 console.log(bestScore)
    //                 bestColumn = s
    //                 console.log(bestColumn)
    //             }
    //         // return
    //        }
    //     }
    }
    // return bestColumn
    console.log(parallelBoard)}
};

Flickering site

On reloading, the site is prickly and flickering. I think it’s because of the dark theme script. But if you write a line at the beginning, before the tag does not exist script. Then the problem disappears. But that’s not right. All showed in the video. I hope it can be resolved.

https://youtu.be/c1ab5ER4qmw

dark.js:

// function to set a given theme/color-scheme
function setTheme(themeName) {
    localStorage.setItem('theme', themeName);
    document.documentElement.className = themeName;
    document.getElementById("sunimgid");
}

// function to toggle between light and dark theme
function toggleTheme() {
    if (localStorage.getItem('theme') === 'theme-dark') {
        setTheme('theme-light');
        document.getElementById("sunimgid").setAttribute("src", "/images/sunny.png");
    } else {
        setTheme('theme-dark');
        document.getElementById("sunimgid").setAttribute("src", "/images/moon.png");
    }
}

// Immediately invoked function to set the theme on initial load
(function () {
    if (localStorage.getItem('theme') === 'theme-dark') {
        setTheme('theme-dark');
        document.getElementById("sunimgid").setAttribute("src", "/images/moon.png");
    } else {
        setTheme('theme-light');
        document.getElementById("sunimgid").setAttribute("src", "/images/sunny.png");
    }
})();

How to disable onclick in JavaScript?

I have been trying to do something like this.

I have a working code, (this is just example), when I click on the button the game starts.

In this example I have a loop, that if condition is true, I want to disable the option to click on the button.

I have seen that this el.disabled = true; / e.disabled = true; / td.disabled = true; (Is it possible to disable onclick without altering its function?) should do the job, but this doesn’t work for me. Why is that? Or maybe there is another way to do that? (this is not the whole code, only the important parts)

<!DOCTYPE html>
<html>
<head></head>
<body>
  <script type="text/javascript">
    function startgame() {
      var ChessTable;
      var counter = 0;
      var center = document.createElement('center');
      ChessTable = document.createElement('table');

      for (var i = 0; i < 8; i++) {
        var tr = document.createElement('tr');
        for (var j = 0; j < 8; j++) {
          var td = document.createElement('td');
          td.setAttribute('id', counter)
          td.addEventListener('click', s)
        }
        ChessTable.appendChild(tr);
      }
      center.appendChild(ChessTable);
      ChessTable.setAttribute('cellspacing', '0');
      ChessTable.setAttribute('width', '270px');
      document.body.appendChild(center);
    }

    var counterforplayer = 0;

    function s(e) {
      event.target.style.backgroundColor = "green";

      if (counterforplayer >= 5) {
        alert("you cannot play anymore")
        e.disabled = true;
        counterforplayer++;
      }
    }
    }
  </script>
  <button onclick="startgame()">Click me to start a new game</button>
  <div id="container">
    <div id="ph1">
    </div>
  </div>
</body>
</html>

How to get ens username using ensjs

On the ensjs README, I see this code snippet:

import ENS, { getEnsAddress } from '@ensdomains/ensjs'



const ens = new ENS({ provider, ensAddress: getEnsAddress('1') })

ens.name('resolver.eth').getAddress() // 0x123

However, when I add that snippet to my webapp, like this:

const ens = new ENS({ provider, ensAddress: getEnsAddress('1') });
const name = ens.name('resolver.eth').getAddress();
name.then((str) => {
  console.log(str); // this is another hash, not my .ens username
});

My dev console logs another 0x... hash, not my .ens username

How do I get my username using this library?

Is there a better way of handling folder structure in Express Handlebars with views

I’m wondering if there is a better way of rendering my html without having to always have my files named differently. If there’s any way handlebars can know I want this file in this folder to be rendered rather than searching everywhere and having same-name conflicts..Any help would be appreciated. Here’s an example of code. Thank you!

//Setting up configuration views here //
const hbs = exphbs.create({ helpers, defaultLayout: 'main', extname: '.handlebars' });
app.engine('handlebars', hbs.engine);


//Handlebar files must be named differently //
app.set('views', [
    path.join(__dirname, 'views/corporate'),
    path.join(__dirname, 'views/help-center'),
  ]);
  
app.set('view engine', 'handlebars');

And then my view folder is

enter image description here

And here is an example of one of my routes

const router = require("express").Router();
const config = require("../../lib/config");
const { appUrl } = config;


router.get("/", (req, res) => {
    res.render("corpIndex", {
      appUrl
    });
  });

  module.exports = router;

JavaScript React component takes dictionary creates the aside bar with the li and link using JSX

I’m learning react and creating a blog along the way and on my articles I want to create a component that would take in a prop dictionary and the key would be the link the user can see and click on and the value would be the link for my routing. Thanks for any help.

import React from 'react'
import styled from 'styled-components'
import { Link } from 'react-router-dom'


function AsideBar(props) {
    return (
        <Container>
            <Sidebar>
                <Nav>
                    {for (const property in props.link_short){
                        <Link='{props.link_short[property]}'><li>property</li></Link>
                    }}
                </Nav>
            </Sidebar>
        </Container>
    )
}

export default AsideBar

PKG Failed to make Bytecode

I am getting this warning when I try and run .. pkg index.js -t macOS

node v17.3.1
[email protected]

Warning Failed to make bytecode node17-arm64 for file /snapshot/______/index.js

was hoping anyone could help,

I have also tried to use -b and got

Error: ENOENT: no such file or directory, open ‘/var/folders/fy/c5tgsjcj63q73kfvg_dd53fh0000gn/T/pkg.d5ef9dd92b18360a4ff95824/node/out/Release/node

thank you

Loop iteration with time interval before passing value to included function

I’m trying to figure out how to set time out for function inside the loop iteration in Ionic TypeScript application.

setInterval makes equal time interval with calling the function in endless repetition:

   setInterval(() => {
      this.myFunc1(val);
   }, 800);

setTimeout gives required result if listed sequentially:

   setTimeout(() => {
      this.myFunc1(val);
   }, 800); 

   setTimeout(() => {
      this.myFunc1(val);
   }, 1200); 

but how to loop with time interval trough the updated list and wait while pass second value val to the function, or call myFunc1 when it will be finished in previous iteration:

 async myFunc2() {
    for (let val of this.myValueList) {
        /// wait for 5 sec or wait for finishing process, then pass value calling function:  
        this.myFunc1(val);          
    }
  }

Understanding Context & Array Types

Good Afternoon,

I am in the process of setting up my context for my application but running into an issue with the information display after the initial load. The initial application load then navigating to the products page everything displays correctly, but if I was to reload the page on Products screen the information is missing. If I was to reload the page on the Products screen, then click the navigation click to that same page the information will load correctly.

index.js

//Context
import UserContextProvider from "./components/context/UserContext";
import ProductsContextProvider from "./components/context/ProductsContext";
import CartContextProvider from "./components/context/CartContext";

ReactDOM.render(
  <BrowserRouter>
    <UserContextProvider>
      <ProductsContextProvider>
        <CartContextProvider>
          <App />
        </CartContextProvider>
      </ProductsContextProvider>
    </UserContextProvider>
  </BrowserRouter>,
  document.getElementById("root")
);

app.js

const App = () => {
  return (
    <div className="App">
      <Switch>
        <Route exact path="/" component={HomePageScreen} />
        <Route exact path="/shop/bands" component={BandsPageScreen} />
        <Route exact path="/shop/photo" component={InsertPageScreen} />
        <Route exact path="/shop/products" component={ProductScreen} />
     </Switch>
    </div>
  );
};

productContext.js

import React, { createContext, useState } from "react";
import axios from "axios";

export const ProductsContext = createContext();

const initialState = [];

const ProductsContextProvider = ({ children }) => {
  const GetProducts = async () => {
    await axios.get("/api/products/find/all").then((response) => {
      if (response.data.results) {
        for (var i = 0; i < response.data.results.length; i++) {
          initialState.push(response.data.results[i]);
        }
      }
    });
  };
  GetProducts();
  const [products] = useState(initialState);
  console.log("Setting Product Context");

  return (
    <ProductsContext.Provider value={{ products }}>
      {children}
    </ProductsContext.Provider>
  );
};

export default ProductsContextProvider;

productScreen.js

import { React, useContext, useState, useEffect } from "react";
import axios from "axios";
import HeaderBar from "./modules/header";
import { Button, Image, Icon, Card, Container } from "semantic-ui-react";
import Temp from "../../img/tempphoto.png";

//Context Files
import { UserContext } from "../context/UserContext";
import { ProductsContext } from "../context/ProductsContext";

const ProductScreen = () => {
  const activeScreen = "productScreen";
  const { products } = useContext(ProductsContext);

  console.log(products);

  const allProducts = products.map((product) => (
    <Card raised key={product.sku}>
      <Image src={Temp} wrapped ui={false}></Image>
      <Card.Content>
        <Card.Header>{product.title}</Card.Header>
        <Card.Meta>
          Sku: {product.sku} | Color: {product.color}
        </Card.Meta>
        <Card.Description> {product.description}</Card.Description>
      </Card.Content>
      <Card.Content extra>
        {/* <Button color="green" onClick={(e) => addItemCart(product._id, e)}>
          <Icon name="add to cart"></Icon>Add to Card
        </Button> */}
      </Card.Content>
    </Card>
  ));

  return (
    <>
      <HeaderBar screen={activeScreen} />
      <Container>
        <Card.Group>{allProducts}</Card.Group>
      </Container>
    </>
  );
};

export default ProductScreen;

  1. Reload Product Screen -> First Array after reload
  2. Click the Navigation Link -> Second Array after click (Everything loads correctly here).

enter image description here

Not sure what I am doing wrong but the information is being stored within the context from what I can see.

Реализация статичных ссылок с функцией onclick [closed]

Как передать аргумент функцию onclick при статичном формировании?

function linkHref(link, name){
return (‘<a href=”#” type=”button” onclick=selectTheme(‘+ link + ‘)>’+ name + ”);
}

Источник: https://codereview.stackexchange.com/questions/176498/javascript-sidebar-menu-with-subitems-from-a-json-object

apply function from methods to reverse string in paragraph in vue.js

Dears, I have tried to apply function to reverse string in paragraph text in vue.js,
I have created function to reverse words in methods called (reverseword) and added it

card using :rule=”reverseword()”,but it does not work. your support is highly appreciated
Code:

    <div class="post-box">
        <span class="post-viwes">{{viwes}}</span>
        <h3 class="post-title">{{title}}</h3>       
         <span class="post-date">{{date}}</span>
        <p class="post-content">{{content}}</p>
        <div class="row">
            <div class = "col-sm-6 text-right">
              <span class="post-author">{{author}} </span>
            </div>
            <div class = "col-sm-6 text-right" :rules="reverseword()">
              <span class="post-category"  >{{category.toUpperCase()}}</span>
            </div>
        </div>
        )
    </div>
</template>
<script>
export default {
    props:["viwes","title","date","content","author","category"],
    name:"posts",
      methods: {
        reverseWord: function () {
          this.category = this.category.split('').reverse().join('')
    }   
}};
</script>```