Modify Class Method Definition in TS or JS

I have a class having structure like :

class A {
    constructor() {}
    myMethod() {
      console.log('in my method');
    }
}

I want to make a method that will accept className and methodName like :

modifyClassMethod(className, methodName)

This method should wrap the whole body of methodName specified into a callback during runtime.

So if I do,

modifyClassMethod(A, myMethod)

Now during runtime the body of myMethod of class A should get changed to

myMethod() {
   nr.recordMe('here', {
      console.log('in my method').
   })
} 

Now when I will create a new object of A class, then I will get modified value of myMethod.

How can I achieve this in TS or JS ?.

VS Code & Node.js: Use console() instead of consol.log()?

I’m writing JavaScript expressions to be used in specialized geospatial software.

In the geospatial software, only console() is valid, not console.log().


As I’m working, I’m debugging my geospatial scripts in VS Code using Node.JS (since the geospatial software doesn’t have linting functionality, etc.).

It’s my understanding that Node.js uses console.log() syntax, not console().

Therefore, when moving the script back and forth between the two programs, I need to do a find and replace to switch from console.log() to console(). This is becoming tedius.


Question:

In VS Code / Node.js, is there a way to use console() instead of console.log()? That would make things a lot easier when developing my scripts. Unfortunately, I can’t control things on the geospatial software side.

I’m a novice, so layman’s terms would be appreciated.

React Route for NAVLINK Received TRUE for a non-boolean attribute

I am using Navlink

import { NavLink } from "react-router-dom";
const MainMenu = () => {
    return (
        <nav className="main-menu d-none d-lg-block">
            <ul className="d-flex">
                <li>
                    <NavLink exact to="/">
                        Home
                    </NavLink>
                </li>
            </ul>
</nav>)};

I am getting a warning in my console saying

