Get value from push key generated

I want to get points of respectived logged in user to be displayed from database corresponding to its push key i tried many ways but i just couldn’t make it possible here is my code

const autoid=firebase.database().ref("user").push().key;


    firebase.database().ref("/").child(autoid).set({
    email :email,
    password : password, 
    points :"500", 
    Id:autoid 
   })

And below is my firebase realtime database picture
Realtime database

Making cursor skip disabled textform

Im making a site, with a lot of user registration, needed in practice, where the least amount of clicks is needed. Im making text input fields, which only need 1 charachter, before jumping to the next registration. However, these text input fields needs to be able to disable. This have I solved by using checked boxes and a function. My problem now comes, when needing to skip disabled text input fields: Lets say text input 2 is disabled, the cursor needs to jump from text input 1 to text input 3.

<form >
  <input type="text" id="yourText1" enabled maxlength="1"  onkeyup="jump(this,'yourText2')"/>
<input type="checkbox" id="yourBox1" checked onmousedown="this.form.yourText1.disabled=this.checked"/>
 </form>

 <form >
  <input type="text" id="yourText2" enabled maxlength="1"  onkeyup="jump(this,'yourText3')"/>
<input type="checkbox" id="yourBox2" checked onmousedown="this.form.yourText2.disabled=this.checked"/>
 </form>

 <form >
  <input type="text" id="yourText3" enabled maxlength="1"  onkeyup="jump(this,'yourText4')"/>
<input type="checkbox" id="yourBox3" checked onmousedown="this.form.yourText3.disabled=this.checked"/>
 </form>

 <form >
  <input type="text" id="yourText4" enabled maxlength="1"  onkeyup="jump(this,'yourText1')"/>
<input type="checkbox" id="yourBox4" checked onmousedown="this.form.yourText4.disabled=this.checked"/>
 </form>



 <script>
  function jump(field, automove) {
    if (field.value.length >= field.maxLength)
      {document.getElementById(automove).focus();}
    
    }
</script>

Cookie not expiring in JS after setting date to 1970

I am trying to delete some cookies BEFORE MY REQUEST IS SENT to my backend so I set expiration date for those cookies to be Thu, 01 Jan 1970 00:00:00 UTC, expecting for my backend service to not see any of those cookies when handling the request.

The process to delete cookies, as far as I know, is to set the expiration date of the cookies to be a past date (As I am doing) but for some reason cookies seem to be still alive.

This is what I currently have:

let badCookies = ['cookieName1', 'cookieName2', 'cookieName3'];
      badCookies.forEach((cookieName) => {
          document.cookie = `${cookieName}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
        });

if(GetCookie('cookieName1') === null) {
    // Must fall here since cookieName1 has been forced to expire
} else {
    // ERROR: cookie still alive, I am actually falling here that's the main issue
}

I don’t really know what can be wrong, a simple process keeps causing problems and I cannot find any solution for this. I have searched in several websites but the answer for delete the cookies are always the same, setting the expiration date to force cookie to be deleted before making a request.

The process is described here:

Delete cookie by name?

and also here:

https://www.w3schools.com/js/js_cookies.asp

I have tried both strings without success.

I am using this to check for cookie to see if it is still valid:

Check if cookie is still valid

Sorry if this question seems like duplicate but none of the answers in similar stack overflow posts could help me that’s why I decided to post my own question.

Thanks in advance.

Practical example where micro task queue is useful in Event Loop

I learn that there are three queue in Event Loop.

  1. macrotaskqueue
  • related with setTimeout, setInterval, event(user gesture) task, event handler, network response etc..
  1. microtaskqueue
  • related with MutationObserver, Object.observe, Promise
  • have higher priority than mactotask queue
  • main thread work on this queue until it is empty
  • rendering will be delayed until this queue is empty
  • a task inserted into microtaskqueue in processing microtask will be executed at that iteration ( = microtaskqueue should be empty before going next iteration or rendering)
  1. animationframequeue
  • callback function of requestAnimationFrame() is inserted in this queue
  • a task inserted into animationframequeue will be executed at next iteraction(unlike microtaskqueue)
  • tasks in this queue will be processed right before rendering

Yes,, But What I want to know is that

  • Is microtaskqueue really needed?
  • What is practical(useful) example of using microtaskqueue?
  • Why the computer guys made this queue? what’s the motivation?

Check please, I need your helps

Eval command works properly, but when it errors it doesn’t use `catch {`

I use eval for some testing outside of the code or console. However, it doesn’t tell me if it errored or the result with the error. It just shows the error in the console, without telling me. As a result, whenever the bot doesn’t respond to my eval, I have to go all the way to the coding place and restart it to have the bot online again.

I’ve tried to modify the catch script, like removing (err) in catch (err).

Here’s my code:

const args = message.content.split(" ").slice(1);

  if (message.content.startsWith(`${p}eval`)) {
    if (message.author.id !== "821682594830614578") {
      message.channel.send(`Eval command can't be used by users, since the command can do anything, even deleting the files of code from a bot.`)
    } else {
      try {
        const evaled = eval(args.join(" "));
        let cleaned = await clean(client, evaled);
        const embedEval = new MessageEmbed()
          .setTitle('Eval succeeded')
          .setColor('#00ff8f')
          .addField('Result:', ````jsn${cleaned}n````, false)
          .setTimestamp()
          .setFooter({ text: 'Eval has been succeded.' })
        
        message.channel.send({ embeds: [embedEval] });
      } catch {
        message.channel.send(``ERROR` ```xln${cleaned}n````);
      }
    }
  }

Fill upload field on submit action and save

I have an HTML form with an upload field that should be filled programmatically with JavaScript. I have written a function that works as desired, when I use this for test:

this.on('click', 'h2', this.fillField);

The field is filled upon the click on the header and upon manual clicking on submit button, everything is saved.

Then, I have only changed the trigger for the function

this.on('submit', 'form', this.fillField);

Upon clicking on submit, I can see how the field is filled, no errors in the console, the form is submitted, but the field is not saved. Just empty.

Why?

Age Verification Popup Show Only Once BY Account instead of by Cookie Memory

Greeting,
I am doing an age verification popup targeted only to the landing page of login.

The show-only-once function was set but only for cookie memory of the browser. That is- if I login to the same account in other device or incognito/ inPrivate, it will show up anyway, and vise versa.

Here are the script code for the age verification. Not sure if there is options for account-based show-only-once.


jQuery(document).ready(function($){
 
if (sessionStorage.getItem('advertOnce') !== 'true') {
//sessionStorage.setItem('advertOnce','true');
 $('.box').show();
}else{
 $('.box').hide();
}
 
$('#refresh-page').on('click',function(){
$('.box').hide();
sessionStorage.setItem('advertOnce','true');
});
 
$('#reset-session').on('click',function(){
$('.box').show();
sessionStorage.setItem('advertOnce','');
});
 
if (sessionStorage.getItem('advertOnce') !== 'true') {
//sessionStorage.setItem('advertOnce','true');
 $('.overlay-verify ').show();
}else{
 $('.overlay-verify ').hide();
}
 
$('#refresh-page').on('click',function(){
$('.overlay-verify ').hide();
sessionStorage.setItem('advertOnce','true');
});
 
$('#reset-session').on('click',function(){
$('.overlay-verify ').show();
sessionStorage.setItem('advertOnce','');
});
 
 
});

Many thanks

how can i get connection from edge of circle insted of center of circle in d3.js force layout

here im added the link  from  circle center to circle center but i want to connect from circle edge to edge

Here im added the link from circle center to circle center but i want to connect from circle edge to edge

I want to connect the links from node edge to edge but im getting node center to center
is i did mistake in my code please help me out if any one know answer for this problem

here is my full working code

const VocabularyGraphh = () => {
  const svgRef = useRef(null);
  React.useEffect(() => {
    const svg = d3.select(svgRef.current),
      diameter = +svg.attr("width"),
      g = svg.append("g").attr("transform", "translate(2,2)"),
      format = d3.format(",d");

    const links = [
      { source: "animate1", target: "animate4" },
      { source: "animate6", target: "animate9" },
      //   { source: "animate9", target: "animate6" },
      { source: "animate3", target: "animate2" },
      { source: "animate1", target: "animate8" },
      { source: "animate3", target: "animate5" },
      //   { source: "analytics1", target: "analytics2" },
    ];

    let root = {
      children: [
        {
          name: "analytics1",
          children: [
            {
              name: "animate1",
              size: 1500,
            },
            {
              name: "animate2",
              size: 1500,
            },
            {
              name: "animate3",
              size: 1500,
            },
            {
              name: "animate33",
              size: 1500,
            },
            {
              name: "animate23",
              size: 1500,
            },
            {
              name: "animate32",
              size: 1500,
            },
            {
              name: "animate11",
              size: 1500,
            },
            {
              name: "animate22",
              size: 1500,
            },
            {
              name: "animate34",
              size: 1500,
            },
            {
              name: "animate16",
              size: 1500,
            },
            {
              name: "animate20",
              size: 1500,
            },
            {
              name: "animate3",
              size: 1500,
            },
          ],
        },
        {
          name: "analytics2",
          children: [
            {
              name: "animate4",
              size: 1500,
            },
            {
              name: "animate5",
              size: 1500,
            },
            {
              name: "animate6",
              size: 1500,
            },
          ],
        },
        {
          name: "analytics3",
          children: [
            {
              name: "animate7",
              size: 1500,
            },
            {
              name: "animate8",
              size: 1500,
            },
            {
              name: "animate9",
              size: 1500,
            },
          ],
        },
      ],
    };

    // svg
    //   .append("svg:defs")
    //   .append("svg:marker")
    //   .attr("id", "arrow")
    //   .attr("viewBox", "0 0 10 10")
    //   .attr("refX", 10)
    //   .attr("refY", 5)
    //   .attr("markerUnits", "strokeWidth")
    //   .attr("markerWidth", 6)
    //   .attr("markerHeight", 3)
    //   .attr("orient", "auto")
    //   .append("svg:path")
    //   .style("stroke", "none")
    //   .attr("d", "M 0 0 L 10 5 L 0 10 z");

    const pack = d3
      .pack()
      .size([diameter / 2, diameter / 2])
      .padding(100);

    root = d3
      .hierarchy(root)
      .sum(function (d) {
        return d.size;
      })
      .sort(function (a, b) {
        return b.value - a.value;
      });

    const node = g
      .selectAll(".node")
      .data(pack(root).descendants())
      .enter()
      .filter(function (d) {
        return !!d.data.name;
      })
      .append("g")
      .attr("id", function (d) {
        return d.data.name;
      })
      .attr("class", function (d) {
        return d.children ? "node" : "leaf node";
      })
      .attr("transform", function (d) {
        return "translate(" + d.x + "," + d.y + ")";
      });

    node.append("title").text(function (d) {
      return d.data.name + "n" + format(d.value);
    });

    const arrow = svg.selectAll("path.arrow").data(links, JSON.stringify);
    arrow
      .enter()
      .append("path")
      .attr("class", "arrow")
      .attr("x1", function (d) {
        console.log(d);
        let translate = getTranslate(d.source);
        console.log(translate);
        return translate[0];
      })
      .attr("x2", function (d) {
        let translate = getTranslate(d.target);
        return translate[0];
      })
      .attr("y1", function (d) {
        let translate = getTranslate(d.source);
        return translate[1];
      })
      .attr("y2", function (d) {
        let translate = getTranslate(d.target);
        return translate[1];
      })
      .attr("d", function (d) {
        // console.log(d);
        let source = getTranslate(d.source),
          target = getTranslate(d.target),
          x1 = source[0],
          x2 = target[0],
          y1 = source[1],
          y2 = target[1];
        console.log(source);
        console.log(target);
        // let dx = x1 - x2,
        //   dy = y1 - y2,
        //   dr = Math.sqrt(dx * dx + dy * dy);

        return (
          "M" + x1 + "," + y1 + "A" + 0 + "," + 0 + " 0 0,1 " + x2 + "," + y2
        );
      })
      .style("stroke", "black")
      .style("fill", "none")
      .style("stroke-width", 1)
      .attr("marker-end", "url(#arrow)")
      .attr("class", "hidden-arrow ");
    //   .attr("stroke-width", 1);

    node
      .append("circle")
      .attr("r", function (d) {
        console.log(d);
        return d.r;
      })
      .attr("class", "pink");

    node.filter(function (d) {
      return !d.children;
    });
    //   .append("text")
    //   .attr("dy", "0.3em")
    //   .text(function (d) {
    //     return d.data.name.substring(0, d.r / 3);
    //   });

    function getTranslate(datum) {
      const circle = d3.select("#" + datum);
      const string = circle.attr("transform");
      const translate = string
        .substring(string.indexOf("(") + 1, string.indexOf(")"))
        .split(",");
      return translate;
    }
  }, []);
  return (
    <div>
      <svg ref={svgRef} width="960" height="960"></svg>
    </div>
  );
};

export default VocabularyGraphh;

if anyone give this solution thats so appreciatable

Google map api. search nearby not getting respond back seem link axios getting skip

Hello guys I am working on google map api to search all the gym near by me using Vue Js and laravel. The problem is I am not getting an error back and also not getting an respond back here is my code.

 <template>
  <div class="container mb-5">
    <div class="row justify-content-center">
      <div class="col-md-12 text-center">
        <h1 class="">Find</h1>
      </div>
      <div class="row mt-5">
        <form>
          <div class="form-group">
            <label>Email address</label>
            <input
              type="text"
              class="form-control"
              placeholder="Address"
              v-model="coordinates"
            />
            <a @click="locatorButtonPressed"> get location</a>
          </div>
          <select class="form-control" v-model="type">
            <option value="gym">gym</option>
          </select>
          <select
            class="form-control"
            v-model="radius"
            aria-placeholder="Distance"
          >
            <option value="10">10 KM</option>
            <option value="50">50 KM</option>
            <option value="100">100 KM</option>
            <option value="200">200 KM</option>
          </select>
          <button class="ui button" @click="findCloseBuyButtonPressed()">
            Find Gym
          </button>
        </form>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "App",
  data() {
    return {
      lat: 0,
      lng: 0,
      type: "",
      radius: "",
      places: [],
    };
  },
  computed: {
    coordinates() {
      return `${this.lat}, ${this.lng}`;
    },
  },
  methods: {
    locatorButtonPressed() {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          this.lat = position.coords.latitude;
          this.lng = position.coords.longitude;
        },
        (error) => {
          console.log("Error getting location");
        }
      );
    },
    findCloseBuyButtonPressed() {
 

      var axios = require('axios');

      var config = {
        method: 'get',
        url:  `https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${
                this.lat
              },${this.lng}&type=${this.type}&radius=${
                this.radius * 1000
              }&key={my-api-key}`,
        headers: { }
      };
      alert(config.url)
      axios(config)
      .then(function (response) {
        console.log(JSON.stringify(response.data ));
      })
      .catch(function (error) {
        console.log(error);
      });
      alert("hello")
    },
  }
};
</script>

