Javascript – Count first element of multi dimensional array

I have below code to extract the ID and username of a unique list of authors.

    let authorsList = await Poem.find({ 'author.id': {$nin: community.busAdmins}}).where('communities').equals(community._id).populate('authors').sort({"author.username": 1});

    let uniqueAuthorsList = [];
    authorsList.forEach(details => {
        if(!uniqueAuthorsList.some(code => code.username == details.author.username)){
            uniqueAuthorsList.push({username: details.author.username, id: details.author.id});
        }
    });

For each of those authors, I want to count how many blogs they have written. So far I have this code:

const counts = {};
        uniqueAuthorsList.forEach((el) => {
        counts[el] = counts[el] ? (counts[el] += 1) : 1;
        });
        console.log(counts);

But this only returns:

{ '[object Object]': 7 }

How can I count the records using only the first element of the array (username), so I can return a list like this?

Dave: 4
Emily: 7
Mark: 2

Puppeteer works headless but not headful (JS)

I am running puppeteer on a Linux VM, which does not have a display; however, I am using xvfb to remedy that.

For some background: The overall goal of this program is to navigate to a page and authenticate using puppeteer. From there, I audit several webpages using Lighthouse.
I have been running this script for several weeks in headless no issues. I’ve recently found that the performance metrics of the headless Lighthouse runs far better than reality by running manual tests on my local machine through chrome developer tools. If it’s relevant, I specifically noticed a huge gap in the number of recorded DOM nodes. Long story short, I now need to run this script in headful mode.

After installing and implementing xvfb in my code, I have been able to start a display within my script without hitting any errors. I used the answer from this question as reference: Running Puppeteer with xfvb headless : false

With all of that out of the way, onto the actual issue: this script, including the xvfb implementation, still runs flawlessly in headless mode with absolutely no timeouts despite repeated runs. When I try running it in headful mode, I consistently timeout on the puppeteer launch, even when I tried extending the timeout to 5 minutes. I’ve tried an absurd amount of launch-option combinations to no avail. Any and all help would be so greatly appreciated, even if it means significantly altering my approach to the problem. Thank you!

Code wars: Why does this function work against whitespace and numbers?

I had this code wars kata that asked me to make a function that checked if 2 inputs were the same case. I have my own solution to this problem but in the solutions section I found this version and I can’t understand how/why it works:

function sameCase(a, b){
 if(a.toUpperCase() === a.toLowerCase() || b.toLowerCase() === b.toUpperCase()){
    return -1
  }else if(a === a.toLowerCase() && b === b.toLowerCase() || a === a.toUpperCase() && b === b.toUpperCase()){
      return 1
  }else{
    return 0
  }
}

im specifically referring to this portion:

if(a.toUpperCase() === a.toLowerCase() || b.toLowerCase() === b.toUpperCase()){ return -1}

I know this check works against numeric characters and white space, but I don’t understand why this works since it doesn’t look to take these items into account.

my question: why does this function work against non-letters and numbers and even white space?

Jest how to test if a mocked promise is resolved

My application code is something like this:
const promises = requests.map(async request => {await someAPI(request)}); await Promises.all(promises).
I don’t care about the return value.

I have a mock for the API like
const someAPI = jest.fn().mockReturnValue(Promise.resolve(true));

I can test that someAPI is called with the right parameters, but how can I test that the returned promise is indeed resolved? For example, if the client code is simply const promises = requests.map(async request => {await someAPI(request)});, it would pass the test for calling the API, even though it doesn’t actually try to resolve the promises.

Vue 3 with Hybrid Data (Static Generated & Dynamic)

My Vue-3 site is currently running using a Firestore database. However, the majority of the site’s data does not need to be dynamically generated, so I would like to move much of this data to a local CMS, i.e. Strapi.

Is it possible to integrate this static data without having to rebuild the entire site using Nuxt, Gridsome, etc, and if so, how?

setTimeout executing synchronously? [duplicate]

I’m new to Javascript and trying to understand async programming. So I wrote the below code in chrome developer tools workspace –

console.log("hi1");
setTimeout(console.log("hi-async"),1000);
console.log("hi3");

The out put I was expecting was –

hi1
hi3
hi-async

Instead, the console printed following, without the 1 second delay (all at once) –

hi1
hi-async
hi3

