How read value from uri key json

i have this object

{
  'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier': '918312asdasc812',
  'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name': 'Login1',
  'http://schemas.microsoft.com/ws/2008/06/identity/claims/role': 'User'
}

How read value for key ‘http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier’?

Metamask accounts do not disconnect when connected from injected code via chrome extension

I am injecting some javascript into a page from a chrome extension. In my injected code, I am getting a list of accounts from metamask with:

ethereum.request({ method: 'eth_requestAccounts' })

The first time I ran this, it prompted me to connect through Metamask as expected. Now I am not able to disconnect or change my account though. I have disconnected through metamask, but when I run this request again, the account is still listed even though it’s disconnected. How can I force it to clear this disconnected account? It is still there even after reloading the extension I’m working on.

Everything works as expected when I debug from the console, so I’m not sure what’s going on. It seems like something funny due to the extension/injection.

Cordova 10 unable to post ajax to http url

I’m trying to send json data to an http url without success (I tried to send same data to an other https with success).
I have this settings:
config.xml

<access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />

AndroidManifest.xml

 android:usesCleartextTraffic="true"

html header

$.ajax({
                                    type: "GET",
                                    url: url,
                                    dataType: "jsonp",
                                    jsonp: 'callback',
                                    crossDomain: true,
                                    async: true,
                                    data: {id:results.rows.item(i).id, bolla:results.rows.item(i).bolla, anno:results.rows.item(i).anno, magazzino:results.rows.item(i). magazzino, articolo:results.rows.item(i).articolo, quantita:results.rows.item(i).quantita, term:terminale},
                                    success: function(data) {
                                        console.log(data)
                                    },
                                    error:function(xhr,textStatus,err)
                                    {
                                        alert("readyState: " + xhr.readyState);
                                        alert("responseText: "+ xhr.responseText);
                                        alert("status: " + xhr.status);
                                        alert("text status: " + textStatus);
                                        alert("error: " + err);
                                    }
                            });

If I use json it returns devicereadystate=0 and error if I use jsonp it returns devicereadystate=4 and error 404 (the url is correct if I paste to a browser it works)

Error : Operation users.insertMany() buffering timed out after 10000ms when using mongoose in the following code

I am having a hard time finding an error in this following code i wanted to connect to a database and add some data to it but iam getting an error whose info is specified below

**This is the code of Server.jswhich is the server of the application **

import userdata from './userdata.js';
import data from "./data.js"
import mongoose  from 'mongoose';
import userrouter from './routers/userrouter.js';


const app=express();

mongoose.connect('mongodb://localhost/purpleshades',{
    useNewUrlParser:true,
    useUnifiedTopology:true,
    useCreateIndex:true
})

app.use(express.json());
app.use(express.urlencoded({ extended: true }))

app.use('/api/users',userrouter)
app.use((err,req,res,next)=>{
    res.status(500).send({message:err.message})
})
const port=process.env.PORT || 5000
app.listen(5000,()=>{
    console.log(`serve at http://localhost:${port}`);
})

This is the code of the userserver.js which is the router file of the user router which handles the user many request

import userdata from "../userdata.js";
import User from "../models/usermodel.js";
import expressAsyncHandler from "express-async-handler";

const userrouter=express.Router()

userrouter.get('/seed',expressAsyncHandler( async(req,res)=>{
    const createdusers=await User.insertMany(userdata.users)
    res.send({createdusers})
}))

export default userrouter 

The data file is asfollows which is called userdata.js

const userdata={
    users:[
        {
            name:'Prashanth',
            email:'[email protected]',
            password:bcrypt.hashSync('1234',8),
            isadmin:true
        },
        {
            name:'ramesh',
            email:'[email protected]',
            password:bcrypt.hashSync('5678',8),
            isadmin:true
        },
        {
            name:'jhon',
            email:'[email protected]',
            password:bcrypt.hashSync('91011',8),
            isadmin:true
        },
        {
            name:'cristine',
            email:'[email protected]',
            password:bcrypt.hashSync('1213',8),
            isadmin:true
        }

    ]
}
export default userdata

Now the error is as follows
"message": "Operation `users.insertMany()` buffering timed out after 10000ms"

How do I get rid of this error.

How to replace image of SVG with inline SVG but keep dropdown-toggle class

How can I replace my current img of an SVG to use an inline SVG but ensure that I can apply a class to it in order to keep the dropdown toggle functionality and custom css styles?

