shiny javascript column sum over multiple pages of datatable

This is a follow-up question to my previous question which can be found here.

In this code snippet I compute the column sum of a shiny datatable using Javascript as I want it to be shown directly under the datatable.

library(shiny)
library(DT)

ui <- shinyUI(fluidPage(
  h1("Testing TableTools"),
  mainPanel(dataTableOutput("display"))
))

Names <- c("", names(mtcars))
FooterNames <- c(rep("", 5), Names[6], rep("", 6))

server <- function(input, output, session) {
  sketch <- htmltools::withTags(table(
    tableHeader(Names), tableFooter(FooterNames)
  ))
  
  opts <- list(
    footerCallback = JS(
    "function(tfoot, data, start, end, display) {
      var api = this.api(), data;
      var sum1 =  api.column(5).data().reduce(function(a, b) {
        return a + b;
      });
      sum1 = Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(sum1)
      $(api.column(5).footer()).html('SubTotal:  ' + sum1)
    }"
    )
  )
  
  output$display <- DT::renderDataTable(container = sketch, extensions = "Buttons", options = opts, {
    mtcars
  })
}

shinyApp(ui = ui, server = server)

original table

However, sorting the table will change the column sum as the sum is only the sum of the shown column.
I want to change it such that it shows the total sum in case of multiple “pages” of the table and if there is only one page it should compute it as it does now.

sorted table

LG WebOS does not supports embedded subtitles

LG WEBOS does not supports embedded subtitles only an external subtitle As I know the only method to play videos on webOS is by using HTML5 video tag which doesn’t support embedded subtitles. Please there are other methods of playing MKV, MP4 videos with embedded subtitles?

How can I see what triggered a ResizeObserverCallback?

I’m running into a recursive loop with a ResizeObserver, where something inside the observed container is changing the size of the container on re-render, which causes the ResizeObserver to re-trigger.

In this specific case, there are several items I suspect may be causing this, but haven’t been able to pinpoint what causes it. Using the DevTools debugger, I’m able to see the ResizeObserver is triggered, but the Stack trace is empty.

There’s a good chance it’s caused by Javascript, but an equally good chance it’s caused by some part of the css layout, which would not be stack trace-able.

Is there some way to see why the ResizeObserver is called?

I have a problem with this question: building a function called findFirstWordWithMostRepeatedChars

Hi, I don’t understand why my codes don’t work. I will be appreciated it if someone can help me, please thanks.
This is the question:
write a function that finds Max Repeat count In Word:

I think many there is a problem with for loops

// Skeleton

// FUNCTION DEFINITION(S)
function findMaxRepeatCountInWord(word) {
  // Break up individual word into individual letters.
  word = word.split('');
  // Count the instances of each letter
  let objOfLetters = {};
  for (let i = 0; word.length; i++) {
    //if word[i] is not exist in objOfLetters
    if (objOfLetters[word[i]] === undefined) {
      //creat an an prop with key set to word at i and value set to 1
      objOfLetters[word[i]] = 1;
      //otherwize
    }else {
      //add 1 to its value
      objOfLetters[word[i]]++;
    }
    
  }
  // getting all the valuse that are the counts of letters
  let counts = Object.values(objOfLetters);
  let max = counts[0];
  for (let k = 1; k < counts.length; k++) {
    if (counts[k] > max) {
      max = counts[k];
    }
  }
  return max;
}

// ASSERTION FUNCTION(S) TO BE USED

function assertEqual(actual, expected, testName) {
  if (actual === expected) {
    console.log('passed');
  }else {
    console.log('FAILED [' + testName + '] Expected ' + expected + ', but got ' + actual);
  }
}

var input_1 = 'passed';
var actual_1 = findMaxRepeatCountInWord(input_1);
var expected_1 = 2;
assertEqual(actual_1, expected_1, 'it shows that how many times a characters repeated');

What does “First Load JS” in @next/bundle-analyzer actually measure?

The NextJS bundle analyzer gives some output like this:

Page                                                                         Size     First Load JS
┌ λ /                                                                        12 kB           368 kB
├   └ 79.202101.46dabc.chunk.css                                             10.3 kB
...
+ First Load JS shared by all                                                195 kB
  ├ chunks/0e69992b3e9a8d51f37748cf97b75268d47a0f0c.f372af.js                27.6 kB
  ├ chunks/cf0e5769c2fa5761a95adfa95a4e062fb86f8f05.272397.js                91.4 kB
  ├ chunks/commons.9707f2.js                                                 9.01 kB
  ├ chunks/framework.efaa9a.js                                               46.9 kB
  ├ chunks/main.9965a5.js                                                    6.39 kB
  ├ chunks/pages/_app.a4ce0d.js                                              11.4 kB
  ├ chunks/webpack.8e3a04.js                                                 2.72 kB
  └ 62.202101.796f1f.chunk.css                                               3.7 kB

What exactly does “First Load JS” measure and why does it not equal the sum of “First Load JS shared by all” and the size of the page and it’s sub-pages. I.e. based on this output I would expect First Load JS to equal 12 kb + 10.3 kb + 195 kb, not 368 kb.

Thanks.

How to solve the error “TypeError: Cannot read properties of undefined (reading ‘0’)”

I’m building a uber clone and I am the code below to get the price of the ride using the route duration but I keep getting an error
code here:

 const [rideDuration, setRideDuration] = useState(0);

  useEffect(() => {
    rideDuration = fetch(
     `https://api.mapbox.com/directions/v5/mapbox/driving/${pickupCoordinates[0]}, ${pickupCoordinates[1]};${dropoffCoordinates[0]}, ${dropoffCoordinates[1]}?access_token=pk.eyJ1IjoidGhlb2xhYWsiLCJhIjoiY2t2a3R0ajRpMDEzYzJxcWY4ZXN4azlsbSJ9.-W4Ax1SOIIGrkmu_swQ92A`
          )
    .then(res => res.json())
         .then(data => {
    setRideDuration(data.routes[0].duration / 100)
    })
        }, [pickupCoordinates, dropoffCoordinates])

It worked once i.e the price only showed once, then stopped working I keep getting “TypeError: Cannot read properties of undefined (reading ‘0’)” as the error

Multiple directions in mermaid flowchart

The code snippet below creates a flowchart with the three boxes Data, Infrastructure & Modeling, ordered from left to right because of this line of mermaid code: flowchart LR. I would like the first two boxes, Data & Infrastructure to behave like that, but the box Modeling should go below Infrastructure. Is it possible in mermaid to allow for multiple directions?

The final flowchart should look roughly like that:

enter image description here

mermaid.initialize({startOnLoad:true});
<script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
<script>
    mermaid.initialize({ startOnLoad: true });
</script>
<div class="mermaid">
  flowchart LR
  subgraph Data
    direction TB
    da1(Data1) --> api(APis)
    da2(Data2) --> api
    da3(Data3) --> api
  end
  subgraph Infrastructure
    direction TB
    pro(Processing) --> db[(Database)]
    db --> api2(API)
    api2 --> p(Python, R, ...)
    db --> app(Web App)
  end
  subgraph Modeling
    direction TB
    sta(Statistics)
    mal(Machine Learning)
    mem(Mechanistic Models)
  end
  api --> pro
  p --> Modeling
</div>

What is wrong in convert code from js to swift?

I have a js code. I’m trying to convert it to swift

const writeUInt64 = value => {
  const result = [];
  let index = 0;
  while (value > BigInt(rest)) {
    result[index] = BigInt(msg).or(value.and(BigInt(rest))).toJSNumber();
    value = value.shiftRight(7);
    index += 1;
  }

  result[Number(index)] = value.toJSNumber();

  return Buffer.from(result);
};

Need to convert this code to swift. My try:

internal func writeUInt64(_ value: UInt64) -> [UInt8] {
    var result = [UInt8]()
    var value = value
    while (value > UInt64(rest)) {
        result.append(msg | UInt8((Int64((value & UInt64(rest))) >>> 0)))
        value = UInt64(Int64(value) >>> 7)
    }

    result.append(UInt8(value))
    
    return result
};