So basically, the setTimeout function was executed synchronously! Can someone tell me why that’s the case? I thought setTimeout is an async function and will always be executed asynchronously. Am I wrong? Thanks!

How do you pass a value to a custom envelop field using the the JS SDK?

I am trying to figure out how to pass a value to the custom envelope field I have created. I am currently using the new JS SDK. I am able to pass a value to a custom field for my document but am unsure how to do this for an envelope custom field.

data-powerform-fields="signer_UserName=firstname%lastname&[email protected]&signer_acknowledgement=Read
and accepted." src="//developers.docusign.com/js/docusign.js"></script>

Cannot save loop data from api to json file

i have problem with my code, all i need is just to save results from looping api into json file using writeFileSync. Here’s my code:

function processRarity(limit) {
    var resultJson = [];
    for (var i = limit; i < limit + 100; i++) {
      const everything = async () => {
        const response = await fetch(
          "https://api-v2-mainnet.paras.id/token/asac.near::" + i
        );
        var json = await response.json();
        return json;
      };
      everything().then((res) => {
        console.log(res);
        resultJson = res;
      });
    }
    fs.writeFileSync(`${basePath}/results.json`, JSON.stringify(resultJson, null, 2));
}

when i check my json file, all i get is just:

[]

Opening a popup by calling Javascript from CodeBehind

I am trying to open a popup window by calling a JavaScript function in CodeBehind (vb.net) on a button click event.

The idea is that I click the button, the button click event does a bunch of stuff, then fires the javascript function to open the popup window.

Javascript:

function openSync() {
            var companyId = $("#<%= txtCompanyID.ClientID%>").val();
            $find("<%= RadWindowManager1.ClientID%>").open("SyncDatabases.aspx?CompanyID=" + encodeURIComponent(companyId), "winSyncProcess");
        }

I can call the openSync function in CodeBehind using:

 ScriptManager.RegisterStartupScript(Me, Me.GetType(), "open", "openSync();", True)

When attempting this, I am getting a TypeError: Cannot read properties of null (reading 'open') error.

BUT, if I assign the OnClientClick property on the button itself to

OnClientClick="openSync(); return false;"

the Javascript works fine, and the popup window appears as it should, but doing so ignores the CodeBehind button click event and doesn’t do the things it’s suppose to do.

I am using a RadWindowManger:

    <telerik:RadWindowManager ID="RadWindowManager1" runat="server" EnableShadow="true">
        <Windows>
            <ic:PopupWindow ID="winSyncProcess" runat="server" Width="800px" Height="600px" OnClientClose="OnSyncProcessClose"></ic:PopupWindow>
        </Windows>
    </telerik:RadWindowManager>

Swiper.js not rendering component when used as a slide

I’m adding virtual slides to my swiper with swiper.js. The array that contains the slides, according to the examples, use strings like below (docs say slides: any, but I tried a component and other things, but nothing else worked):