Currently Using:

<img src="/assets/images/icons/close.svg" class="dropdown-toggle" alt="close" />

Want to use:

<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M15.875 1.95648L14.0435 0.125L8 6.16852L1.95648 0.125L0.125 1.95648L6.16852 8L0.125 14.0435L1.95648 15.875L8 9.83148L14.0435 15.875L15.875 14.0435L9.83148 8L15.875 1.95648Z" fill="black"/>
</svg>

but also keep a class applied to it, for JS and CSS purposes.

NuxtJS (VueJS) v-model issues

I have a parent component calling the textInput component:

<template>
  <TextInput
  v-model.lazy="fields.title"
  container-text="Hero Title"
  mobile-container-text="Hero Title Mobile"
  :mobile-text="fields.mobileTitle"
  inline="true" />
</template>

<script>
import TextInput from "@/components/core/inputs/TextInput"
import { libComponentMixin } from "@/shared/mixins"

export default {
  name: "test",
  components: {
    TextInput
  },
  mixins: [libComponentMixin],
  data: function () {
    return {
      fields: {
        title: "Hero Headline",
        mobileTitle: "Hero Headline Mobile"
      }
    }
  }
}
</script>

And within the TextInput component I have the following:

<template>
  <span
    v-if="$store.state.editMode && !$store.state.previewMode"
    class="edit"
    :class="{
      selected: $store.state.editingId === id,
    }"
  >
    <span @click="onShowControls" v-html="parsedValue"></span>
    <portal v-if="$store.state.editingId === id" to="controls">
      <div class="white-area">
        <h2>{{ containerText ? `${containerText}` : "Textarea" }}</h2>
        <slot></slot>
        <VueEditor
          ref="quillEditor"
          v-model="editorValue"
          :editor-options="editorSettings"
        />
      </div>
      <div v-if="mobileText">
        <h2>{{ mobileContainerText ? `${mobileContainerText}` : "Textarea" }}</h2>
        <slot></slot>
        <VueEditor
          ref="quillEditor"
          v-model="mobileText"
          :editor-options="editorSettings"
        />
      </div>
    </portal>
  </span>
  <span v-else v-html="parsedValue"></span>
</template>

<script>
import { VueEditor } from "vue2-editor"
import { debounce } from "lodash"
import { getUID } from "@/shared/utils"

export default {
  name: "TextInput",
  components: {
    VueEditor,
  },
  props: [
    "value",
    "itemIndex",
    "inline",
    "linkStyle",
    "supStyle",
    "containerText",
    "miniMode",
    "staticText",
    "mobileText",
    "mobileContainerText"
  ],
  data() {
    return {
      id: getUID(),
      editorSettings: {
        modules: {
          toolbar: !this.miniMode ? customToolbarConfig : false,
        },
      },
    }
  },
  computed: {
    editorValue: {
      get() {
        return this.itemIndex !== undefined
          ? this.value[this.itemIndex].text
          : this.value
      },
      set: debounce(function (newValue) {
        if (this.itemIndex !== undefined) {
          this.$emit(
            "input",
            this.value.map((item, i) =>
              this.itemIndex === i ? { ...item, text: newValue } : item
            )
          )
        } else {
          this.$emit("input", newValue)
        }
      }, 400),
    },
    editorValueMobile: {
      get() {
        return this.itemIndex !== undefined
          ? this.value[this.itemIndex].text
          : this.value
      },
      set: debounce(function (newValue) {
        if (this.itemIndex !== undefined) {
          this.$emit(
            "input",
            this.value.map((item, i) =>
              this.itemIndex === i ? { ...item, text: newValue } : item
            )
          )
        } else {
          this.$emit("input", newValue)
        }
      }, 400),
    }
  },
  methods: {
    insertMarkup(markup) {
      const quill = this.$refs.quillEditor.quill
      const pos = quill.getSelection(true).index
      this.$refs.quillEditor.quill.clipboard.dangerouslyPasteHTML(pos, markup)
    },
    onShowControls() {
      this.$store.commit("setEditingId", this.id)
    },
  },
}
</script>

<style lang="scss" scoped>
.edit {
  display: inline-block;
  border: 3px dashed transparent;
  &:hover {
    border: 3px dashed $button-secondary;
  }
  &.selected {
    border: 3px dashed $red;
  }
}
</style>

I am trying to update the mobileText data and have that show on the parent component. I think my problem is in the editorValueMobile method inside the computed object. Any help would be great thanks

