How to add aria label to ext JS close messageBox

Ext.Msg.show({
title:'Save Changes?',
message: 'You are closing a tab that has unsaved changes. Would you like to save your   changes?',
buttons: Ext.Msg.YESNOCANCEL,
icon: Ext.Msg.QUESTION,
fn: function(btn) {
    if (btn === 'yes') {
        console.log('Yes pressed');
    } else if (btn === 'no') {
        console.log('No pressed');
    } else {
        console.log('Cancel pressed');
    }
}
});

How do I add aria-label “close dialog” to the close icon at the top?

I am unable to add afterRender or listeners

How to retrieve more than 1000 otherContacts from Google API with pageToken?

I have a react App which I will be using to bring in google other contacts and I see that theres a limit for 1000 contacts in each call to google People Api’s.

const getGoogleContacts = async (token) => {
        if(!token) throw new Error('Google Auth Token Missing');
        let params = {"readMask" : "emailAddresses,names", "pageSize" : "1000"};
        let url = `https://people.googleapis.com/v1/otherContacts?${new URLSearchParams(params)}`;
       
        let headers = { Authorization: `Bearer ${token}`};
        let rawData = await fetch(url, { headers })
            .then(res => res.text());
        let parsedJson = JSON.parse(rawData);
        let nextPageCheck = checkForNextPageToken(parsedJson);
        if(nextPageCheck){
         //get the next page contacts. 
         }
        return handleRawContactData(parsedJson);
    }
const checkForNextPageToken = (response) => {
        if(response.hasOwnProperty('nextPageToken')){
            return true;
        }
        return false;
    }

how to convert all optional object fields into non-optional

I have the following Object type in Flow:

type Identity = {
  name: string,
  lastName: string
};

type ExtraInfo = {
   favoriteColor: string,
   age: number
};

type Person = {
   a: Identity,
   b?: ExtraInfo
};

Is there a way to define from Person a type without any maybe type?:

// final result, but I don't want to redeclare all the properties, I want to derive from the Person type
type PersonWithExtraInfo = {
   a: Identity,
   b: ExtraInfo
};

I thought that by applying this would work, but apparently, not. Maybe becuase it’s not a maybe type what’s defined, but an optional property:

type NonMaybeType = <Type>(Type) => $NonMaybeType<Type>;
export type PersonWithExtraInfo = $ObjMap<Person, NonMaybeType>;

How to export variable from react component?

I am using Mantine for a search bar and I need to get the wordcount of the text area. This is using Nodejs and React. I need to be able to export this value to use in a different file.

import React, { useState } from 'react';
import { TextInput, createStyles } from '@mantine/core';
var count = document.getElementById('count');

const useStyles = createStyles((theme, { floating }: { floating: boolean }) => ({
  root: {
    position: 'relative',
  },
  label: {
    position: 'absolute',
    zIndex: 2,
    top: 7,
    left: theme.spacing.sm,
    pointerEvents: 'none',
    color: floating
      ? theme.colorScheme === 'dark'
        ? theme.white
        : theme.black
      : theme.colorScheme === 'dark'
      ? theme.colors.dark[3]
      : theme.colors.gray[5],
    transition: 'transform 150ms ease, color 150ms ease, font-size 150ms ease',
    transform: floating ? `translate(-${theme.spacing.sm}px, -28px)` : 'none',
    fontSize: floating ? theme.fontSizes.xs : theme.fontSizes.sm,
    fontWeight: floating ? 500 : 400,
  },
  required: {
    transition: 'opacity 150ms ease',
    opacity: floating ? 1 : 0,
  },
  input: {
    '&::placeholder': {
      transition: 'color 150ms ease',
      color: !floating ? 'transparent' : undefined,
    },
  },
}
)
);
export function FloatingLabelInput() {
  const [focused, setFocused] = useState(false);
  const [value, setValue] = useState('');
  const { classes } = useStyles({ floating: value.trim().length !== 0 || focused });
  const uniqueid = "input";
  return(
    <TextInput
      id={ uniqueid }
      placeholder="Add anything you want to the book of the internet."
      required
      classNames={classes}
      value={value}
      onChange={(event) => setValue(event.currentTarget.value)}
      onFocus={() => setFocused(true)}
      onBlur={() => setFocused(false)}
      mt="md"
      onKeyUp={(e) => {
        var text = value.split(' ');
        var wordcount = 0;
        for (var i = 0; i < text.length; i++) {
          if (text[i] !== ' ') {
            wordcount++;
            }
          }
          count.innerText = wordcount;
        }
        }
      autoComplete="nope"
    />
      );
}

