SciPy Spatial equivalent for JS?

I’m attempting to use an equivalent function for scipy.spatial.HalfspaceIntersection in a TS project, i.e. something like:

const halfspaces: number[][] = [[1,2,3,4], [5,6,7,8], ...];
const feasiblePoint: number[] = [0,0,0];
const halfspaceIntersections = sciPyHalfSpaceIntersection(halfspaces, feasiblePoint, true);

In python I would normally do something like:

halfspaces = np.array([[1,2,3,4], [5,6,7,8]])
feasible_point = np.array([0., 0., 0.])
hs = HalfspaceIntersection(halfspaces, feasible_point, incremental=True)

Is there a JS/TS equivalent to do so?

Difference between element.setAttribute and element.style.setProperty

Assuming there is one custom css variable that I want to change it’s value dynamically using JavaScript. I found that using element.style.["--my-custom-var"] = value will not work because it’s a custom variable. Then I found out we can actually add custom css property to an element using element.setAttribute and element.style.setProperty. My question is that what’s the difference between these two approach, such as which approach will have better performance and which one is the better practce if I want to add custom property using JavaScript.

Example:

// both code is able to add custom css rule to the inline style of an element
element.setAttribute('style','--my-custom-var: 10px;');
element.style.setProperty('--my-custom-var', '10px');

Display ‘Read more’ on same line as cut off text after ‘x’ lines

I am trying to add the Read more action on the same line as the cut off text after ‘x’ lines. Right now it is displaying below the cut off text.

<p style={{ overflow: 'hidden', display: '-webkit-box', 
-webkit-line-clamp: 4, line-clamp: 4, -webkit-box-orient: 'vertical' 
}}>
   Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed 
   do eiusmod tempor incididunt ut labore et dolore magna aliqua. 
   Ut enim ad minim veniam, quis nostrud exercitation ullamco 
   laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
   dolor in reprehenderit in voluptate velit esse cillum dolore eu 
   fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 
   proident, sunt in culpa qui officia deserunt mollit anim id est 
   laborum.
</p>
<Button>Read more</Button>

I am able to handle to functionality where it toggles the text by changing the overflow prop to visible/hidden. I am just trying to style it in a way where the Read more is always on the last line in place of the ellipsis.

This currently cuts is off at 4 lines which is correct, but wanting to replace the ellipsis with the Read more button.

Any help is appreciated

Recursion in react js? [closed]

I’m learning React. I know about recursion in plain JS functions. And recently I’ve found that this concept exists in React too. It’s called recursive rendering.

import React from 'react';

const RecursiveComponent = ({ depth }) => {
  // Termination condition
  if (depth <= 0) {
    return null;
  }

  return (
    <div>
      <p>Depth: {depth}</p>
      {/* Recursive call with reduced depth */}
      <RecursiveComponent depth={depth - 1} />
    </div>
  );
};

const App = () => {
  return (
    <div>
      <h1>Recursive Rendering Example</h1>
      {/* Initial depth, adjust as needed */}
      <RecursiveComponent depth={5} />
    </div>
  );
};

export default App;

I did this but it gives me error.

Select2 list of elements moves outside datatable when using a cellphone

I have a responsive datatable that renders a Select element with Select2 on each row. Everything works as expected on a PC. But when using a cellphone, whenever a select is opened, the list of elements moves to the top of the page (outside the datatable).

this is the code I tried:

    $(input).select2({
       dropdownParent: $("#tblTratamiento"),//tblTratamiento is the datatable
    });

I’m not sure what the problem is: If I am not specifying the dropdownParent correctly or the fact that the datatable is responsive.

This is how the the list of elements looks on cellphone

enter image description here

Problemas com o useStates

O problema é que meu useState setScoreTime esá sendo atualizado com minha função timer, quando quero que ele só atualize quando a função hendleStop seja chamada. Mas o problema tem ocorrido quando chamo a função pelo evento da tecla space, quando uso os buttons o código roda normalmente:

import React, { useState, useEffect } from "react";
import "./style.css";
import Buttons from "../Buttons";
import TimeCounter from "../TimeCounter";

