Roman to Integer using JavaScript could not pass all tests

I am trying to solve this problem Roman to integer problem in LeetCode by using JavaScript. The code I got so far did not pass all tests. it is working only in some of the cases.
for example, it passes test for “III” and it returns back 3, but for case where the string is “LVIII”, it returns only 57 instead of 58. Also in case where string is “MCMXCIV”, it returns back 1990 instead of 1994. It seems that the for loop stopped too early for some reason.
Can someone please have a look at it and please let me know where I got it wrong, thanks.

var romanToInt = function(s) {
    var strArr = s.split('');
    var numArr = [];

    var int = 0;

    for(var i=0; i<strArr.length; i++) {
        if(strArr[i] === 'I'){
            numArr.push(1)
        } else if(strArr[i] === 'V') {
            numArr.push(5)
        }else if(strArr[i] === 'X') {
            numArr.push(10)
        }else if(strArr[i] === 'L') {
            numArr.push(50)
        }else if(strArr[i] === 'C') {
            numArr.push(100)
        }else if(strArr[i] === 'D') {
            numArr.push(500)
        }else if(strArr[i] === 'M') {
            numArr.push(1000)
        }
    }

    for(var i=0; i<=numArr.length; i++) {
      if(numArr[0] === 1000) {
        int += 1000;
        numArr.shift();
    } else if(numArr[0] >= numArr[1]) {
        int += (numArr[0] + numArr[1]);
        numArr.splice(0, 2);
    } else if(numArr[0] < numArr[1]){
        int += (numArr[1] - numArr[0]);
        numArr.splice(0, 2);
    } else {
        int += numArr[0]
    }
    }
    

   return int;
};

console.log(romanToInt("III"), "should be 3");
console.log(romanToInt("LVIII"), "should be 58");
console.log(romanToInt("MCMXCIV"), "should be 1994");

Javascript memory allocation while passing objects to functions

recently I had problem with long minor and major gc sweeps in my app, overall I was allocating too much memory too quickly. But it also got me thinking on such case: Often when there are multiple arguments to function I’m creating an object to not mess up order and I’m wondering how much does it affect minor and major gc sweeps. Consider 2 scenarios:

  1. const fn = (arg1, arg2, arg3, arg4) => {...}
  2. const fn = ({ arg1, arg2, arg3, arg4 }) => {...}

Subtle change, but in first example we are not allocating any memory right? All of the variables are already defined and have memory allocated for them. In the second example if we want to call this function, we have to create object therefore allocate memory.

So I was wondering if I’m calling 2nd function very quickly, like every few ms, is it making garbage collector sweeps a lot longer, or maybe it’s negligible? Does it even allocate memory or JS engines are taking care of that and it’s basically free as in 1st example?

How to display current logged In User in SharePoint Using SPFx?

I am working on a SharePoint Web part using SPF to display welcome a message to current logged in user. I am new to SPF and with little knowledge in JavaScript.

I Have tried this code which displays the list of properties. But i am not sure how to only display the user first name.

` private GetUserProperties(): void {
pnp.sp.profiles.myProperties.get().then(function(result) {
var userProperties = result.UserProfileProperties;
var userName = “”; userProperties.forEach(function(property: { Key: string; Value: string; }) {

userName += property.Key + ” – ” + property.Value + “
“;

});

document.getElementById(“FirstName”).innerHTML = userName;
})

type here

.catch(function(error) { console.log(“Error: ” + error); });
}`

adding custom class by row in RShiny using jQuery

This question is just an extention of this question

The following code consists of two containers or divs or bucket_lists from the sortable R package and each bucket_list consists of two add_rank_list functions.

The first container elements are completly unmovable where the disabled arguments in each add_rank_list are set to TRUE, while the second container allows the user to drag and drop the items except the first item, since the disabled argument in the first add_rank_list function is set to TRUE but in the second function is set to FALSE.

I would like to apply a red background color to the element in the second container if its value is “Camp”, and allow it to be moved by the user. Additionally, I would like to apply the same background color to any element in the first container that shares the same index or row as the “Camp” element. Despite attempting different methods, I have been unable to achieve this outcome. Any assistance would be greatly appreciated.

library(shiny)
library(sortable)

ui <- fluidPage(
  actionButton(inputId = "id1", "run"),
  uiOutput("id2")
)