<style>
</style>

I have try to debug this code by putting alert() it pop us both but it seems that it skipped this part because there is not respond or error in console

 axios(config)
  .then(function (response) {
    console.log(JSON.stringify(response.data ));
  })
  .catch(function (error) {
    console.log(error);
  });

So I try changed alert to console.log() this time it just refresh a page and return noting in a console.

I have try my google map api key with example from document on website it still work fine.

How do I let the browser allow me to use imports? (TypeScript)

Context

I have these two TypeScript files:

// something.ts

let x = 3;

export default x;
// index.ts

import x from "./something";

console.log(x);

under these tsconfig.json settings:

{
  ...
    "target": "es2016",
  ...
    // "module": "commonjs" /* <- commented out */
}

when I compile this into JavaScript, I get these two files (which is what I expect):

// something.js

let x = 3;
export default x;
// index.js

import x from "./something";
console.log(x);

Now, I’ve linked the index.js file from my HTML file like so:

<script src="./dist/index.js"></script>

Problem

When I try opening this up using Live Server, I get this error in the console:

Uncaught SyntaxError: Cannot use import statement outside a module

So, how do I fix this?

What I’ve tried

  1. Adding back the "module": "commonjs" line in my tsconfig.json file

This results in a different error message appearing in the console:

Uncaught ReferenceError: exports is not defined