virtual: {
  // cache: true,
  slides: (function() {
    const slides = [];
    for (let i = 0; i < 1; i += 1) {
      slides.push('<img src="https://picsum.photos/600/600/?image=1/>';
    }
    return slides;
  })()
},

Problem – I want to use a custom component ‘app-member-card’ as my slide instead of a string, so I add it as a string like below, but when it’s rendered on the screen it doesn’t interpolate/transpile/compile/render/etc the components code or HTML, the debugger shows the string I passed it.

I’d like to do this:

slides.push(‘<app-member-card class=”router-link” [MemberCard]=”member”></app-member-card>’);

Where this below is what I’d see on the screen:

<div class="card member-card">
  <div class="row">...other tags left out here for verbosity</div>
</div>

Question: Is there something I can do in Angular or swiper.js that will translate this string into the component when adding it as a slide? I couldn’t find anything in the swiper doc and not that familiar with all of the Angular stuff.

What I tried – I tried dynamically creating the component in my .ts file and adding the properties, but when I try and extract the innerHTML as a string from the viewContainerRef all data is empty. Here is my link to that post on SO

Use template literals with conditional logic in hasura GQL mutation

I have a gql mutatation for hasura that both inserts and updates based on whether the $vendorLicenseId has been passed to id like so:

export const UPDATE_LICENSE = gql`
  mutation UpdateLicense(
    $vendorId: Int!
    $licenseId: Int!
    $vendorLicenseId: Int
  ) {
    insert_license_one(
      object: {
        id: $vendorLicenseId:  
        vendor_id: $vendorId
        license_id: $licenseId
      }
      on_conflict: {
        constraint: license_pkey
        update_columns: [
          license_number
          license_id
    ]
  }
) {
  id
  license_id
  vendor_id
  license_number
}

}
`;

The problem is, it’s non nullable and if I just leave it like the rest of the variables, like above and don’t pass the vendorLicenseId, it passes to hasura as null (obviously) and fails:

Is there a way to check in the mutation for the variable to exist and if it doesn’t just omit the entire line?

something like this:

export const UPDATE_LICENSE = gql`
  mutation UpdateLicense(
    $vendorId: Int!
    $licenseId: Int!
    $vendorLicenseId: Int
  ) {
    insert_license_one(
      object: {
        ${ $vendorLicenseId ? `id: $vendorLicenseId`: ``}  
        vendor_id: $vendorId
        license_id: $licenseId
      }
      on_conflict: {
        constraint: license_pkey
        update_columns: [
          license_number
          license_id
    ]
  }
) {
  id
  license_id
  vendor_id
  license_number
}

}
`;

I’ve tried variations of this and can’t get it to work. Is there a right way or better way to do this?

Start, Stop, Pause timer using Functional React-Redux and setInterval?

How do I create a functional pause and restart/pause button using functional React.js for a Pomodoro app? I’ve been able to create the start button but I’m really lost on how I would do pause or restart, since unlike react components I don’t have an easy to access state.

enter image description here

This image shows a preview of what I have so far: the start button works, but I’m unsure how to create functionality for pause and stop/restart. I also want to be able to have the break timer begin after the study timer is finished, but I don’t know how to do that either.

function App() {
  const study_time = useSelector(state => state.study);
  const break_time = useSelector(state => state.break);
  const dispatch = useDispatch();

  const [timer, setCounter] = useState(time());
  //initiating a timeout function, without our mount lifecycle method
  useEffect(() => { // fires on Mount
    const interval = setInterval(() => {
      setCounter(time());
    }, 1000);
    return () => clearInterval(interval); //unmount function to account for memory leaks
  }, [])

  ///////
  const timerRef = React.useRef();
  React.useEffect(() => {
    return () => clearInterval(timerRef.current);
  }, []);
  const [remainingTime, setRemainingTime] = React.useState(study_time * 60);

  const startTimer = () => {
    clearInterval(timerRef.current);
    setRemainingTime(study_time * 60);
    timerRef.current = setInterval(() => {
      setRemainingTime((remainingTime) => {
        if (remainingTime - 1 <= 0) {
          return 0;

        } else {
          return remainingTime - 1;
        };
      });
    }, 1000);
    return () => clearInterval(timerRef.current);
  };
  const minute = String(Math.floor(remainingTime / 60)).padStart(2, 0);
  const seconds = String(remainingTime % 60).padStart(2, 0);

  const pauseTimer = () => {
    //TODO: complete this
  };

  const stopTimer = () => {
    //TODO: complete this

  };

  return (
    <div className="App">
      <div id='Focus-page'>
        <div className='timer-widget'>
          <h3>{date()}</h3>
          <h3>{timer}</h3>
          <div className='together'>
            <div className='left'>
              <Button className="increase" id='stdy-incr' onClick={() => dispatch(incrStdy('study'))}>+</Button>{' '}
              <Button className="decrease" id='stdy-dcr' onClick={() => dispatch(decrStdy('study'))}>-</Button>{' '}
              <h3>{study_time}:00 study</h3>

            </div>
            <div className='right'>
              <Button className="increase" id='brk-incr' onClick={() => dispatch(incrBrk('break'))}>+</Button>{' '}
              <Button className="decrease" id='brk-dcr' onClick={() => dispatch(decrBrk('break'))} >-</Button>{' '}
              <h3>{break_time}:00 break</h3>
            </div>
          </div>
          <br></br>
          <div className='together'>
            <Button onClick={pauseTimer}>Pause</Button>
            <Button onClick={startTimer}>Start</Button>
            <Button onClick={stopTimer}>Stop</Button>
          </div>
          <p>{minute}:{seconds}</p>
        </div>
      </div>
    </div>
  );
}

export default App; 

If there is a cleaner way to do this, please help me out as I’m new to react-redux but wanted to use both in this project for practice.

Dialog of material UI has afterimage when being closed

Introduction

Bascially <Dialog /> receives open and onClose as props. open is boolean from state and onClose is a function that changes the state.

I made <CustomModal /> that wraps <Dialog />, which receives another prop content that defines what to display on <Dialog />.

// CustomModal.jsx

const CustomModal = props => (
  <Dialog {...props} sx={{ '& .MuiDialog-paper': { padding: '2em' } }}>
    {props.content}
  </Dialog>
);

And I’m delivering handlers using context so that my modal could be open and closed everywhere.

// modalHandlersContext.js

const initialState = {
  open: false,
  content: null,
};

const ModalHandlersProvider = ({ children }) => {
  const [modal, setModal] = useState(initialState);
  const handlers = {
    openModal: payload => setModal({ open: true, ...payload }),
    closeModal: () => setModal(initialState),
  };

  return (
    <ModalHandlersContext.Provider value={handlers}>
      {children}
      <CustomModal
        open={modal.open}
        onClose={handlers.closeModal}
        content={modal.content}
      ></CustomModal>
    </ModalHandlersContext.Provider>
  );
};

When I want to open modal somewhere, I execute a function like this

  const onLogin = () =>
    openModal({
      content: <h1>component</h1>,
    });

That is, I pass a component. (I used h1 for a simple example)

Main subject

But when I close it, it’s not clean.

enter image description here

I experimented on this to check when this happens.

It happens

With css, display something from props(same code as above)

const CustomModal = props => (
  <Dialog {...props} sx={{ '& .MuiDialog-paper': { padding: '2em' } }}>
    {props.content}
  </Dialog>
);

It doesn’t happen

  1. Without css, display something from props

enter image description here

const CustomModal = props => (
  <Dialog {...props}>
    {props.content}
  </Dialog>
);

2,3. With/Without css, display just plain text

const CustomModal = props => (
  <Dialog {...props} sx={{ '& .MuiDialog-paper': { padding: '2em' } }}>
    content
  </Dialog>
);
const CustomModal = props => (
  <Dialog {...props}>
    content
  </Dialog>
);

So after that, I tried using <DialogContent /> instead of css but It didn’t work. But I have tried using <Modal /> instead of <Dialog /> and it hasn’t caused any problems.

I wanna use <Dialog /> if possible but now can’t find the cause.
Can anyone help?

trying to create a table that takes a user given image URL and displays it in the cell

hello I’m working on a simple project where a user inputs the information and it goes into a table. I want the user to have the ability to put in the URL for an image and have it show up when the cell is made in the table. I have a button that prompts the user to input a URL but I cant figure out how to put that into an image tag inside the created cell.

let id = 0;

let img = document.getElementById("image").addEventListener("click", () => {
  function getUrl() {
    var url = prompt("Enter image URL");
    if (url) {
      return url;
    } else {
      return getUrl();
    }
  }
  image.src = getUrl();
});

document.getElementById("add").addEventListener("click", () => {
  let table = document.getElementById("list");
  let row = table.insertRow(1);
  row.setAttribute("id", `
test - $ {
  id
}
`);
  row.insertCell(0).innerHTML = document.getElementById("image").src = ""
  row.insertCell(1).innerHTML = document.getElementById("Game-name").value;
  row.insertCell(2).innerHTML = document.getElementById("hours-played").value;
  row.insertCell(3).innerHTML = document.getElementById("new-critic-score").value;
  row.insertCell(4).innerHTML = document.getElementById("new-personal-score").value;
  let actions = row.insertCell(5);
  actions.appendChild(createDeleteButton(id++));
  document.getElementById("Game-name").value = "";
  document.getElementById("hours-played").value = "";
  document.getElementById("new-critic-score").value = "";
  document.getElementById("new-personal-score").value = ""
});

function createDeleteButton(id) {
  let btn = document.createElement("button");
  btn.className = "btn btn-primary";
  btn.id = id;
  btn.innerHTML = "Delete";
  btn.onclick = () => {
    console.log(`
Deleting row with id: test - $ {
  id
}
`);
    let elementToDelete = document.getElementById(`
test - $ {
  id
}
`);
    elementToDelete.parentNode.removeChild(elementToDelete);
  };
  return btn;
}