javascript swap two elements in an array issue using arrays destructuring [duplicate]

I’m a novice in Javascript and I was stuck in a leetcode question due to the js syntax, which involves swapping two elements in an array. The complete code in JS is shown below:

/**
 * @param {number[]} nums
 * @return {number[][]}
 */
var permute = function(nums) {
    const n = nums.length
    const rs = []
    const dfs_swap = (idx, path) => {
        if (idx >= n - 1) {
            rs.push([...path])
            return
        }

        for (let i = idx; i < n; i++) {
            [path[i], path[idx]] = [path[idx], path[i]]
            dfs_swap(idx + 1, path)
            [path[i], path[idx]] = [path[idx], path[i]]
        }

    }
    dfs_swap(0, [...nums])
    return rs
};
// test case below
permute([1,2,3])

But I received the an runtime error below:

Line 17 in solution.js
            [path[i], path[idx]] = [path[idx], path[i]]
                                 ^
TypeError: Cannot set properties of undefined (setting '2')
    Line 17: Char 34 in solution.js (dfs_swap)
    Line 16: Char 13 in solution.js (dfs_swap)
    Line 21: Char 5 in solution.js (permute)
    Line 35: Char 19 in solution.js (Object.<anonymous>)
    Line 16: Char 8 in runner.js (Object.runner)
    Line 24: Char 26 in solution.js (Object.<anonymous>)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
Node.js v20.10.0

I was using the debugger to look into the code at runtime and found everything looked fine there before getting that runtime error. I even tried to run this in my Chrome’s developer console but ended up with the same error.

Then, I only added one thing to solve this error: I added a semicolon after dfs_swap(idx + 1, path), that is:

        for (let i = idx; i < n; i++) {
            [path[i], path[idx]] = [path[idx], path[i]]
            dfs_swap(idx + 1, path);
            [path[i], path[idx]] = [path[idx], path[i]]
        }

After this, I was even more confused about this and ChatGPT failed to give me a plausible answer for that. I pretty much appreciate any help or insights on this, and thank you in advance!

Play Youtube in VSCode

Can I create a VSCode extension which plays a youtube video when I provide a URL inside an iframe.

Is this allowed by VSCode ?

I’m asking because, I tried to develop one and the video is loading in iframe but I’m not able to play and getting error in iframe saying An error occurred. Please try again later.

Infinite slider doesn’t repeat list icons & stops briefly after one cycle before repeating

I’m working on an infinite slider using Angular 17, HTML, SCSS, and TypeScript. The slider works as expected initially, but after all icons from the list have been displayed once, nothing is visible for a few seconds before the animation restarts from the beginning.

I want the slider to loop seamlessly, showing the same icons again without any pause.

My HTML:

<div class="slide-track" #sliderTrack>
  @for (item of slider_items; track item) {
    <div class="slide mr-8">
      <img ngSrc="{{ item.image_url }}" width="64" height="64"
           alt="Clank ~ Discord-Bot (Guild {{ item.guild_name}} Icon)" class="img-fluid rounded-full" />
    </div>
  }
</div>

TypeScript from component:

export class LandingPageComponent implements AfterViewInit {
  @ViewChild('sliderTrack')
  protected sliderTrack!: ElementRef<HTMLDivElement>;
  protected readonly nav_items = nav_items;
  protected slider_items: SliderItems[] = [
    {
      image_url: 'https://cdn.discordapp.com/icons/671065574821986348/313528b52bc81e964c3bd6c1bb406b9b.png?size=64',
      guild_name: 'Bl4cklist',
      guild_invite: 'https://discord.gg/bl4cklist'
    },
    // additional items...
  ];

  constructor(private animations: AnimationService) {
    // clone the list for the slider; is needed for the infinite loop
    this.slider_items = [...this.slider_items, ...this.slider_items];
  }

  ngAfterViewInit(): void {
    // set amount of slides for the infinite loop
    this.sliderTrack.nativeElement.style.width = `calc(150px * ${this.sliderTrack.nativeElement.children.length / 2})`;
  }
}

My SCSS:

.slider {
  background: transparent;
  box-shadow: 0 10px 20px -5px rgba(0, 0, 0, .125);
  margin: auto;
  overflow:hidden;
  position: relative;
  width: 960px;

  &::before,
  &::after {
    content: "";
    height: 100px;
    position: absolute;
    width: 200px;
    z-index: 2;
  }

  &::after {
    right: 0;
    top: 0;
    transform: rotateZ(180deg);
  }

  &::before {
    left: 0;
    top: 0;
  }

  .slide-track {
    animation: scroll 40s linear infinite;
    display: flex;
    width: calc(150px * 10);
  }

  .slide {
    height: 64px;
    width: 64px;
  }
}

Showcase of the problem (it’s speed-up because of the little waiting time at the end):
Showcase

Web application using Rafael JS crashes on Safari and Chrome after updating to iOS 18.2

After updating my phone to iOS 18.2 2 days ago, I noticed that a website I’m working on that uses Rafael JS(https://dmitrybaranovskiy.github.io/raphael) to do some svg rendering which used to work before I updated just stopped working. I am also using this library for importing svg into Rafael: (rafael-svg-import)

I notice that Safari tries to load website tries to load 2 or 3 times before showing the error: A problem repeatedly occurred on which I find really odd since this used to work before and I haven’t made any changes to the code.

This also happens in Chrome on iOS 18.2.

Websockets in JavaScript: concurrency issue?

I an application, a microcontroller system is controlled through a web interface (connected through WiFi). Communication occurs using a web socket.

This works, but from time to time I receive garbage messages on the microcontroller side. This seems to happen mostly when more data is transferred through the web socket. But data amounts really are not very high.

My question now is whether in the javascript part, when messages are sent from “multiple places”, the messages can be “mixed” up. In other words, is some kind of mutex required to lock access to the websocket?

Here is a sketch of how the code looks like:

    ws = new WebSocket('ws://' + location.host + '/xxx');

    (...)

    function do_send(message) {
        try {
            ws.send(message);
        } catch (err) {
            (...)
        }
    }   
    
    function tick() {
        try {
            do_send('{"tick": 1}');
        }
        catch (err) {
            console.log("*** !!! ERROR in tick(): " + err);
        }
    }

    (...)
    
    setInterval(tick, 2000);

    (...)

    function send_params() {        
        var params = {
            xxx: yyy,
        };

        do_send(JSON.stringify(params));
    }

    /* send_params is registered as event handler in several GUI elements */

Basically, there is a “tick” function that periodically sends a “ping” message to the controller, just to notify that an interface is connected.

My question now is whether there are concurrency issues on the javascript side. For example, when two GUI elements are modified rapidly after each other, then send_params() is called multiple times. Could these two calls interfere? Also, could the tick() heartbeat function be called while a GUI-triggered event leads to the invocation of send_params() ?

I understand that this boils down to whether some sort of concurrency occurs in this JavaScript code. From what I understand about JavaScript, this should not be the case, but I am not totally sure, especially what concerns I/O through the websocket.

Error: Prisma Migrate has detected that the environment is non-interactive, which is not supported

I want to create new table add schema.prima:

model REF_DOMAIN_GSTANDARDS {
  Data_Domain_GS String? @db.VarChar(Max) 
  DomainGSID    Int     @id@default(autoincrement()) 
}

then i run in cmdnpx prisma migrate dev --name add_ref_domain_gstandards
but got error:

Environment variables loaded from .env
Prisma schema loaded from prismaschema.prisma
Datasource “db”: SQL Server database

Error: Prisma Migrate has detected that the environment is non-interactive, which is not supported.

prisma migrate dev is an interactive command designed to create new migrations and evolve the database in development.
To apply existing migrations in deployments, use prisma migrate deploy.

Streaming response from a POST request stops processing when in another browser tab

I am making an API call to OpenAI and getting a streaming response back. Here is the API call:

    response = await fetch(url, {
        method: "POST",
        headers: { ...headers, "Content-Type": "application/json" },
        body: JSON.stringify(request)
    });

The response.body property is thus a ReadableStream which is then processed via this snippet of code:

            var i = 1;
            for await (const event of readNDJSONStream(response.body)) {
                console.log("event", event);
                console.log(i);
                i++;
                if (event["context"] && event["context"]["data_points"]) {
                    event["message"] = event["delta"];
                    askResponse = event as ChatAppResponse;
                } else if (event["delta"]["content"]) {
                    setIsLoading(false);
                    await updateState(event["delta"]["content"]);
                } else if (event["context"]) {
                    // Update context with new keys from latest event
                    askResponse.context = { ...askResponse.context, ...event["context"] };
                } else if (event["error"]) {
                    throw Error(event["error"]);
                }
            }

The streamed response is rendered in my webpage as it comes in, and so the user sees it coming in the same fashion like ChatGPT does in the browser (each word gets added to the page one at a atime as it gets streamed in).

The issue is that when I switch to another tab in the browser, the streaming and the rendering slows down tremendously (maybe only 1 line of text shows up in the webpage while spending around 5 minutes on a different tab), and then starts running quickly again once that I am back in the tab.

Is there something I can do to have it continue processing and rendering in the background while I am on another tab?

Androidstudio (built 22 november) ladybug macos intel edition missing javascript typescript plugin

Is it just me? I went to the official download page, downloaded the install image for macos, intel edition and installed android studio. Most things works great, including gemini. Well as good gemini can work at least. I wrote a simple ma application for android (dont ask), and discovered that i didnt get syntax highlighting in the editor on the javascript portions of the html file which defined the azure map component. So I went down the rabbit hole (settings–> plugins choose the installed tab and expected to fins the javascript and typescript plugin to be disabled. But i couldnt find it at all. After some searching i discovered that it wasnt in the plugin folder, and looking directly in the installation package as downloaded from the android studio website it wasnt present there either.

So what gives, is this a bug, or is it it simply ommited and the javascript support has been removed in ladybug? Or is this support moved somewhere elese or? As in a specific plugin which has to be gotten from the marketplace instead from the bundled plugins?

I am completly lost here…

React Native OTP Input – Cursor Not Centered in TextInput Box

I’m building an OTP input component in React Native with four TextInput boxes, but I’m facing an issue where the cursor is not centered inside the box. Instead, it’s aligned to the right side of the box.

Here’s the relevant code I’m using:

<View style={styles.otpContainer}>
  {[...new Array(4)].map((_, index) => (
    <TextInput
      ref={ref => { inputs.current[index] = ref; }}
      style={[styles.otpInput, focusedIndex === index && { borderColor: tertiary }, emptyOtp && { borderColor: '#D00000' }, invalidOtp && { borderColor: '#D00000' }]}
      key={index}
      keyboardType="number-pad"
      maxLength={1}
      selectTextOnFocus
      contextMenuHidden
      testID={`OTPInput-${index}`}
      onChangeText={text => handleChangeText(text, index)}
      onKeyPress={e => handleKeyPress(e, index)}
      placeholder={focusedIndex !== index ? '•' : ''}
      onFocus={() => setFocusedIndex(index)} 
      onBlur={() => setFocusedIndex(-1)} 
    />
  ))}
</View>
otpContainer: {
  flexDirection: 'row',
  alignItems: 'center',
  justifyContent: 'center',
  gap: 8,
  marginTop: 40,
  textAlign: 'center',
},
otpInput: {
  borderWidth: 1,
  borderColor: '#ccc',
  borderRadius: 8,
  paddingHorizontal: 16,
  textAlign: 'center',
  fontSize: 24,
  color: '#000',
  lineHeight: 55,
  width: 55,
  height: 55,
}

The TextInput cursor seems to be slightly off-center, leaning towards the right side. I’ve already ensured that the textAlign: 'center' is set, but it still doesn’t work as expected.

Things I’ve tried:

  • Removing padding and adjusting lineHeight.
  • Ensuring width and height are consistent with fontSize.
  • Adjusting textAlign properties.

Has anyone faced this issue before or have any suggestions for fixing the cursor alignment?

Insert DOM element on the specific index of parent DIV

There is a DIV in Angular template:

<div #parent [innerHTML]="content"></div>
and in .ts file

let content = 'test1 test2 test3'

Now I’m creating new DIV:
const newDiv = this.renderer.createElement('div') as HTMLDivElement
newDiv.innerHTML = 'plug'
newDiv.addEventListener('click'......)

Goal is to have inside #parent:
test1 <div>plug</div> test2 test3
and new div should have working listener.

How?

Manipulating innerHTML as string directly is not a solution: div exists but it is invisible for Angular engine.

Is there a framework that does this kind of SSR? [closed]

Question

I’m looking for a full-stack JS framework that is client first (i.e. the basic architecture is client side routing + client side data fetching) but also supports SSR on first page load (e.g. for SEO) without any modifications to the code (i.e. it awaits queries with the same interface).

Here’s an example using something like React, but the same applies to any framework:

export const Component = () => {
    const data = useSomeQuery(); // this is awaited on the server on first page render and also can be a RPC/fetch on the server if the page is loaded via client side routing 
    return (<div>{data}</div>);
}

Is there something like this somewhere? If not, why not (e.g. are there technical limitations I’m not seeing)?


What have I tried?

Most frameworks I’ve tried do some parts of this (arguably the most complicated ones like RPC creation) but each one has a different way to express queries and mutations and often times different ways to SSR a query vs calling it client side.

For example:

For Next.JS this is the recommended approach in v15:

  • For SSR data fetching => server components with a simple async function
  • For client side data fetching => fetch or react-query or similar
  • For mutations => "use server" server action that is converted to a RPC call

Some add events are missing when copying many files into watched folder

Chokidar Version: 3.5.2

When copying many files, e.g. hundreds of files into the watched folder, I found number of add events is not equal to the total number of files, i.e. some add events are missing.
Following is the configuration of chokidar.

let defaultOptions = {
    ignored: /(^|[/\])../, // ignore dotfiles
    persistent: true,
    depth: 99,
    alwaysStat: true,
    awaitWriteFinish: {
        stabilityThreshold: 3000,
        pollInterval: 100
    },
    ignorePermissionErrors: false,
    ignoreInitial: true,
    atomic: true // or a custom 'atomicity delay', in milliseconds (default 100)
};

I have also tried with usePolling = true. but, it didn’t work for me. could anyone help us with this?

How does deviceinfo.me detect mobile model?

I was wondering, if anyone has any clue as to how would one detect a mobile phone model using javascript?

Everywhere I look, people are recommending to detect this from user agent.
I have noticed that when you simulate mobile device using devTools, user agent returns model number.
But this is not a case in real world.
In real world, the model number is omitted and you cannot detect the model from userAgent.

But there is this site, deviceinfo.me that detects my mobile model, even though my user agent does not provide it.

Does anyone have any idea how do they manage to do this?

enter image description here

How to Use koffi with Struct Pointers

#pragma pack(1)
struct EnvInfo
{
DWORD dwSize; 
WCHAR wszAppId[128]; 
ULONGLONG u64Qid; 
};

extern "C" int __stdcall SDK360_Init(const EnvInfo* pEnvInfo);

this c++ code

const envInfo = koffi.pack('envInfo', {
    dwSize: 'uint32',
    wszAppId: koffi.array('char16', 128),
    u64Qid: 'uint64'
});

const arr = 'xtI7nxn';
const utf16Buffer = new Uint16Array(128); 
arr.forEach((char, index) => {
    utf16Buffer[index] = char.charCodeAt(0);
});

envInfo.dwSize = koffi.sizeof(envInfo);
envInfo.wszAppId = utf16Buffer;
envInfo.u64Qid = 3269309681;

const sdk360 = koffi.load(dynamicLib);
const SDK360_Init = sdk360.func('SDK360_Init', 'int', [koffi.pointer(envInfo)]); 

const result = SDK360_Init(envInfo);

I tried to do this, but I get an error, I don’t know what’s wrong.

TypeError: Unexpected Type value, expected envInfo *