It is correct ? can you help please

(Mongoose) I’m trying to make a single update query from an array of unique objects of unrelated items, but it doesn’t work

To give you a quick overview, I am trying to get an update query in my express/node/mongoose application that could update x amounts of cards’ data in a single query (where x could be either 0 or + infinite).

Here is what the JSON file looks like at the moment:

{
    "review_update": [
        {
            "_id": "621f2f403e96942c55acfa71",
            "review_lapse": "bite"
        },
        {
            "_id": "621f3d533e96942c55acfb1f",
            "review_lapse": "bite"
        }
    ]
}

Each object represents a unique card (see _id key)

And here is the method in my controller (very inefficient as I use a foreach loop, obviously not very scalable if I had 10.000 cards:

module.exports.updateReviewLapse = updateReviewLapse =  async (req, res, next) => {
    try{
        let updates = req.body.review_update;   
            
            updates.forEach(async item => {
                    let card = await UserDeckCard.findOneAndUpdate(
                        { _id: item._id },
                        { $set: { 
                            review_lapse: item.review_lapse
                        }},
                        { new: true }
                    )
                    console.log(card)

            })


        return res.status(200).json("ok") 
    } catch (err){  return res.status(500).json({ message: "" + err  })}
}

I thought of changing the JSON file, yet that didn’t give any convincing results, nor using Promise.all and I couldn’t achieve anything with updateMany.

Thanks in advance for your help

How to get the starting index and the ending index using a regular expression in a string? [duplicate]

I am unable to understand how to get the start and end index of a substring that matches a regex in a String.
Consider,

const regex = /@([w-.']+(?:s[w-.']+)?)$/g;

const string1 = '[@Shilpa Shetty] [@Rohit Shetty] [@Rohit Bahl] @Salman Khan [@Sonal Shetty]';
const string2 = '[@Shilpa Shetty] [@Rohit Shetty] [@Rohit Bahl] @Salman.Khan [@Sonal Shetty]';
const string3 = '[@Shilpa Shetty] [@Rohit Shetty] [@Rohit Bahl] @Salman-Khan [@Sonal Shetty]';
const string4 = "[@Shilpa Shetty] [@Rohit Shetty] [@Rohit Bahl] @Salman'Khan [@Sonal Shetty]";
const string5 = '[@Shilpa Shetty] [@Rohit Shetty] [@Rohit Bahl] @sal[@Sonal Shetty]';

With help of the defined Regex I want the start Index(index where ‘@’ is present) and the last index aswell as the matched String.

const expectedAnswer = [derivedString, startIndex, endIndex];
const expectedAnswer1 = ['@Salman Khan', 47, 58];
const expectedAnswer2 = ['@Salman.Khan', 47, 58];
const expectedAnswer3 = ['@Salman-Khan', 47, 58];
const expectedAnswer4 = ["@Salman'Khan", 47, 58];
const expectedAnswer5 = ['@sal', 47, 50];

Using map() inside a map() function in Javascript

I have an array of objects:
const accounts = [account1, account2, account3, account4];
and each object is like:

const account4 = {
  owner: 'Sarah Smith',
  movements: [430, 1000, 700, 50, 90],
  interestRate: 1,
  pin: 4444,
};

I need to build the username from each of the objects which is formed by concatenating the first letters of individual words-
Example: For “Sarah Smith”, it is “ss”.
And I have written this code using two maps:

let userNames = accounts.map(account => {
  account.owner
    .toLowerCase()
    .split(' ')
    .map(f => f[0])
    .join('');
});

And when I log the userNames – they are all undefined.

[undefined, undefined, undefined, undefined];

But the output should be something like:

["js","ss","tc","sw"];

where:
js-jonas smith,
ss-sarah smith,
tc-tom cruise,
sw-serena williams.
Why is this happening?

Datatable is blocking events for button click on other pages except page 1

I have a datatable with all the categories in my website. There is a function to delete a categori with AJAX while selecting a category to move the products(websites in my case) to another category. Here’s how I do it:

$(".delete_category_instant").on('click', function(event) {
        $(this).hide();
        $(this).closest("td").find(".editCategory").hide();
        $(this).closest("td").find(".selectCategoryToMove").removeClass("d-none");
      });

      $(".selectCategoryToMove").find(".submitSelection").on('click', function(event){
        $(this).closest("td").find(".selectCategoryToMove").addClass("d-none");
        $(this).closest("td").find(".confirmAction").removeClass("d-none");
        Toast.fire({
          icon: 'warning',
          title: 'Please confirm your action!'
        });
      });

      $(".confirmActionYes").on('click', function(event) {
        var cat_id = $(this).attr('category-id');
        var move_cat_id = $(this).closest("td").find("select").val();
        $this = $(this);
        $.ajax({
            type: 'GET',
            url: '{{ url("administrator/delete/category/") }}',
            data: {
              id: cat_id,
              move_id: move_cat_id
            },
            success: function(response) {
                if(response.status == 1) {
                    Toast.fire({
                      icon: 'success',
                      title: 'Category deleted successfully!'
                    });
                    $this.parents('tr').remove();
                } else if(response.status == 2) {
                  Toast.fire({
                      icon: 'warning',
                      title: 'You are not allowed to do this action!'
                    });
                } else {
                    Toast.fire({
                      icon: 'error',
                      title: 'Could not delete this category!<br/>Please try again later!'
                    });
                }
            },
            error: function(xhr, ajaxOptions, thrownError) {
                console.log(xhr.status);
                console.log(thrownError);
            }
        });
      });

      $(".confirmActionNo").on('click', function(event) {
        $(this).parent().addClass("d-none");
        $(this).parent().closest("td").find(".delete_category_instant").show();
        $(this).parent().closest("td").find(".editCategory").show();
      });

But that’s working only on page 1 in the datatable. Inside other pages the button isn’t even responding on click. What’s the solution of that? Is that a common problem that I need to be aware of in the future?

How can I mimic a Javascript “spread operator” in C#?

I am following a tutorial on Dynamic Programming on youtube to understand more about Recursive functions, and I am stuck where a spread operator is used.

Code in JavaScript

const howSum = (targetSum, numbers) =>{
    if(targetSum === 0) return [];
    if(targetSum < 0) return null;

    for(let num of numbers){
           const remainder = targetSum - num;
           const remainderResult = howSum(remainder, numbers);
            if(remainderResult != null){
                 return [...remainderResult, num];
            } 
    }

}

This is the code in C# where I’m trying to replicate the function

class HowSumSlow {

    static dynamic HowSum(int targetSum, int[] numbers)
    {
            
        if (targetSum == 0) return numbers;
        if (targetSum < 0) return null;

        
        foreach( var num in numbers){
            var remainder = targetSum - num;
            int[] remainderResult = HowSum(remainder, numbers);

            if (remainderResult != null) { 
                //Code here//
            }
        }
        return null;
    }

    static void Main(string[] arg) {
        int[] numbers = new int[] { 2, 3 };
        Console.WriteLine(HowSum(7, numbers));
    }
    
}

Should I use a Dictionary and use a key? I don’t understand how to work my way around this one.

  static Dictionary<int, int[]> spread = new Dictionary<int, int[]>();
            
        static dynamic HowSum(int targetSum, int[] numbers){
        ...
            if(spread.ContainsKey(remainderResult)){
                return spread[remainderResult];
        }
    }

What does it determine the placedItem.width and placedItem.height , when adding one without specifying those properties?

I’m in Adobe Illustrator 2022 26.064 and I’m placing an item. It is the thirdone I place in the same document.

var placedItem3 = doc.placedItems.add();
placedItem3.file = new File("/c/files/dotfiles-win/illustrator-scripts/lorem-picsum/3to2-1080x720.jpg");
placedItem3.name = "placedItem3";

For some reason it gets placedItem.width=3061,41 ,placedItem.height=2040,94
When the file is 1080x720
The previous items were placed keeping the same dimensions of the file.