server <- function(input, output, session) {
  observeEvent(input$id1, {
    output$id2 <- renderUI({
      tagList(
        tags$style(
          HTML(paste0("
              .custom-sortable .rank-list-item-Camp {
              background-color: red 
              }
                      "))
        ),
        tags$script(
          HTML("
                $(document).ready(function() {
                $('.custom-sortable .rank-list-item').each(function(index) {
                if ($(this).text() === 'Camp') {
                targetIndex = index;
                }
                });
                $('.custom-sortable .rank-list-item').eq(targetIndex).addClass('rank-list-item-Camp');
                });
                     ")
        ),
        div(
          style = "width: 15%; float: left; overflow: hidden;",
          bucket_list(
            header = NULL,
            class = c("default-sortable","custom-sortable" ),
            orientation = c("vertical"),
            add_rank_list(
              text = NULL,
              labels = 100,
              options = sortable_options(disabled = T)
            ),
            add_rank_list(
              text = NULL,
              labels = c(50,40,30,15),
              options = sortable_options(disabled = T)
            )
          )
        ),

        div(
          style = "width: 15%; float: left; overflow: hidden;",
          bucket_list(
            header = NULL,
            class = c("default-sortable", "custom-sortable"),
            orientation = c("vertical"),
            add_rank_list(
              text = NULL,
              labels = c("Fixed"),
              options = sortable_options(disabled = T)
            ),
            add_rank_list(
              text = NULL,
              labels = c("Camp", rep("No Info",3)),
              options = sortable_options(disabled = F)
            )
          )
        )
        
      )
    })
  }
 )
}

shinyApp(ui, server)

I sent a link on Discord, how can I delete the title at the top of the incoming message?

enter image description here

export function getDynamicHeadContent(config: SiteConfig) {
  return (
    <>
      {/* base */}
      <title>{config.title}</title>
      <meta name="description" content={config.description} />
      <meta property="og:image" content={config.previewImageUrl} />

      {/* facebook */}
      <meta property="og:title" content={config.title} />
      <meta property="og:description" content={config.description} />
      <meta property="og:site_name" content={config.title} />

      {/* twitter */}
      <meta name="twitter:title" content={config.title} />
      <meta name="twitter:description" content={config.description} />

      {/* pwa */}
      <meta name="application-name" content={config.title} />

      {/* apple */}
      <meta name="apple-mobile-web-app-title" content={config.title} />
    </>
  )
}

My React code is as above. Which meta tag should I delete so that the title above is gone?

I deleted the meta tag with property=”og:title” but it didn’t work

TypeError: Cannot read properties of null (reading ‘setTabColor’)

I have minimal knowledge about coding or javascript but I tried to generate a code with ChatGPT but when I try to run it in google apps script it gives me an error saying: TypeError: Cannot read properties of null (reading ‘setTabColor’)

The script it supposed to create a google sheets for me.
This is the script I am trying to run:

`function createTaskTracker() {
// Create a new Google Sheets document
var sheetName = “Task Tracker”;
var spreadsheet = SpreadsheetApp.create(sheetName);

// Set up the tabs for the document
var tabs = ["Overall", "Work", "Social Media", "Workout", "Freetime", "Long-Term         Progress"];
for (var i = 0; i < tabs.length; i++) {
var tabName = tabs[i];
var sheet = spreadsheet.insertSheet(tabName);
}

// Set the tab colors to match the categories
var colors = ["#ffffff", "#00ff00", "#0000ff", "#ffff00", "#ff0000"];
var categoryTabs = ["Work", "Sports/Training", "Freetime", "Social Media"];
for (var i = 0; i < categoryTabs.length; i++) {
var categoryTab = categoryTabs[i];
var colorIndex = i + 1;
var sheet = spreadsheet.getSheetByName(categoryTab);
var color = colors[colorIndex];
sheet.setTabColor(color);
}

// Set up the column headers for each tab
var headers = ["Task", "Routine", "Time Spent", "Status", "Progress"];
var tabsWithHeaders = ["Work", "Sports/Training", "Freetime", "Social Media"];
for (var i = 0; i < tabsWithHeaders.length; i++) {
var tabName = tabsWithHeaders[i];
var sheet = spreadsheet.getSheetByName(tabName);
sheet.appendRow(headers);
}

// Freeze the first row on each tab
for (var i = 0; i < tabs.length; i++) {
var tabName = tabs[i];
var sheet = spreadsheet.getSheetByName(tabName);
 sheet.setFrozenRows(1);
}

// Rename the default sheet to "Settings"
var defaultSheet = spreadsheet.getSheetByName("Sheet1");
defaultSheet.setName("Settings");

// Add a message to the main tab
var mainTab = spreadsheet.getSheetByName("Overall");
mainTab.getRange("A1").setValue("Welcome to your Task Tracker!");

}`

Since I have minimal knowledge about scripts I really had no solution or didn´t find a direct answer from a google search.

Nuxt alias not found

I’ve got a nuxt project in a ‘mono-repo’. I want to use components in my nuxt project from a different project within the mono repo.

In nuxt.config.ts I’ve added an alias:

import { defineNuxtConfig } from "nuxt/config";

export default defineNuxtConfig({
  modules: ["@nuxtjs/tailwindcss"],
  srcDir: "src",
  devServer: {
    port: 3000,
  },
  imports: {
    autoImport: false,
  },
  typescript: {
    strict: true,
    typeCheck: "build",
  },
  alias: {
    "@components": "../components/src/components",
  },
});

It’s imported like this:

<template>
  <Footer />
</template>

<script lang="ts" setup>
import Footer from "@components/Footer/Footer.vue";
</script>

However, I keep this error when building (npm run dev):

ERROR Failed to load url
/components/src/components/Footer/Footer.vue (resolved id:
/components/src/components/Footer/Footer.vue) in
/Users/jamie/Documents/code/project/packages/project/src/pages/Layout/BaseLayout.vue.
Does the file exist?

How should i write a throttle decorator for function attribute?

I want to write a throttle decorator for a function attribute?But i’m stucked in the closure issues.

My code is as follows:

function throttle(timecount) {
    return function (value, { name, kind }) {
        let origin = value
        if (kind === 'method') {
            return function (args) {
                setTimeout(function (args) {
                    // Following 'this' is always Timeout closure, how shoould i do ???
                    origin.apply(this, args)
                }, timecount)
            }
        }
    }
}

class D {
    message = "hello!";

    @throttle(1000)
    m() {
        console.log('excutet', this.message);
    }
}

let y = new D('sss');
y.m(); // i got undefined ???

How should get the right context and get the right answer?

javascript carousel not workong

i’m trying to make a carousel with different slides in my website with javascript through a youtube tutorial i followed https://www.youtube.com/watch?v=9HcxHDS2w1s&t=605s, but it’s not working, i checked my code and there is no mistake in it

here is my html and js:

<script>
        
        //carousel script
        const buttons = document.querySelectorAll("[data-carousel-button]")

        buttons.forEach(button => {
        button.addEventListener("click", () => {
        const offset = button.dataset.carouselButton === "next" ? 1: -1
        const slides = button.closest("[data-carousel]").querySelector('[data-slides]')

        const activeSlide = slides.querySelector("[data-active]")
        let newIndex = [...slides.children].indexOf(activeSlide) + offset
        if(newIndex < 0) newIndex = slides.children.length - 1
        if(newIndex >= slides.children.length) newIndex = 0

        slides.children[newIndex].dataset.active = true
        delete activeSlide.dataset.active
     })
})
        </script>
        <div class="carousel" data-carousel>

            <button class="carousel-button prev" data-carousel-button="prev">Vorige</button>
            <button class="carousel-button next" data-carousel-button="next">Volgende</button>

            <ul data-slides>
                <li>
                    <div class="Slide" data-active>
                        <div class="Avatar"></div>
                        <div class="InfoHeader"><h1>Wie ben ik?</h1></div>
                        <div class="Info1">Mijn naam is Mohammed, ik ben 18 jaar oud en mijn passie is om te creëren. zelf ben ik een hard werkende man die achterzijn doelen aan gaat. Ik snap hoe belangrijk het is om te hard werken, om iets van je leven te maken!</div>
                    </div>
                </li>

                <li>
                    <div class="Slide">
                        <div class="Avatar"></div>
                        <div class="InfoHeader"><h1>Mijn Studie.</h1></div>
                        <div class="Info1">Ik Studeer Software Development op Vista College in Heerlen op MBO niveau 4, deze studie heb ik gekozen omdat geïnteresseerd ben in engineering en Software engineer als mijn vervolg opleiding wil doen op het HBO.</div>
                    </div>
                </li>

                <li>
                    <div class="Slide">
                        <div class="Avatar"></div>
                        <div class="InfoHeader"><h1>Wie ben ik?</h1></div>
                        <div class="Info1">Mijn naam is Mohammed, ik ben 18 jaar oud en mijn passie is om te creëren.</div>
                    </div>
                </li>
            </ul>
        </div>

    </section>

and here is my css:

.carousel{
position: relative;

}

 .Slide{
 position: absolute;
 inset: 0;
 opacity: 0;
}

.Slide[data-active]{
 opacity: 1;
}

.carousel > ul{
 margin: 0;
 padding: 0;
 }

 .carousel-button.prev{
 background-color: #1378d6;
 border-radius: 10px;
 position: absolute;
 top: 320%;
 left: 55%;
 transform: translateY(-50%);
 padding: 5px;
 padding-left: 15px;
 padding-right: 15px;
 border: none;
 z-index: 10;
 }

.carousel-button.next{
 background-color: #1378d6;
 border-radius: 10px;
 position: absolute;
 top: 320%;
 left: 62%;
 transform: translateY(-50%);
 padding: 5px;
 border: none;
 z-index: 10;
 }

.carousel-button:focus{
  background-color: #6db9ff;
}

.Avatar{
 vertical-align: middle;
  position: relative;
  border-radius: 50%;
  width: 300px;
  height: 300px;
  background-image: url("../img/Avatar10.jpg");
  background-size: cover;
  left: 15%;
   top: 80%;
  margin-bottom: 20px;
  box-shadow: 9px 9px 9px  black;

 }


.InfoHeader{
  position: absolute;
  top: 60%;
  left: 40%;
  color: #ffffff;
  font-size: 277%;
  font-family: arial black;
  text-shadow: 9px 9px 3px black;
 }


 .Info1{
  position: absolute;
  top: 130%;
  left: 40%;
  color: #ffffff;
   font-size: 138%;
  text-shadow: 9px 9px 3px black;
   margin-bottom: 20px;
  }

can someone please explain why it isn’t working? thankyou

Expect method in Typescript does not work properly

In the below method, if I print animal.meatConsumption, I see that it has a list and the values are correctly populated.

However, it fails in the code expect(animal).toHaveProperty('meatConsumption').

I do not understand why because the property is present in the object. Also, it fails because the received value is some other object and doesn’t find this. How is this even possible?

export async function validateMyMethod(
  jsonData: IAnimal,
  isCarnivorous: boolean) {
  jsonData.animals.forEach(animal=> {
    if (isCarnivorous) {
      logger.info("print the meatConsumption property" + animal.meatConsumption) //works
      expect(animal).toHaveProperty('meatConsumption') // doesn't work
    } else 
      expect(animal).not.toHaveProperty('meatConsumption')
  })
}

Why is an object possibly undefined after a *ngIf check in Angular 14?

We have an object that is defined by an interface, where the category and its name is optional:

export interface Product {
  category?: {
    name?: string,
  }
}

Now we want to render an element only if both the category and its name are set:

<h1 *ngIf="product.category?.name">{{ product.category.name }}</h1>

Unfortunately this throws an error:

TS2532: Object is possibly ‘undefined’.

<h1 *ngIf="product.category?.name">{{ product.category.name }}</h1>`<br>
                                                       ~~~~

I can solve it by either one of these solutions:

<h1 *ngIf="product.category?.name">{{ product.category?.name }}</h1>
<h1 *ngIf="product.category && product.category.name">{{ product.category.name }}</h1>

My question is: Why is the first solution not working?

Uncaught TypeError: (…) is not a function [closed]

`My function is,

    function ChosenDropdownForName() {
        $("#ddlPayee").chosen();
        $("#ddlPayee").chosen({ allow_single_deselect: true });
        $("#txtAmount").focus();
    }

when i run the program and debug it on google chrome, it shows following error.

Uncaught TypeError: ChosenDropdownForName(…) is not a function.
`

How to tell what kind of screen sharing the user selected?

One can retrieve a stream of the users display using navigator.mediaDevices.getDisplayMedia . On some browsers I can also preselect the entire screens tab like so:

const stream = await navigator.mediaDevices.getDisplayMedia({
  // Pre-select the "Entire Screen" pane in the media picker.
  video: { displaySurface: "monitor" },
});

However the user is still free to pick any tab, window or screen they choose. Is there a way to find out what the user picked?