As per this SO post, a suggested solution is to comment out the "module": "commonjs" line, which essentially throws my situation into an infinite loop…

  1. Adding "type": "module" to the <script> tag and package.json

From this SO post, a suggested solution is to add "type": "module" to the <script> tag:

<script type="module" src="./dist/index.js"></script>

but now I get this error message:

GET http://127.0.0.1:5501/dist/something net::ERR_ABORTED 404 (Not Found).

In the same post, another suggestion was to add “type”: “module” to the package.json file:

{
  "type": "module",
  "dependencies": {
    "typescript": "^4.6.2"
  }
}

and from what I’ve observed, this doesn’t really do anything.

Key value in javascript

This is the continuation of this question which is here How to group by dynamic key value of an object of arrays(Month and year) Here i am getting output as expected but i want a small change on the output. The out put which is producing right now is as follows.
enter image description here

But the result which i am expecting is goes like this.

enter image description here
Code which i am using is like this.

           //Stack to retrive result
              let filteredStack:any =[];
            //Sorting based on the sorted key
              sortedKeys.forEach(k => {
                filteredStack.push(k,result[k]);
              });

How can i do this?

This “undefined” error has been driving me crazy! Can you find the error? [duplicate]

The code below references a td object with id “00”. I’m simply trying to get the the background color (which is currently expected to be “white”). I’ve declared the background in CSS as “white”. I can’t figure out how the statement below would result in an error. Can you?