jQuery $(window).on(“load”, function() only launches after refresh

I had some scripts running on 1.7.1 jQuery and now I am on WordPress’s 1.12.4. The code wouldn’t run. I had two errors running.
Uncaught TypeError: $ is not a function
https://grumans.ca/delicatessen/:1734

This line on the page is
$(window).load(function(){Grumans.deli.init();});

and this

Uncaught TypeError: $ is not a function
https://grumans.ca/js/script.js:1162

$(window).load(function(){

     //Grumans.deli.init();
});

I found what I thought was a solution. Someone had posted for a different article that you could do this.

jQuery(function($) {
    $(window).on("load", function() {
       Grumans.deli.init();
    });
});

This got rid of both errors when applied to the page and in the script code, and let my code run, but only if I refresh the page twice. When I first hit the page nothing happens. I am not a code writer. Does anyone know why and how to fix the code so that it runs as soon as the page loads?

React Testing Library – unable to find the input with data-testid

So when I try to catch input by getByTestId I get an error:

TestingLibraryElementError: Unable to find an element by: [data-testid=”Name”]

I’ve changed method to queryByTestId and I’d been getting error:

Unable to fire a “change” event – please provide a DOM element.

I found out that if I enter following code:

expect(input).toBeNull;

I don’t get any errors at all and test is passed.

AddUser.test.js:

import React from 'react';
import '@testing-library/jest-dom';
import AddUser from 'views/AddUser';
import Dashboard from 'views/AddUser';
import { screen, fireEvent } from '@testing-library/react';
import { renderWithProviders } from 'helpers/renderWithProviders';

describe('Input With Button', () => {
  it('Renders the component', () => {
    renderWithProviders(
      <>
        <AddUser />
        <Dashboard />
      </>
    );
    const input = screen.queryByTestId('Name');
    console.log(input);
    expect(input).toBeNull; // PASSED!

    fireEvent.change(input, { target: { value: 'Andrew' } }); // ERROR!
    // fireEvent.change(screen.getByTestId('Attendance'), { target: { value: '89%' } });
    // fireEvent.change(screen.getByTestId('Average'), { target: { value: '4.1' } });
    // fireEvent.click(screen.getByText('Add'));
    // screen.getByText('Andrew');
  });
});

AddUser.js:

// ...
return (
        <ViewWrapper as="form" onSubmit={handleSubmitUser}>
          <Title>Add new student</Title>
          <FormField label="Name" id="name" name="name" value={formValues.name} onChange={handleInputChange} />
          <FormField label="Attendance" id="attendance" name="attendance" value={formValues.attendance} onChange={handleInputChange} />
          <FormField label="Average" id="average" name="average" value={formValues.average} onChange={handleInputChange} />
          <Button type="submit">Add</Button>
        </ViewWrapper>
      );
// ...

FormField.js:

// ...
return (
<Wrapper>
  <Label htmlFor={id}>{label}</Label>
  <Input name={name} id={id} type={type} value={value} onChange={onChange} data-testid={label} />
</Wrapper>
);
// ...

HTML Output of input element:

<input name="name" id="name" type="text" data-testid="Name" class="sc-gsDKAQ dfgpGW" value="">
                                         ------ HERE ------

Thank you in advance!

Resolving invalid_grant in Reddit

I am trying to authenticate my third party app against a Reddit account using oauth.

I first hit this endpoint

let authorizationUrl = https://www.reddit.com/api/v1/authorize?client_id=${redditClientId}&response_type=code&state=${state}&redirect_uri=${oAuthCallbackURL}&duration=permanent&scope=${scopes};

and then I was sent a code to my callback url

then I hit the next endpoint like this:

    let accessTokenUrl = `https://www.reddit.com/api/v1/access_token`;
    let accessTokenRequest = new URLSearchParams();
    accessTokenRequest.append("grant_type", "authorization_code");
    accessTokenRequest.append("code", code);
    accessTokenRequest.append("redirect_uri", oAuthCallbackURL);

    let redditClientId = process.env.REDDIT_CLIENT_ID;
    let redditSecret = process.env.REDDIT_SECRET;
    const clientIdAndSecretBase64 = 
    Buffer.from(`${redditClientId}:${redditSecret}`).toString('base64');
    try {
        let authorizationCodeResponse = await axios.post(accessTokenUrl, accessTokenRequest, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Authorization': `Basic ${clientIdAndSecretBase64}`
            }
        });
        let { data } = authorizationCodeResponse;
        console.log(authorizationCodeResponse);
        console.log(`Reddit OAUTH Response=${JSON.stringify(data, null, 2)}`);
    } catch (e) {
        console.log(e);
}