export default function StopwatchApp({ setScoreTime }) {
  // State responsável pelo tempo
  const [timer, setTimer] = useState({
    milSecond: 0,
    seconds: 0,
    minute: 0,
  });

  const [intervalState, setIntervalState] = useState();
  const [running, setRunning] = useState(false);

  // Função principal de incremento no state tempo
  const increment = () => {
    setTimer((prevTimer) => {
      let { milSecond, seconds, minute } = prevTimer;

      if (milSecond >= 100) {
        seconds += 1;
        milSecond = 0;

        if (seconds >= 60) {
          minute += 1;
          seconds = 0;
        }
      }

      milSecond++;

      return {
        milSecond,
        seconds,
        minute,
      };
    });
  };

  // Funções controladoras dos eventos Onclick
  const handleStart = () => {
    setRunning(true);

    const intervalId = setInterval(() => {
      increment();
    }, 10);

    setIntervalState(intervalId);
  };

  const handleStop = () => {
    clearInterval(intervalState);
    setRunning(false);
    setScoreTime({
      ms: timer.milSecond,
      s: timer.seconds,
      m: timer.minute,
    });
  };

  const handleReset = () => {
    clearInterval(intervalState);
    setRunning(false);
    setTimer({
      milSecond: 0,
      seconds: 0,
      minute: 0,
    });
  };

  const handleKeyStart = (event) => {
    if (event.code === "Space" && !running) {
      handleStart();
    }
    if (event.code === "Space" && running) {
      handleStop();
    }
  };

  // Função que gera o Listener e Limpa o mesmo
  useEffect(() => {
    document.addEventListener("keydown", handleKeyStart);

    return () => {
      document.removeEventListener("keydown", handleKeyStart);
    };
  }, [running]);

  return (
    <main className="mainContainer">
      <TimeCounter
        minute={timer.minute}
        seconds={timer.seconds}
        milSecond={timer.milSecond}
      />
      <Buttons
        start={handleStart}
        stop={handleStop}
        reset={handleReset}
        running={running}
      />
    </main>
  );
}

Bem tentei várias soluções, mas todas quebram o código e simplesmente não roda.

What does “${}” mean in JavaScript and how can I use it? [duplicate]

I’ve spent a lot of time on Stack Overflow and I keep randomly seeing this ${} but I can’t find out what it actually is, I’ve tried googling it and the only thing I got is that it isn’t native Javascript and it’s jQuery? I honestly don’t know, so I came here.

I found a few uses for them, but I can’t get them to work, which is why I figure that it isn’t native to JS.

Timed Image-slider with Js media-query doesn’t work

I tried to get an image-slider that should change image every two seconds to only be active if the website is smaller than 650px, but it doesn’t work and I don’t know why.
Here is the html-code:

 <div class="kitchen-slider">
            <div class="kitchen-img-box">
            <img src="IMG/kitchen/kitchen.jpg " class="img" width="100%">
            </div>
            </div>

and the javascript:

var slider_img = document.querySelector('.kitchen-slider');
var images = ['kitchen.jpg', 'kitchen2.jpg', 'kitchen3.jpg'];
    var x = 0;
    var max = 3;
    var m = window.matchMedia("(max-width: 650px)");


    myfunction(m);

    m.addEventListener("change",function(){
        myfunction(m);
    });
    
    function myfunction(m){
        if (m.matches) {
    function imgslider(){
       if (x < max) x=images.length;
       x--;
       return setImg();
    } 
    function setImg() {
        return slider_img.setAttribute('src','IMG/' + 'kitchen/' + images[x]);
    }
    setInterval (imgslider, 2000);
} else null;
    }
    
   

I hope you can help me.

Event listener on Enter in the React-Date-Picker library