console.log(document.getElementById("00").style.backgroundColor);

Length issue with Javascript carry-forward choices from multiple questions using Qualtrics?

I am using a matrix drag and drop on Qualtrics to ask respondents to sort 46 statements into the categories: agree less, neutral, and agree more (QID1).

QID1

In QID6 I ask them to sort the statements carried forward from the category agree less into -5 to 0.

QID6

Then in QID7 I ask them to sort the statements carried forward from the category agree more into 0 to 5.

QID7

In QID4 I show them how they sorted the statements (from -5 to 5) from QID6 and QID7. However, I wanted to combine how they sorted the responses in QID1, QID6, and QID7 specifically for the neutral and 0 responses. However, I have been unsuccessful at getting all the statements to carry forward. If only one statement was put into each of the categories of neutral (in QID1), category 0 in QID6, and category 0 in QID7 then those three statements appear in QID4.(QID1selection, QID6selection, QID7selection, result)

However, if more than one statement is placed into any of those categories (neutral in QID1 or 0 in QID6 and 7), then none of them appear in QID4. This does not seem to be an issue for the statements selected in the other categories (-5,-4,-3,-2,-1,1,2,3,4,5). Is this an issue with length or is concat the incorrect function to use? I am not familiar with javascript at all, so I am having a hard time figuring out what is the issue.