As you can see, it correctly outputs it into html, but returning inside the function doesnt work at all.

I tried exporting it, I tried returning it to the function but it doesn’t see it. I tried exporting and using modules exports but that doesnt work either. Any help would be appreciated.

How do you check if an API Object is undefined without getting a console error?

I’m using JS & AJAX to gather info from a Web-API (for a crypto-mining pool). Almost all of it works perfectly, but with the server the way the developer set it up, when a value is not used, it MIGHT be empty, not 0. Others do have a placeholder value (I’m talking with the dev to give everything a placeholder, but until then, I need some help).

e.g.:

{"version":"0.0.3","statusCode":200,"headers":{"Access-Control-Allow-Headers":"Content-Type, Access-Control-Allow-Headers, Access-Control-Allow-Origin, Access-Control-Allow-Methods","Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET","Content-Type":"application/json"},"body":{"primary":{"hashrate":{"shared":0,"solo":0},"payments":{"balances":0,"generate":0,"immature":0,"paid":0},"shares":{"shared":{},"solo":{}},"times":{"shared":0},"work":{"shared":0,"solo":0},"workers":{"shared":[],"solo":[]}},"auxiliary":{"hashrate":{"shared":0,"solo":0},"payments":{"balances":0,"generate":0,"immature":0,"paid":0},"shares":{"shared":{},"solo":{}},"times":{"shared":0},"work":{"shared":0,"solo":0},"workers":{"shared":[],"solo":[]}}}}

You can see that under body.primary.shares.shared it is just [] and not a zero value.

Here is part of the script:

function avianDashboard(api, workerAPI) {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", api, true);
    xhr.onload = function () {
        if (this.status === 200) {
            obj = JSON.parse(this.responseText);
            if (typeof (obj.body.primary.shares.shared) === 'undefined') {
                document.getElementById('minerShares').innerHTML = 0;
            } else {
                document.getElementById('minerShares').innerHTML = obj.body.primary.shares.shared.valid;
            }

//Rest of the function works properly so I've omitted it for the sake of sanity

When I run the page, the console.log shows this..

uncaught TypeError: Cannot read properties of undefined (reading ‘shared’)
at XMLHttpRequest.xhr.onload (avian.php:784:61)

and points to this line:

if (typeof (obj.body.primary.shares.shared) === ‘undefined’) {

I’ve found a lot of things that are supposed to help with this issue (including using typeof because I was originally just using <1 or null as my conditional checker and that didn’t work either.

Any help would be greatly appreciated.

Reading a OneDrive local JSON file using fetch in JavaScript

I am trying to read a local JSON file using JavaScript. The file is in OneDrive however, and I am operating in Codepen. In the browser console, I get a 404 error.

fetch(".UsersmyNameOneDrive - myOrgDocumentsmyFile.json")
  .then(response => response.json())
  .then(json => console.log(json));

Nothing is returning and I get that 404 error. I just want to console.log my json text. I can even convert it to a js file if that works better, but it didn’t work here.

The file location actually reads: C:UsersmyNameOneDrive – myOrgDocumentsmyFile.json , so am I writing the URL wrong? Is there a way to pull from OneDrive that I am missing? Is it because I am using Codepen? I can’t figure it out.

Need to sort using this function

I need sort the but not sure how:

class Stack {
  data;
  top;

  constructor() {
    this.data = [];
    this.top = 0;
  }

  push(element) {}
  pop() {}
}
size() {
  peek() {}
  isEmpty() {

  }
  display() {}
}

How do I solve sortQUsingStack I need to sort input q.display

function sortQUsingStack(q) {
  console.log("input:  " + q.display());
  var st =
    while () {

    }

  console.log("sorted: " + q.display());
}

How can I make my wordle clone in code.org make partial answers yellow?

So I am making a wordle clone in code.org using the dataset, yet I am facing two issues.

The first issue is that when I console.log the correct answer, sometimes it says “null” and other times it works without issue.

The second problem is I don’t know how to make the words yellow if they are out of order or in the word. My code is down below.

//Getting Wordle Answer 
var answers = getColumn("Wordle", "validWordleAnswer");
var index = (randomNumber(0, answers.length));
console.log(answers[index]);
var letters =  ["letter1", "letter2", "letter3", "letter4", "letter5"];


//Checking Words
onEvent("wordbutton", "click", function( ) {
  var guess = getProperty("wordInput", "text");
  for (var i = 0; i < 5; i++) {
   

     if (guess == answers[index]) {
          setProperty(letters[i], "background-color", "green");
        } else if ((answers[index].includes(guess))) {
          setProperty(letters[i], "background-color", "yellow");
        } else {
          setProperty(letters[i], "background-color", "red");
        }
    setProperty(letters[i], "text", guess[i]);
  }
});

Specifically the else if statement, and the first four lines of code that are my variables

Simulating free drawing of path objects in fabric.js

I’m trying to simulate the free drawing of a path object inside a fabric.js canvas.

I have a “recording” of the steps inside a javascript object such as :

var dataset = [{
  "type": "move",
  "value": [
    [30, 257, "2022-03-22T10:16:56.882Z"],
    [58, 271, "2022-03-22T10:16:56.898Z"],
    [79, 281, "2022-03-22T10:16:56.914Z"],
    [91, 282, "2022-03-22T10:16:56.931Z"],
    [95, 282, "2022-03-22T10:16:56.948Z"],
    [96, 281, "2022-03-22T10:16:56.963Z"],
    [97, 281, "2022-03-22T10:16:56.981Z"]
  ]
},
{
  "type": "draw",
  "value": [
    [97, 281, "2022-03-22T10:16:57.046Z"],
    [98, 281, "2022-03-22T10:16:57.070Z"],
    [103, 279, "2022-03-22T10:16:57.083Z"],
    [106, 278, "2022-03-22T10:16:57.098Z"],
    [114, 274, "2022-03-22T10:16:57.114Z"],
    [133, 268, "2022-03-22T10:16:57.130Z"]
  ]
}]

value is an array of array containing the coordinates (x, y) on the canvas, and the timestamp. It is the result of a recording of the user interactions on the canvas.

I managed to recreate a moving cursor ("type": "move") but I have troubles recreating the drawing process ("type": "draw") as it involves three mouse events (‘mousedown’, ‘mousemove’ and ‘mouseup’).

For now, I’m using two nested asynchronous functions to navigate inside the object and move the cursor around the canvas.

var time;

autoDrawing(dataset, function() {
   console.log('finished');
});

async function autoDrawing(dataset, callback) {
   time = new Date(dataset[0].time);
   for (let i = 0; i < dataset.length; ++i) {
       await draw(dataset[i]);
   }
   callback();
}

function draw(data) {
    return new Promise(resolve => {
        if (data.type === 'move') {
            console.log('moving');
            moveCursor(data.value, false, function() { resolve('') });
        } else if (data.type === 'draw') {
            console.log('drawing');
            moveCursor(data.value, true, function() { resolve('') });
        } else {
            resolve('');
        }
   });
}

async function moveCursor(moves, draw, callback) {
     // The canvas object is stored inside the DOM element, in the fabric property.
     // This is because I have different canvas for different layers.
     let activecanvas = document.getElementsByClassName('canvas-container active')[0].firstChild.fabric;
     if (draw) {
          activecanvas.fire('mouse:down', {
              x: moves[0][0],
              y: moves[0][1]
          });
          activecanvas.renderAll();
     }
     for (j = 0; j < moves.length; j++) {
          await movement(moves[j], draw);
     }
     if (draw) {
          activecanvas.fire('mouse:up', {
              x: moves[moves.length - 1][0],
              y: moves[moves.length - 1][1]
          });
          activecanvas.renderAll();
     }
     callback();

     function movement(m, draw) {
         return new Promise(function(resolve, reject) {
              let newtime = new Date(m[2]);
              if (draw) {
                   activecanvas.fire('mouse:move', {
                        x: m[0],
                        y: m[1]
                   });
                   activecanvas.renderAll();
              }
              // mousecursor is a circle that substitutes the mouse cursor on an other canvas.
              mousecursor.set({
                   top: m[1],
                   left: m[0]
              }).setCoords().canvas.renderAll();
              // waitMap is just a setTimeout with the duration/callback position inverted
              waitMap((newtime - time) / 1000, function() {
                   time = newtime;
                   resolve('')
              })
         })
     }
}

I’m using the fire method of a fabric.js canvas but I didn’t find any examples, so maybe I’m not using it the right way.

grouping subsequent objects inside the array that have the same property value [duplicate]

I have the following array.

const slides = [

  { name: 'intro', effect: 'default'},

  { name: 'slide1', effect: 'spin' },

  { name: 'slide2', effect: 'spin' },

  { name: 'slide3', effect: 'spin' },

  { name: 'slide4', effect: 'spin' },

  { name: 'slide5', effect: 'spin' },

  { name: 'slide6', effect: 'spin' },

  { name: 'slide7', effect: 'default' },

  { name: 'slide8', effect: 'rotate' },

  { name: 'slide9', effect: 'rotate' },

  { name: 'slide10', effect: 'rotate' },

  { name: 'slide11', effect: 'rotate' },

  { name: 'outro', effect: 'default' },

]

If i have objects one after another that have the same effect i need to group them into an object that has { type: ‘stacked’, items: [ here will be all the objects with the same effect property }

How can i transform it to look like this?

const slides = [
  { name: 'intro', effect: 'default'},
  { type: 'stacked', 
    items: [
      { name: 'slide1', effect: 'spin' },
      { name: 'slide2', effect: 'spin' },
      { name: 'slide3', effect: 'spin' },
      { name: 'slide4', effect: 'spin' },
      { name: 'slide5', effect: 'spin' },
      { name: 'slide6', effect: 'spin' },
    ]
  },
  { name: 'slide7', effect: 'default' },
  { type: 'stacked', 
    items: [
      {  name: 'slide8', effect: 'rotate' },
      {  name: 'slide9', effect: 'rotate' },
      {  name: 'slide10', effect: 'rotate' },
      {  name: 'slide11', effect: 'rotate' },
    ],
  },
  {  name: 'outro', effect: 'default' },
]

Can anyone help? thank you !

How to check if a timeslot lies between two other timeslots?

I have 3 time stamps

StartTime: 22:30:00

EndTime: 05:00:00

CurrentTime: 03:00:00

Now if the current time lies between StartTime and EndTime, then I want to print the “CurrentTime”. So in the above example since CurrentTime is between 22:30:00 and 05:00:00, hence I wish to print it.

So I used the following code

const StartTime = new Date("2020-02-22T23:00");
const EndTime = new Date("2020-02-23T05:00");
const CurrentTime = new Date("2022-02-23T0:00");

const StartTimeHours = StartTime.toLocaleTimeString('en-US', { hour12: false });
const EndTimeHours = EndTime.toLocaleTimeString('en-US', { hour12: false });
const CurrentHours = CurrentTime.toLocaleTimeString('en-US', { hour12: false});

if (StartTimeHours < CurrentHours && CurrentHours < EndTimeHours)
{
    console.log("Current Time",CurrentHours);
}

However, since 05:00:00 is less than 22:30:00, hence it is not printing the output. So how do I make it check that the EndTime is between the two time slots

DiscordJS V12 Reactions not Catching Error

    channel.send(embed).then(m => {
      m.react("<:check:947079937372872704>")
      m.react("<:warning:943421375526355024>")
    }).catch(err => {
      message.channel.send('Error')
    })

This is my code but when the bot doesn’t have add reaction perms it crashes instead of catching it and printing Error

how can I make a universal function to change the local state

I have onChangeName and onChangeAge functions, but I want to make 1 function from these two.

functions onChangeSomeState does not work, I don’t no why

codesandbox

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [name, setName] = useState("");
  const [age, setAge] = useState("");

  const onChangeSomeState = (setFunc) => (event) => {
    setFunc(event.taget.value);
  };

  const onChangeName = (e) => {
    setName(e.target.value);
  };

  const onChangeAge = (e) => {
    setAge(e.target.value);
  };

  const onSubmit = () => {
    const res = JSON.stringify({
      name: name,
      age: age
    });
    console.log(res);
  };

  console.log(name);
  console.log(age);

  return (
    <div className="App">
      <input
        onChange={onChangeName}
        placeholder="name"
        value={name}
        className="input"
      />
      <input
        onChange={() => onChangeSomeState(setAge())}
        // onChange={onChangeAge}
        placeholder="age"
        value={age}
        className="input"
      />
      <button onClick={onSubmit} type="button" className="button">
        submit
      </button>
    </div>
  );
}

I’m not getting any age value in the console