if anyone has used this library link =>(https://github.com/wojtekmaj/react-date-picker/blob/main/packages/react-date-picker/README.md), can you tell me how to make changes accepted not by onChange but by onKeyDown Enter

Here is the code

const SearchDates = ({ onChangeDate, date }: Props) => {
    return (
        <div className={style.search}>
            <DatePicker
                inputRef={(ref) => {
                    inputs(ref);
                }}
                calendarClassName={'calendar'}
                format="dd-MM-yyyy"
                // onChange={(value: any) => {
                //      onChangeDate(formatDate(value, fullDate));
                // }}

                onKeyDown={(event) => {
                    if (event.key === 'Enter') {
                        const value = event.target.value;
                        console.log(value);
                        onChangeDate(formatDate(value, fullDate));
                    }
                }}
                shouldCloseCalendar={({ reason }) => reason !== 'select'}
                maxDate={new Date(futureYear(1))}
                minDate={new Date(futureYear(0))}
                locale={'ru-RU'}
                dayPlaceholder={'__'}
                monthPlaceholder={'__'}
                yearPlaceholder={'____'}
                clearIcon={date ? <ClearIndicatorIcon /> : null}
                calendarIcon={<CalendarIcon />}
                showNeighboringMonth={false}
                next2Label={null}
                prev2Label={null}
                prevLabel={<ArrowLeft />}
                nextLabel={<ArrowRight />}
                view={'month'}
                formatMonthYear={(locale: string | undefined, date: Date) => formatDate(date, MonthYear) as string}
                value={date ? (isNaN(Date.parse(date)) ? undefined : new Date(date)) : undefined}
            />
        </div>
    );
};
```Anyone who has encountered this problem, can you tell me how to solve this problem.

Promise returning undefined (have tried other solutions on Stack Overflow)

I am trying to capture the value of a network call and can’t seem to get it to work. I have tried solutions from similar posts to no avail. I’m really confused, as looking at the ‘currentInquiry’ network call in devtools, I see the call is successful and does in fact have data.

I am calling the function in component did update, which subsequently makes the network call.

componentDidUpdate(){
  getCurrentInquiry(this.props.inquiry)
//console.log(getCurrentInquiry(this.props.inquiry))
}

async function getCurrentInquiry(inquiry) {
  if (inquiry) {
    const results = await currentInquiry(inquiry).then((response) => 
{
      return response
    });
//console.log(results)
    return results
  } 
  return undefined
}

//Have tried 
async function getCurrentInquiry(inquiry) {
  if (inquiry) {
    const results = await currentInquiry(inquiry)
      return results
    });
//console.log(results)
    return results
  } 
  return undefined
}

I have tried async/await, as well as returning a Promise, to no avail. I am expecting the return value to be the response date from the network call currentInquiry. Thanks in advance!

R shiny dashboard, show conditionalPanel only when a specific tabPanel within a specific sidebar menuItem is selected

Below I have provided the skeleton of a Shiny Dashboard that I am trying to create. I’ve fought with this for quite a while and cannot figure out how to make it work.

App Current Behavior: Right now the “Select Date Range” date input is visible when the Menu Item 1 sidebar item is selected.

Desired Behavior: I would like the “Select Date Range” input to only be visible when “Menu Item 1” and “Tab 1” are selected simultaneously.

library(shiny)
library(shinydashboard)
library(shinyWidgets)
library(lubridate)

generate_dates <- function(start_date, end_date) {
  all_dates <- seq(start_date, end_date, by = "days")
  all_mondays <- all_dates[weekdays(all_dates) == "Monday"]
  return(all_mondays)
}

start_date <- floor_date(as.Date("2023-07-01"), unit = "week", week_start = 1)
end_date <- floor_date(as.Date("2023-12-06"), unit = "week", week_start = 1)
dates <- generate_dates(start_date, end_date)

df <- data.frame(
  Week = dates,
  Value_1 = sample(c("A", "B", "C", "D"), length(dates), replace = TRUE),
  Value_2 = sample(c("X", "Y", "Z", "W"), length(dates), replace = TRUE)
)


sidebar <- dashboardSidebar(
  sidebarMenu(
    id= "sidebarID",
    conditionalPanel(
      condition="input.sidebarID =='menu1'",
      dateRangeInput("complaints_date_range","Select Date Range",
                     start=max(df$Week),
                     end=max(df$Week),
                     min=max(df$Week),
                     max=max(df$Week),
                     format="yyyy-mm-dd"
                     )
    ),
    menuItem("Menu Item 1",tabName="menu1"),
    menuItem("Menu Item 2",tabName="menu2")
  )
)

body<- dashboardBody(
  tabItems(
    tabItem(tabName="menu1",
            tabsetPanel(
              tabPanel("Tab 1"),
              tabPanel("Tab 2")
            )),
    tabItem(tabName="menu2")
  )
)

ui<-dashboardPage(
  dashboardHeader(title="Navigation"),
  sidebar,
  body
)

server<-function(input,output,session){
  
  
  
}

shinyApp(ui,server)

I have tried many different attempts involving different conditions in the conditionalPanel but nothing has worked.

Swiper how to render x next slides

I have been trying to use SwiperJS https://swiperjs.com/, however there seems to be no option that I can find to be able to set that when the slide goes out of view on the left it returns to the right straight away.

Currently it causes this issue, where on the right there is no next slide and it only renders the next slide when it moves.

Example

I have tried reviewing all the docs and searching but was unable to find any documentation or examples on how to solve this issue.

25+5 clock for freecodecamp test fail

I’m making the 25 + 5 clock for the freecodecamp certification but 1 is failing:

User Story #22: When a session countdown reaches zero (NOTE: timer MUST reach 00:00), and a new countdown begins, the element with the id of timer-label should display a string indicating a break has begun.

Timer has reached zero but didn’t switch to Break time

I have used the provided sample 25 + 5 clock, and watched mine side by side to it, and it seems to function the exact same, counts down, changes from Session to Break at the same time, displays Session or Break, and the new countdown, and the sound, at the same time.

I assume it has something to do with the timing. Since they are testing it in a hyper-fast mode, even a micro-second off will fail it, I am assuming. I have tried adjusting the seconds, to no avail. I’ve also tried reorganizing or changing calling sequence in my countDown() function.

I did not do this in REACT, which nearly 100% of students did, which may be my issue. I am seeing how timing is important and perhaps REACT code is better for count down , or clock/time -type code? Mine is pure JavaScript.

Any assistant would be greatly appreciated! Here is the CodePen demo.

Expecting the test to pass, as it seems to function correctly. But, in the hyper-fast state of FCC’s test, it does not.

Only portion of first and last ticks shown in x-axis

I’m only see a portion of the first and last ticks in this d3.js graph. Here’s the JavaScript code:

let margin = ({ top: 50, right: 50, bottom: 50, left: 100 });
let dim = ({ height: 500, width: 1200 });
let svg = d3.select('#foo');

svg.attr('height', dim.height);
svg.attr('width', dim.width);

let dateTimeExtent = [new Date('2023-12-07T08:02:38.000Z'), new Date('2023-12-07T08:10:46.000Z')];
let x = d3.scaleUtc()
  .domain([dateTimeExtent[0]!, dateTimeExtent[1]!])
  .range([margin.left, dim.width - margin.right]);
let ticks = [dateTimeExtent[0], ...d3.utcMinute.every(5)!.range(dateTimeExtent[0], dateTimeExtent[1]), dateTimeExtent[1]];
/* ticks contains [
"2023-12-07T08:02:38.000Z",
"2023-12-07T08:05:00.000Z",
"2023-12-07T08:10:00.000Z",
"2023-12-07T08:10:46.000Z"
]*/

// x-axis
svg.append('g')
  .attr('transform', `translate(0,${dim.height - margin.bottom})`)
  .call(d3.axisBottom(x)
    .tickValues(ticks)
    .tickSizeOuter(0))
  .call(g => g.selectAll('.tick > text')
    .attr('transform', 'rotate(90) translate(23 -12)')) // <-- rotates axis tick
  .call(g => g.append('text')
    .attr('x', dim.width - margin.right)
    .attr('y', -4)
    .attr('fill', 'currentColor')
    .attr('font-weight', 'bold')
    .attr('text-anchor', 'end')
    .text(''));

And the HTML code where the graph in rendered:

<div>
  <svg id='foo'>
  </svg>
</div>

In the graph I only see the seconds portion of the first and last ticks. The other ticks occur at 5 minute intervals and are showing as expected.
enter image description here