Below is the Javascript function I am using (based on this discussion post: https://community.qualtrics.com/XMcommunity/discussion/14728/carry-forward-response-into-drag-drop-box)

    Qualtrics.SurveyEngine.addOnReady(function () {
    let ques = this;
    //let a1 = "${q://QID1/ChoiceGroup/SelectedChoicesForAnswer/1}";
    let a2 = "${q://QID1/ChoiceGroup/SelectedChoicesForAnswer/2}"; //this is neutral
    //let a3 = "${q://QID1/ChoiceGroup/SelectedChoicesForAnswer/3}";
    let b1 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/1}";
    let b2 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/2}";
    let b3 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/3}";
    let b4 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/4}";
    let b5 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/5}";
    let b6 = "${q://QID6/ChoiceGroup/SelectedChoicesForAnswer/6}"; //this is 0
    let c1 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/1}"; //this is 0
    let c2 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/2}";
    let c3 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/3}";
    let c4 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/4}";
    let c5 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/5}";
    let c6 = "${q://QID7/ChoiceGroup/SelectedChoicesForAnswer/6}";
    
    let d1 = a2.concat(b6,c1); //this should combine all the statements selected for QID1 (ans2), QID6 (ans6), and QID7 (ans1)
    
    let choice_text = ques.getChoiceContainer().innerText.split(/n/gm);
    let all_choices = ques.getChoices();
    let all_answers = ques.getAnswers();
    
    for (let i = 0; i < choice_text.length; i++) {
        let set_choice= -1
        switch (true) {
            case b1.includes(choice_text[i]):
                set_choice = all_answers[0];
                break;
            case b2.includes(choice_text[i]):
                set_choice = all_answers[1];
                break;
            case b3.includes(choice_text[i]):
                set_choice = all_answers[2];
                break;
             case b4.includes(choice_text[i]):
                set_choice = all_answers[3];
                break;
             case b5.includes(choice_text[i]):
                set_choice = all_answers[4];
                break;
            case d1.includes(choice_text[i]): //this should show all the statements selected for QID1 (ans2), QID6 (ans6), and QID7 (ans1)
                set_choice = all_answers[5];
                break;  
            case c2.includes(choice_text[i]):
                set_choice = all_answers[6];
                break;
            case c3.includes(choice_text[i]):
                set_choice = all_answers[7];
                break;
             case c4.includes(choice_text[i]):
                set_choice = all_answers[8];
                break;
             case c5.includes(choice_text[i]):
                set_choice = all_answers[9];
                break;
            case c6.includes(choice_text[i]):
                set_choice = all_answers[10];
                break;
        }
        ques.setChoiceValue(all_choices[i], set_choice, true);
    }
});

I would appreciate it if anyone can point me to the right direction or to any helpful resources.

Automatic scroll to the current song in the playlist

I have a div with vertical scrollbar. It contains a list of 20 songs, with variable length titles. At any given moment, the div can display only 7 songs.

I am able to highlight the song being played in the div, however, it remains hidden under the div, as moving to the next song refreshes the page and the div scroll to the top.

Q. How do I scroll the div such that the current song (and preferably prev and next) always remain in the view?

Any points are greatly appreciated!

JS using dot, string notation to map nested and assign errors

Ok, this is an odd one that I just can’t seem to get right.

I have a large, complex object to send to a backend. After various attempts, I tried using Joi to validate the schema, and I like it, but passing the errors back to the inputs is a nightmare

The body is subdivided into 5 sections, with each subsection containing between 10-30 fields, some of which are string[], interface[], number[], or general nested interfaces.

I tried writing my own custom validation and the complexity grew outta control.

(I know some of you are thinking “your schema is too complex” and you’re right, but its not something I can change right now. Clients blah blah.)

The problem: Joi.validate(myBody) gives me a bunch of errors in the following format:

[ // <- error.details
  {
    context: {},
    message: "X is not allowed to be empty",
    path:["path","to","property"], // <- this is the key
    type: ""
  }
]

How can I map error.details to create a new validation object that I can then use for the form items themselves.

For example:

path = ["path","to","property"] // -> map over to create

let newObj = {
  path:{
    to: {
       property: ""
    }
}
}

I hope this make sense.

I want to take an array of vallidation errors, and turn them into a validation object that matches the initial object