bundle.js:30762 Warning: Received `true` for a non-boolean attribute `exact`.
If you want to write it to the DOM, pass a string instead: exact="true" or exact={value.toString()}.
at a
at LinkWithRef (http://localhost:3000/static/js/bundle.js:59806:5)
at NavLinkWithRef (http://localhost:3000/static/js/bundle.js:59852:21)
at li
at div
at header
at Header (http://localhost:3000/static/js/bundle.js:11996:91)
at Routes (http://localhost:3000/static/js/bundle.js:60295:5)
at NavScrollTop (http://localhost:3000/static/js/bundle.js:3960:51)
at Wrapper (http://localhost:3000/static/js/bundle.js:4034:78)
at Router (http://localhost:3000/static/js/bundle.js:60228:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:59704:5)
at App

Any idea how can I fix it ? I tried other stack overflow details but could not come up with anything !! Thanks in Advance

Hide payment methods based select option?

Hi i want to show show payments methods based on country option selected.
i have following code.

FOR COUNTRY SELECTION

          $countries = json_decode(file_get_contents(resource_path('views/partials/country.json')));
   


<select name="country" id="countriess" class="form-control">
                         
                 <option value="nil"> -- select an option -- </option>
                        @foreach($countries as $key => $country)
                      
                            <option data-mobile_code="{{ $country->dial_code }}" value="{{ $country->country }}" data-code="{{ $key }}">{{ __($country->country) }}</option>
                         
                        @endforeach
                    </select>

To LOAD GATEWAYS

@foreach($gatewayCurrency as $data) // $data->country has country name from database

@endforeach

I have tried following using jquery

<script type="text/javascript">
           
   $('#countriess').on('change',function(){
     if("{{$data->country}}"!=$(this).val()){
            
      $("#country_{{$data->country}}").hide();
      
        }
       else if("{{$data->country}}"== $(this).val()){
           
        $("#country_{{$data->country}}").show();
        
        }
else if("{{$data->country}}"!=$(this).val()){
            
      $("#country_{{$data->country}}").hide();
      
        }
    });

        
        </script>

but issue is shows some other countries gateways as well if they are 2nd last in database

How to control microphone output from JavaScript?

I am building an app, which needs to record a microphone. I want users to control microphone output from the app, mute/unmute it.

Is it possible ? If yes, how can I achieve that ?

React version of the project

   "react": "^17.0.2",

Code where I get an microphono input

const handleRecord = async () => {
    setIsAudioLoading(true);
    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
    const mediaRecorder = new MediaRecorder(stream, { mimeType: "audio/wav" });
    let orderNumber = 0;
    let chunks = [];

    mediaRecorder.ondataavailable = function (e) {
      chunks.push(e.data);
    };
    mediaRecorder.onstop = function () {
      const blob = new Blob(chunks, { type: "audio/wav" });
      streamChunk(blob, orderNumber, "mic");
      chunks = [];
    };

    mediaRecorder.start();

    setStopMic(() => () => {
      setIsMicPaused(true);
      setCurrentAudioTime(lastChunkSecondRef.current - 1.5);
      isMicPausedRef.current = true;
      mediaRecorder.stop();
    });
    setStartMic(() => () => {
      setIsMicPaused(false);
      isMicPausedRef.current = false;
      mediaRecorder.start();
    });

    setInterval(function () {
      if (!isMicPausedRef.current) {
        orderNumber++;
        mediaRecorder.stop();
        mediaRecorder.start();
      }
    }, MIC_INTERVAL);
  };

How can I use page.type() inside The page.$eval() in puppeteer?

    const browser = await puppeteerExtra.launch({
      "dumpio": true, // to log
      "headless": false, // to open browser in background process
      "devtools": false, // do disable dev-tools
      "ignoreHTTPSErrors": true, // to ignore webpage https error
      "args": [
        "--disable-setuid-sandbox",
        '--no-sandbox',
        '--disable-features=IsolateOrigins,site-per-process',
      ],
    });
    let page = await browser.newPage();
    await page.setUserAgent(userAgent.toString());
    await page.goto(url, { waitUntil: 'networkidle2' });
    await page.waitForTimeout(1000);
    await page.setCacheEnabled(false);
    await page.evaluate(() => {
      let modelSONATA = document.querySelector('input[id="model-SONATA"]');
      modelSONATA.click();
    });

i Want to Use page.evaluate() inside page.type so Please Help Me What is Way to Use Inside page.type()

clearInterval when you choose GOOD or WRONG answer JavaScript

Please help, I don’t know how to clear Interval when i choose good or wrong answer. Without choosing answer Interval clear when time goes to 0. When you choose a good option or a bad one, it moves to the next artboard, but the old interval still remains in the computer’s memory. I am not a coding specialist, which can be seen from my coding method… Game made in Adobe Animate.

createjs.Touch.enable(stage);
stage.enableMouseOver();

this.stop();
console.log("enter game")

let selected = [];
let finalMove = null;
let numberOfSec = 20;
//let level = 1;
//let score = 0;
this.timer.text = numberOfSec;
this.score.text = counterWin;

this.timer.visible = true;
this.timeplace.visible = false;

const timerInterval = setInterval(() => {
        numberOfSec--
    this.timer.text = numberOfSec;
    if(numberOfSec==5){
        this.timer.visible = true;
        this.timeplace.visible = true;
        createjs.Sound.play('clock');
        console.log("clock 5 to 0")
    }
    if(numberOfSec==0){
        this.gotoAndStop('next1')
        clearInterval(numberOfSec);
        console.log(numberOfSec);
        console.log("enter to page next1")
        createjs.Sound.stop();
    }
},1000)


const elements1 = [
this.mc1,
this.mc2,
this.mc3,
this.mc4,
this.mc5,
]


const places = [
    this.card1, 
    this.card2, 
    this.card3, 
    this.card4,
    this.card5,
];
    

shuffle(places);

elements1.forEach((element, index) => {
    element.x = places[index].x;
    element.y = places[index].y;
})


function shuffle(a) {
    let j, x, i;
    for (i = a.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        x = a[i];
        a[i] = a[j];
        a[j] = x;
    }
    return a;
}


//var clear = clearInterval(numberOfSec);
var root = this;

elements1.forEach(element => {
    element.addEventListener('click', (event) =>{
    
        if (event.currentTarget.name === 'mc5'){
            console.log("GOOD")
            counterWin+=2;
            //clearInterval(numberOfSec);
            //root.clear;
            console.log(clear);
            this.score.text = counterWin;
            //createjs.Sound.stop();
            createjs.Sound.play('good');
            this.play();
            createjs.Sound.stop();
            console.log(counterWin);
        }else{
            console.log("WRONG")
            createjs.Sound.play('wrong');
            //clearInterval(numberOfSec);
            //root.clear;
            createjs.Sound.stop();
            this.play();
        }
        
        
    });
    
});

How can I replace a call argument of a function with Sinon?

I am using sinon to make my tests, and I faced a problem that I can’t find a proper solution

lets say, for simplicity, that I want, when I call console.log(),that the proper console.log receives the argument that I want in my test.

I have tryied:

Sinon.replace( console, 'log', () => console.log('mytestparam'))

Sinon.stub( console, 'log').callsFake( console.log('mytestparam'))

But it creates some kind of circular dependency that crashes

I cant simply make a full stub of the function, because it contains code that I want to run, I only want to replace the argument used for the call.

I have researched the sinon docs but I can’t find any function that allows to call the original function changing the args

Any idea?

How to get posts from the next pagination page using ajax?

There is a category on wordpress where posts and standard pagination 1, 2, 3, etc. are displayed. I made that when I clicked on the pagination, an Ajax request was triggered and from the next page of the pagination the posts were inserted into the page, but for some reason all the posts are displayed. Where am I wrong?

Post output code with pagination

<?php
$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
$args = array(
    'cat' => $current_cat_id,
    'posts_per_page' => 1,
    'paged'          => $paged,
);

$query = new WP_Query( $args );
// Цикл
if ( $query->have_posts() ) {
    while ( $query->have_posts() ) {
    $query->the_post();

?>

<a class="post-list-item mb-32" href="<?php the_permalink(); ?>">
    <div class="post">
        <div class="post-header mb-32">
            <div class="post-date">Jan 4, 2022</div>
            <h3 class="post-title"><?php the_title() ?></h3>
            <div class="post-short-info">
                <?php the_field('kratkoe_opisanie'); ?></div>
        </div>
        <div class="post-thumbnail">
            <div class="image-inner"><img class="image"
                    src="<?php echo get_the_post_thumbnail_url(); ?>">
            </div>
        </div><span class="read-more">Read more</span>
    </div>
</a>



<?php
}
} else {
    // Постов не найдено
}
// Возвращаем оригинальные данные поста. Сбрасываем $post.
wp_reset_postdata();

$big = 999999999; // уникальное число

$pagination =  paginate_links( array(
    'base'    => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
    'current' => max( 1, get_query_var('paged') ),
    'total'   => $query->max_num_pages
) );


?>

</div>

<?php
echo "<div class='pagination'>" . $pagination . "</div>";

?>

Ajax javascript

<script type="text/javascript">

        $('.pagination a').click(function(e) {

            e.preventDefault(); // don't trigger page reload

            if($(this).hasClass('active')) {
                return; // don't do anything if click on current page
            }

            $.post(
                '<?php echo admin_url('admin-ajax.php'); ?>', // get admin-ajax.php url
                {
                    action: 'ajax_pagination',
                    page: parseInt($(this).attr('data-page')), // get page number for "data-page" attribute
                    posts_per_page: <?php echo get_option('posts_per_page'); ?>
                },
                function(data) {
                    $('.posts-list').html(data); // replace posts with new one
                    console.log(data);
                }
            );
        });
</script>

Functions.php

function my_ajax_navigation() {
    $requested_page = intval($_POST['page']);
    $posts_per_page = intval($_POST['posts_per_page']) - 1;
    $posts = get_posts(array(
        'cat' => 6,
        'posts_per_page' => $posts_per_page,
        'offset' => $page * $posts_per_page
    ));
    foreach ($posts as $post) {
        setup_postdata( $post );
        echo $post->ID;
    }
    exit;
}
add_action( 'wp_ajax_ajax_pagination', 'my_ajax_navigation' );
add_action( 'wp_ajax_nopriv_ajax_paginationr', 'my_ajax_navigation' );

Fill diagonals of array with same values in JS

I have an array of n x n elements, and I want to fill its diagonals with the same values as follows:

ex. n = 3:

0 1 2
3 0 1
4 3 0

arr = [0, 1, 2, 3, 0, 1, 4, 3, 0]

ex. n = 4;

0 1 2 3
4 0 1 2
5 4 0 1
6 5 4 0

arr = [0, 1, 2, 3, 4, 0, 1, 2, 5, 4, 0, 1, 6, 5, 4, 0]

I was able to fill upper half of the array using the following code, but got stuck with the rest:

var n = 3;
var values = [0, 1, 2, 3, 4]

var a = [];
for (var i = 0; i < n; i++) {
    for (var j = 0; j < n; j++) {
        a[j * n + i] = values[i - j];
    }
}

/* Result
0 1 2
  0 1
    0

arr = [0, 1, 2, undefined, 0, 1, undefined, undefined, 0] */

Length of values array is 2 * n - 1, which is the count of diagonals of the array.

Any ideas how to fill the whole array?

Angular – AWS Amplify amplify-authenticator crashes the form when the ‘Code’ I send is wrong

I have an amplify-authenticator form which I use to reset the password. If I enter a wrong code, I get a response from the API which says

CodeMismatchException: Invalid verification code provided, please try again.

which is correct, but the entire form then freezes and I also get this message in the console of the browser:

Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading ‘authAttributes’)
TypeError: Cannot read properties of undefined (reading ‘authAttributes’)
at actorDoneData (index.js:2:34774)

which points to webpack:///node_modules/@aws-amplify/ui/dist/esm/index.js

This is the code I have:

HTML

<amplify-authenticator [services]="services" initialState="resetPassword"></amplify-authenticator>

TS

    this.services = {
      async handleForgotPasswordSubmit(formData): Promise<void> {
        const { username, code, password } = formData;

        return Auth.forgotPasswordSubmit(username, code, password)
          .then(res => {
            //  Do something on success
          })
          .catch(err => {
            // The ERROR is here
            console.log(err);
          });
      }
    };

Please advise what can I do to avoid the form freeze problem. Thanks!

How to fix JsonWebTokenError in node.js using express and reactjs?

I am trying to show the page only if the Jsonwebtoken is verified and the user is logged on to the website, else show him the sign-in page.

However, I can see the token is generated in MongoDB, and also when I console log I can see that it is all good. But the issue is when I try to verify it using an already generated jwt token i.e.

req.cookies.signinToken

it shows an error.

Please the detail code below:

On app.js

const dotenv = require("dotenv");
const mongoose = require("mongoose");
const express = require("express");
const app = express();

const jwt = require("jsonwebtoken");
const cookieParser = require("cookie-parser");

dotenv.config({ path: "./config.env" });
require("./db/connection");

app.use(express.json());
app.use(cookieParser());

app.use(require("./router/route"));

const PORT = process.env.PORT;

app.listen(5000, () => {
    console.log(`server running on ${PORT}`);
});

On route.js

const express = require("express");
const bcrypt = require("bcrypt");
const router = express.Router();
const jwt = require("jsonwebtoken");

require("../db/connection");
const User = require("../model/newUserSchema");
const auth = require("../middleware/auth");

// router.get("/", (req, res) => {
//     res.send("hello am backend sever");
// });

//Signup or  Register Part
router.post("/signup", async (req, res) => {
    const { username, email, cpassword, retypePassword } = req.body;

    if (!username || !email || !cpassword || !retypePassword) {
        return res.status(422).json({ error: "please enter valid details" });
    }

    try {
        const UserExist = await User.findOne({ email: email });

        if (UserExist) {
            return res.status(422).json({ error: "email already exist" });
        } else if (cpassword !== retypePassword) {
            return res.status(422).json({ error: "password incorrect" });
        } else {
            const user = new User({
                username,
                email,
                cpassword,
                retypePassword,
            });

            const userResgister = await user.save();

            if (userResgister) {
                return res.status(201).json({ message: "signup successfully" });
            }
        }
    } catch (error) {
        console.log(error);
    }
});

//Login Part
router.post("/signin", async (req, res) => {
    try {
        const { email, cpassword } = req.body;

        if (!email || !cpassword) {
            return res.status(400).json({ error: " please enter valid credentials" });
        }

        const userLogin = await User.findOne({ email: email });

        const token = userLogin.generateAuthToken();

        res.cookie("signinToken", token, {
            expires: new Date(Date.now() + 25892000000),
            httpOnly: true,
        });

        if (userLogin) {
            const isMatch = await bcrypt.compare(cpassword, userLogin.cpassword);

            if (isMatch) {
                return res.status(200).json({ message: "sigin in scuccessfully" });
            } else {
                return res.status(400).json({ error: " Invalid credentials" });
            }
        } else {
            return res.status(400).json({ error: "  Invalid credentials " });
        }
    } catch (error) {
        console.log(error);
    }
});

//watchlistpage
router.get("/watchlist", auth, (req, res) => {
    console.log("  this is jwt token test  " + req.cookies.signinToken);
    res.send(req.rootuser);
    console.log(req.rootuser);
});

module.exports = router;

On newUserSchema.js:

const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");

const newUserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
    },
    email: {
        type: String,
        required: true,
    },
    cpassword: {
        type: String,
        required: true,
    },
    retypePassword: {
        type: String,
        required: true,
    },
    tokens: [
        {
            token: {
                type: String,
                required: true,
            },
        },
    ],
});

newUserSchema.pre("save", async function (next) {
    if (this.isModified("cpassword")) {
        this.cpassword = await bcrypt.hash(this.cpassword, 12);
        this.retypePassword = await bcrypt.hash(this.retypePassword, 12);
    }
    next();
});

newUserSchema.methods.generateAuthToken = async function () {
    try {
        let token = jwt.sign({ _id: this._id }, process.env.SECRETKEY);
        this.tokens = this.tokens.concat({ token: token });
        await this.save();
        return token;
    } catch (error) {
        console.log(error);
    }
};

const User = mongoose.model("newUser", newUserSchema);

module.exports = User;

On auth.js (this is also my middleware)

    const jwt = require("jsonwebtoken");
const User = require("../model/newUserSchema");

const Auth = async (req, res, next) => {
    try {
        console.log(JSON.stringify(req.cookies.signinToken) + "  this is jwt token test");
        const token = req.cookies.signinToken;
        const verifytoken = jwt.verify(token, process.env.SECRETKEY);

        const rootuser = await User.findOne({ _id: verifytoken._id, "tokens.token": token });

        if (!rootuser) {
            throw new Error("user not found");
        }

        req.token = token;
        req.rootuser = rootuser;
        req.UserID = rootuser._id;

        next();
    } catch (error) {
        res.status(401).send("Unauthorized access");
        console.log(error);
    }
};

module.exports = Auth;

The API call result in postman

postmanimg

The terminal error :

terminalimg

Could you please help to correct the error also please let me know why is this error coming?

Thanks a million in advance for any tips or suggestions.