But all I keep getting back is this error:

Reddit OAUTH Response={
“error”: “invalid_grant”
}

On careful observation of Reddit docs I saw a line that says invalid_grant is only thrown when

The code has expired or already been used

This makes no sense because during the testing phase I forgot to save the access token. I should be able to reinitiate this request anytime. Why this limitation? I wanted to really see what the response is like before saving the access token. Now, clearly it seems there is no way to resolve this issue.

But any insight will be really appreciated.

Implementing Winston as a Writable Stream

I was planning on implementing Winston for logging in my project but I needed to implement it as a writable stream. I’ve noticed that there is a export for writable in the Winston package itself. My original plan was to simply wrap Winston in a writable stream, but if Winston can export itself as a Writable stream how would I go about doing this while keeping the same customizability as just exporting Winston normally?

How to implement a Fibonacci sequence in JavaScript?

I need to implement a Fibonacci sequence Оthrough a function for my homework. And I need to implement a function so that each subsequent call will output the next number in the sequence. It seems simple if you pass an argument to the function, but I’m not allowed to do that by the assignment. I have implemented this function with an argument, the code is shown below:

function helperFibonacci (n) {
 let number1 = 0;
 let number2 = 1;

 for (i = 0; i < n; i++) {
 let current = number1 + number2;
 number1 = number2;
 number2 = current;
     console.log(current);
  }
 }

 helperFibonacci(2); 

Please help me implement this function without passing an argument. thanks!

Node.js spawn is not running python command

I am trying to run a python command from Node.js v12.22.1 in a web application. This is the method that is being called in one of my controllers:

async start ({request,response,params}) {
                Log.create(request.request.headers.user,request.url())
                const { spawn } = require('child_process');
                const command = spawn('python',[process.env.BUS_PATH+'inventario/SystemDManager.py', params.name, "start"]);

                var responseData = "teste";
                command.stdout.setEncoding('utf-8');
                command.stdout.on('data', function (data){
                        responseData += data.toString();
                });
                command.stderr.on('data', function (data){
                        responseData += data.toString();
                });
                command.stdout.on('end',function(data){
                        console.log(responseData);
                });

                return responseData
        }

Variables are correctly instantiated, I have already printed them:

process.env.BUS_PATH = /home/ubuntu/

params.name = witty

So that the request command is:

python /home/ubuntu/inventario/SystemDManager.py witty start

This command runs perfectly when I type it directly into the shell console. However, nothing happens when running it through spawn. Moreover, when I change spawn arguments to:

spawn('cp',[process.env.BUS_PATH+'inventario/SystemDManager.py', "dummy.txt"]);

It works fine, it makes the file copy … Note that my responseData variable ends with “teste”, as if nothing had happened. I have even tried to change “python” to “/usr/bin/python”, but everything remains the same.

Does anyone has a tip of what is going wrong that python command is no being executed?

I am trying to have a second slider on the same page but its not working

I am trying to have a second slider on the same page but its not working.
The first one works fine but the second one is not working. I think there is something wrong with the parent element method but cant wrap my head around it.

var ids = ["view_0", "view_1", "view_2", "view_3"]
let current_id = 0;

function next(productnr) {
  if (document.getElementById(ids[current_id]).parentElement.id == productnr) {
    let last_array_position = ids.length;
    document.getElementById(ids[current_id]).classList.remove("show");
    current_id++;
    if (current_id >= last_array_position) {
      current_id = 0;
    }
    document.getElementById(ids[current_id]).classList.add("show");
  }
}
<style>#1 img {
  display: none;
}

#1 img.show {
  display: block;
}

</style>
<!DOCTYPE html>
<html>

<head>
  <title>Multiple Slider</title>
</head>

<body>

  <article id=1>
    <img class="show" id="view_0"></img>
    <img id="view_1"></img>
    <img id="view_2"></img>
    <img id="view_3"></img>
    <button><</button>
    <button onclick="next(1)">></button>
    <article id=2>
      <img class="show" id="view_0"></img>
      <img id="view_1"></img>
      <img id="view_2"></img>
      <img id="view_3"></img>
      <button><</button>
      <button onclick="next(2)">></button>




</body>