问:
Why doesn't QWidget clear connections before deleteChildren() call?
I have two simple classes:

```<code>class Parent: public QWidget {
  Q_OBJECT

  public:
    Parent(QWidget * parent): QWidget(parent) {}

  public:
    void slot() const {
      qDebug() << "slot:" << state;
    }

  private:
    int state {
      42
    };
};

class Child: public QWidget {
  Q_OBJECT

  public:
    Child(QWidget * parent): QWidget(parent) {}

    ~Child() override {
      emit signal();
    }

  signals:
    void signal();
};

int main(int argc, char * argv[]) {
  QApplication app(argc, argv);
  QMainWindow w;

  auto * p = new Parent( & w);
  auto * c = new Child(p);
  QObject::connect(c, & Child::signal, p, & Parent::slot);

  QTimer::singleShot(1000, & app, & QApplication::quit);
  w.show();
  return app.exec();
}
</code>```

This program crashes because signal from the child destructor calls a slot of already destructed parent. There is no problem with ~QObject(), which clears all its connections before deleteChildren() call, but ~QWidget() calls this function before base QObject destruction.

Body:
I have two simple classes:

class Parent: public QWidget {
  Q_OBJECT

  public:
    Parent(QWidget * parent): QWidget(parent) {}

  public:
    void slot() const {
      qDebug() << "slot:" << state;
    }

  private:
    int state {
      42
    };
};

class Child: public QWidget {
  Q_OBJECT

  public:
    Child(QWidget * parent): QWidget(parent) {}

    ~Child() override {
      emit signal();
    }

  signals:
    void signal();
};

int main(int argc, char * argv[]) {
  QApplication app(argc, argv);
  QMainWindow w;

  auto * p = new Parent( & w);
  auto * c = new Child(p);
  QObject::connect(c, & Child::signal, p, & Parent::slot);

  QTimer::singleShot(1000, & app, & QApplication::quit);
  w.show();
  return app.exec();
}

This program crashes because signal from the child destructor calls a slot of already destructed parent. There is no problem with ~QObject(), which clears all its connections before deleteChildren() call, but ~QWidget() calls this function before base QObject destruction.


来源: stackexchange

问:
Client database thread pool for connection pool
I'm using Hikari as a connection pool provider library. For each database connection pool, it creates a unique Java thread pool, and you can share one thread pool for scheduled tasks (for keeping connections stable and maintain idle connections).

I have a client logic of sharding queries to a different Postgres physical databases, Hikari creates a different Java thread pool for each database.

The problem is that I have 50 Postgres shards (I choose shard based on a key hash). Hikari creates 50 Java thread pools size of 5 that's why there are a lot of CPU context switches among threads. (Instances are stateless, each one with approximately 5 CPUs that's why I would like to keep as few threads per instance as I can).

I wasn't able to find a way of sharing one Java thread pool among different shards in Hikari.

How can I handle this issue?

ContentLicense: CC BY-SA 4.0


问:
Custom tailwind keyframes not working in NextJS
Following the tailwind docs, I got to the end of this page that says how to add custom keyframes for use with tailwind classes, but can't get any custom animations to work.

I've done the following:

tailwind.config.js

```<code>/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      keyframes: {
          wiggle: {
            "0%, 100%": { transform: "rotate(-3deg)" },
            "50%": { transform: "rotate(3deg)" },
          },
        },
        animation: {
          wiggle: "wiggle 1s ease-in-out infinite",
        },
    },
  },
  plugins: [],
};

</code>```

_app.tsx:

```<code>export default function App({ Component, pageProps }: AppProps) {
  const [notification, setNotification] = useState<Notification | null>(null);

  return (
    <>
      <div className="animate-wiggle wiggle">asdf</div>
      {notification && (
        <Notification type={notification.type} message={notification.message} />
      )}
      <Component {...pageProps} setNotification={setNotification} />
    </>
  );
}
</code>```

And it just doesn't want to work. I can't figure out why. The class is applied, but no keyframe animation. The default tailwind animations work fine.

You can find the whole repo here:
https://github.com/ic-768/word-station

Body:
Following the tailwind docs, I got to the end of this page that says how to add custom keyframes for use with tailwind classes, but can't get any custom animations to work.

I've done the following:

tailwind.config.js

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {
      keyframes: {
          wiggle: {
            "0%, 100%": { transform: "rotate(-3deg)" },
            "50%": { transform: "rotate(3deg)" },
          },
        },
        animation: {
          wiggle: "wiggle 1s ease-in-out infinite",
        },
    },
  },
  plugins: [],
};

_app.tsx:

export default function App({ Component, pageProps }: AppProps) {
  const [notification, setNotification] = useState<Notification | null>(null);

  return (
    <>

asdf

      {notification && (
        <Notification type={notification.type} message={notification.message} />
      )}
      <Component {...pageProps} setNotification={setNotification} />
    </>
  );
}

And it just doesn't want to work. I can't figure out why. The class is applied, but no keyframe animation. The default tailwind animations work fine.

You can find the whole repo here:
https://github.com/ic-768/word-station


问:
Using GLib.IOChannel to send data from one python process to another
I am trying to use GLib.IOChannels to send data from a client to a server running a Glib.Mainloop.

The file used for the socket should be located at /tmp/so/sock, and the server should simply run a function whenever it receives data.

This is the code I've written:

import sys
import gi
from gi.repository import GLib

ADRESS = '/tmp/so/sock'

def server():
    loop = GLib.MainLoop()
    with open(ADRESS, 'r') as sock_file:
        sock = GLib.IOChannel.unix_new(sock_file.fileno())
        GLib.io_add_watch(sock, GLib.IO_IN,
                          lambda *args: print('received:', args))
        loop.run()

def client(argv):
    sock_file = open(ADRESS, 'w')
    sock = GLib.IOChannel.unix_new(sock_file.fileno())
    try:
        print(sock.write_chars(' '.join(argv).encode('utf-8'), -1))
    except GLib.Error:
        raise
    finally:
        sock.shutdown(True)
        # sock_file.close() # calling close breaks the script?

if __name__ == '__main__':
    if len(sys.argv) > 1:
        client(sys.argv[1:])
    else:
        server()
```
<p>When called without arguments, it acts as the server, if called with arguments, it sends them to a running server.
When starting the server, I immediately get the following output:</p>
```received: (<GLib.IOChannel object at 0x7fbd72558b80 (GIOChannel at 0x55b8397905c0)>, <flags G_IO_IN of type GLib.IOCondition>)
```

I don't know why that is. Whenever I send something, I get an output like (<enum G_IO_STATUS_NORMAL of type GLib.IOStatus>, bytes_written=4) on the client side, while nothing happens server-side.

What am I missing? I suspect I understood the documentation wrong, as I did not find a concrete example.

I got the inspiration to use the IOChannel instead of normal sockets from this post: How to listen socket, when app is running in gtk.main()?

Body:
I am trying to use GLib.IOChannels to send data from a client to a server running a Glib.Mainloop.

The file used for the socket should be located at /tmp/so/sock, and the server should simply run a function whenever it receives data.

This is the code I've written:

import sys
import gi
from gi.repository import GLib

ADRESS = '/tmp/so/sock'

def server():
    loop = GLib.MainLoop()
    with open(ADRESS, 'r') as sock_file:
        sock = GLib.IOChannel.unix_new(sock_file.fileno())
        GLib.io_add_watch(sock, GLib.IO_IN,
                          lambda *args: print('received:', args))
        loop.run()

def client(argv):
    sock_file = open(ADRESS, 'w')
    sock = GLib.IOChannel.unix_new(sock_file.fileno())
    try:
        print(sock.write_chars(' '.join(argv).encode('utf-8'), -1))
    except GLib.Error:
        raise
    finally:
        sock.shutdown(True)
        # sock_file.close() # calling close breaks the script?

if __name__ == '__main__':
    if len(sys.argv) > 1:
        client(sys.argv[1:])
    else:
        server()

When called without arguments, it acts as the server, if called with arguments, it sends them to a running server.
When starting the server, I immediately get the following output:

received: (<GLib.IOChannel object at 0x7fbd72558b80 (GIOChannel at 0x55b8397905c0)>, <flags G_IO_IN of type GLib.IOCondition>)

I don't know why that is. Whenever I send something, I get an output like (<enum G_IO_STATUS_NORMAL of type GLib.IOStatus>, bytes_written=4) on the client side, while nothing happens server-side.

What am I missing? I suspect I understood the documentation wrong, as I did not find a concrete example.

I got the inspiration to use the IOChannel instead of normal sockets from this post: How to listen socket, when app is running in gtk.main()?


问:
Integrating an optional "App Shell" into React Router
I want my React website normally to have an "app shell" (header, footer, sidebar with menu, etcetera) but for specific URI paths...I want those "app shell" elements to disappear.  I am new to React and React Router, so I came up with this (incorrect) solution:

import { OuterShell } from './OuterShell';
import Home from './home';
import About from './about';
import Login from './login';
import { Route, Routes } from "react-router-dom";

function App() {
  return (
    <>
      <MantineProvider withGlobalStyles withNormalizeCSS theme={{
        fontFamily: "fantasy",
        colorScheme: "dark"
      }}>

          <Routes>
            //This "OuterShell" contains my Mantine "App Shell" (header, footer, menu...).
            <OuterShell>
              <Route path="/" element={<Home />} />
              <Route path="/about" element={<About />} />
            </OuterShell>

            //HERE IS THE ISSUE...
            //I want this component path to render WITHOUT the "App Shell"
            <Route path="/login" element={<Login />} />
          </Routes>

      </MantineProvider>
    </>
  )
}
```
<p>As soon as I remove the <code><Route path "/login" /></code> element, then my app starts working again.  So I conclude this is an incorrect way to use React Router.</p>
<p>What then is the proper way to achieve the result I'm looking for?  That is, I want the <code>Login</code> component to be rendered full-screen, without the "app shell".</p>
<p>Incidentally the React Router <code><BrowserRouter/></code> element is indeed present, and is rendered outside my <code><App /></code> element.  Thus my SPA is working correctly, as long as I remove that aforementioned <code>Login</code> route.  Also, my website is built with Vite - in case that is relevant.</p>
<h1>UPDATE</h1>
<p>I re-studied the react-router-dom documentation, and discovered what looks like the perfect solution for my need.  UNFORTUNATELY, the code feature I want doesn't work as documented.  I have simplified my original code into exactly what I need, which is this:</p>
<pre class="lang-js prettyprint-override"><code><Routes>
  <Route path="/" element={<button />}>
    <Route index element={<div>WARP</div>} />
    <Route path="drive" element={<div>DRIVE</div>} />
  </Route>
  <Route path="success" element={<div>SUCCESS</div>} />
</Routes>
</code>```

According to the documentation, the above should be able to give me a button labeled with either "WARP" or "DRIVE" depending on the route.  Instead, the button for those routes is rendered with no text at all!

I can force a partial result I'm looking for, minus the "success" path, with the following code:

<button>
  <Routes>
    <Route path="/" element={
WARP
} />
    <Route path="about" element={
DRIVE
} />
  </Routes>
</button>
```
<p>The above code works, but for only two of the three routes I want. Again, my ideal example is supposed to work - it comes directly from the documentation but doesn't work!</p>
<p>Any ideas?</p>
<p>My dependencies:</p>
```    "react-dom": "^18.2.0",
    "react-router-dom": "^6.6.1",
```

Body:
I want my React website normally to have an "app shell" (header, footer, sidebar with menu, etcetera) but for specific URI paths...I want those "app shell" elements to disappear.  I am new to React and React Router, so I came up with this (incorrect) solution:

import { OuterShell } from './OuterShell';
import Home from './home';
import About from './about';
import Login from './login';
import { Route, Routes } from "react-router-dom";

function App() {
  return (
    <>
      <MantineProvider withGlobalStyles withNormalizeCSS theme={{
        fontFamily: "fantasy",
        colorScheme: "dark"
      }}>

          <Routes>
            //This "OuterShell" contains my Mantine "App Shell" (header, footer, menu...).
            <OuterShell>
              <Route path="/" element={<Home />} />
              <Route path="/about" element={<About />} />
            </OuterShell>

            //HERE IS THE ISSUE...
            //I want this component path to render WITHOUT the "App Shell"
            <Route path="/login" element={<Login />} />
          </Routes>

      </MantineProvider>
    </>
  )
}

As soon as I remove the <Route path "/login" /> element, then my app starts working again.  So I conclude this is an incorrect way to use React Router.

What then is the proper way to achieve the result I'm looking for?  That is, I want the Login component to be rendered full-screen, without the "app shell".

Incidentally the React Router <BrowserRouter/> element is indeed present, and is rendered outside my <App /> element.  Thus my SPA is working correctly, as long as I remove that aforementioned Login route.  Also, my website is built with Vite - in case that is relevant.

UPDATE

I re-studied the react-router-dom documentation, and discovered what looks like the perfect solution for my need.  UNFORTUNATELY, the code feature I want doesn't work as documented.  I have simplified my original code into exactly what I need, which is this:

<Routes>
  <Route path="/" element={<button />}>
    <Route index element={
WARP
} />
    <Route path="drive" element={
DRIVE
} />
  </Route>
  <Route path="success" element={
SUCCESS
} />
</Routes>

According to the documentation, the above should be able to give me a button labeled with either "WARP" or "DRIVE" depending on the route.  Instead, the button for those routes is rendered with no text at all!

I can force a partial result I'm looking for, minus the "success" path, with the following code:

<button>
  <Routes>
    <Route path="/" element={
WARP
} />
    <Route path="about" element={
DRIVE
} />
  </Routes>
</button>

The above code works, but for only two of the three routes I want. Again, my ideal example is supposed to work - it comes directly from the documentation but doesn't work!

Any ideas?

My dependencies:

    "react-dom": "^18.2.0",
    "react-router-dom": "^6.6.1",


问:
How to implement Authentication using Riverpod in Flutter?
I have three providers for login => email, password, login.
then I am refreshing login provider which is a future provider and will call the login API.
now I need to see if the provider returns success then I will need to navigate to next page.
But .when() is not waiting for the refreshing to finish. Its logging "loading..." in the console.

`

```<code>ref.watch(email.notifier).state =
                                  emails.trim().toLowerCase();
                              ref.watch(password.notifier).state = passwords;
                              final loginstate = ref.refresh(login);
                              loginstate.when(data: ((data) {
                                // log(data + "here");
                                if (data == "Success") {
                                  context.go('/home');
                                }
                              }), error: (error, stackTrace) {
                                // log(error.toString() + "here");
                              }, loading: () {
                                log("loading....");
                              });
</code>```

`

I need to Navigate to the Home page upon successful API call.

Body:
I have three providers for login => email, password, login.
then I am refreshing login provider which is a future provider and will call the login API.
now I need to see if the provider returns success then I will need to navigate to next page.
But .when() is not waiting for the refreshing to finish. Its logging "loading..." in the console.

`

ref.watch(email.notifier).state =
                                  emails.trim().toLowerCase();
                              ref.watch(password.notifier).state = passwords;
                              final loginstate = ref.refresh(login);
                              loginstate.when(data: ((data) {
                                // log(data + "here");
                                if (data == "Success") {
                                  context.go('/home');
                                }
                              }), error: (error, stackTrace) {
                                // log(error.toString() + "here");
                              }, loading: () {
                                log("loading....");
                              });

`

I need to Navigate to the Home page upon successful API call.


问:
Run once time async code when start dev in Vue Cli
Recently I ran into a problem that it seems no one know how to solve.

I want to run async code (#1) when I ...

start dev ( i.e. npm run dev or npm run serve )

before compiling

That means, the async code can only run once!

And I can't use the feature of of "Service Plugin" (#2) in Vue Cli to do that.

Because it's async, I even can't use any webpack hook list here (#3)

BUT!

I knew that can be achieved by using Vite (#4)

I just out of idea how to do that in Vue CLI (after spent tons of hours)

Any expert have an idea?

Note

#1 This should be not important at all, because it's an implementation details, but I'll just leave it here: The async task for me is starting a local websocket server.

#2 Because you can write down async code in Service Plugin, for more info, check this

#3 You might see a webpack compiler hook called beforeRun can support async, but sorry, that also doesn't work for me.

#4 As shown here, you can see there's a method called configResolved, which can let you do async task, and achieve what I want as I described in this post. I'm not considering to choose Vite for just solving this problem, because this would be too overkill.


问:
Why does this capture limit set with regex fail by modifying substrings that it shouldn't?

import re

def date_to_internal_stored_format(input_text, identify_only_4_digit_years = False, limit_numbers_immediately_after_date = True):

    #grupo de captura para fechas en donde el año tiene si o si 4 digitos
    if (identify_only_4_digit_years == True):
        if(limit_numbers_immediately_after_date == True):
            date_capture_pattern = r"([12]\d{3}-[01]\d-[0-3]\d)(\D*?)"
        elif(limit_numbers_immediately_after_date == False):
            date_capture_pattern = r"([12]\d{3}-[01]\d-[0-3]\d)"

    input_text = re.sub(date_capture_pattern, lambda m: m.group().replace("-", "_-_", 2), input_text)

    return input_text

input_text = "el dia 2022-12-2344 o sino el dia 2022-09-23 10000-08-23"

input_text = date_to_internal_stored_format(input_text, False, True)

print(repr(input_text))
```
<p>Why doesn't the limit imposed behind work so that after the last number of the date there can be no more numbers to be considered a group that must be captured?</p>
<p>I need this output where <code>2022-12-23</code> is not captured I need this output where this is not captured, since there are more than 2 digits at the end of the date <code>(\D*?)</code></p>
<pre class="lang-py prettyprint-override"><code>'el dia 2022-12-2344 o sino el dia 2022_-_09_-_23 10000_-_08_-_23'
</code>```

Body:
import re

def date_to_internal_stored_format(input_text, identify_only_4_digit_years = False, limit_numbers_immediately_after_date = True):

    #grupo de captura para fechas en donde el año tiene si o si 4 digitos
    if (identify_only_4_digit_years == True):
        if(limit_numbers_immediately_after_date == True):
            date_capture_pattern = r"([12]\d{3}-[01]\d-[0-3]\d)(\D*?)"
        elif(limit_numbers_immediately_after_date == False):
            date_capture_pattern = r"([12]\d{3}-[01]\d-[0-3]\d)"

    input_text = re.sub(date_capture_pattern, lambda m: m.group().replace("-", "_-_", 2), input_text)

    return input_text

input_text = "el dia 2022-12-2344 o sino el dia 2022-09-23 10000-08-23"

input_text = date_to_internal_stored_format(input_text, False, True)

print(repr(input_text))

Why doesn't the limit imposed behind work so that after the last number of the date there can be no more numbers to be considered a group that must be captured?

I need this output where 2022-12-23 is not captured I need this output where this is not captured, since there are more than 2 digits at the end of the date (\D*?)

'el dia 2022-12-2344 o sino el dia 2022_-_09_-_23 10000_-_08_-_23'


问:
vscode SSH connect failed using SSH-remote extension but success by terminal
I'm trying to setup a ssh server using my win10 PC. After following steps to setup the server,  it is now can be connected via terminal from by laptop(win11).

However, if I use vscode extension Remote - SSH with connecting config :

```<code>Host 192.168.0.183
  HostName 192.168.0.183
  User User
  Port 22
</code>```

I always encounter Could not establish connection :

```<code>[23:49:42.494] Got password response
[23:49:42.494] "install" wrote data to terminal: "**********"
[23:49:42.521] >
[23:49:42.815] > powershell : �L�k���� 'powershell' ���J�O�_�� Cmdlet�B��ơB���O�ɩΥi����{�����W�١C���ˬd�W�٫��r�O�_���T�A�p�G�]�t
[23:49:42.826] > ��|���ܡA�нT�{��|�O�_���T�A�M��A�դ@���C
��� �u��:1 �r��:1
+ powershell
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (powershell:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

[23:49:44.124] "install" terminal command done
[23:49:44.125] Install terminal quit with output:
[23:49:44.126] Received install output:
[23:49:44.129] Resolver error: Error:
    at g.Create (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:583926)
    at c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:581767
    at t.handleInstallOutput (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:582462)
    at t.tryInstall (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:680469)
    at process.processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:642848
    at async t.withShowDetailsEvent (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:646166)
    at async t.resolve (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:643898)
    at async c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:723024
[23:49:44.138] -----
</code>```

Then I tried to use the laptop setting up as server and PC otherwise. It connect successfully with following output log :

```<code>[23:56:27.929] Got password response
[23:56:27.929] "install" wrote data to terminal: "************"
[23:56:27.951] >
[23:56:28.645] > Windows PowerShell
> Copyright (C) Microsoft Corporation. All rights reserved.
>
> Install the latest PowerShell for new features and improvements! https://aka.ms/
> PSWindowsPS C:\Users\lspss>
> PS C:\Users\lspss> $uuid="d68ebbafd913"
> PS C:\Users\lspss> "${uuid}: running"
> d68ebbafd913: running
> PS C:\Users\lspss> "d68ebbafd913: pauseLog"
> d68ebbafd913: pauseLog
</code>```

In comparison, the failed one have some random code I do not understand follow the powershell, while the other success after Windows Powershell.

I have tried to reinstall the ssh-server on my PC, and also tried using other laptop as client, which all failed.

Body:
I'm trying to setup a ssh server using my win10 PC. After following steps to setup the server,  it is now can be connected via terminal from by laptop(win11).

However, if I use vscode extension Remote - SSH with connecting config :

Host 192.168.0.183
  HostName 192.168.0.183
  User User
  Port 22

I always encounter Could not establish connection :

[23:49:42.494] Got password response
[23:49:42.494] "install" wrote data to terminal: "**********"
[23:49:42.521] >
[23:49:42.815] > powershell : �L�k���� 'powershell' ���J�O�_�� Cmdlet�B��ơB���O�ɩΥi����{�����W�١C���ˬd�W�٫��r�O�_���T�A�p�G�]�t
[23:49:42.826] > ��|���ܡA�нT�{��|�O�_���T�A�M��A�դ@���C
��� �u��:1 �r��:1
+ powershell
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (powershell:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

[23:49:44.124] "install" terminal command done
[23:49:44.125] Install terminal quit with output:
[23:49:44.126] Received install output:
[23:49:44.129] Resolver error: Error:
    at g.Create (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:583926)
    at c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:581767
    at t.handleInstallOutput (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:582462)
    at t.tryInstall (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:680469)
    at process.processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:642848
    at async t.withShowDetailsEvent (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:646166)
    at async t.resolve (c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:643898)
    at async c:\Users\lspss\.vscode\extensions\ms-vscode-remote.remote-ssh-0.94.0\out\extension.js:1:723024
[23:49:44.138] -----

Then I tried to use the laptop setting up as server and PC otherwise. It connect successfully with following output log :

[23:56:27.929] Got password response
[23:56:27.929] "install" wrote data to terminal: "************"
[23:56:27.951] >
[23:56:28.645] > Windows PowerShell
> Copyright (C) Microsoft Corporation. All rights reserved.
>
> Install the latest PowerShell for new features and improvements! https://aka.ms/
> PSWindowsPS C:\Users\lspss>
> PS C:\Users\lspss> $uuid="d68ebbafd913"
> PS C:\Users\lspss> "${uuid}: running"
> d68ebbafd913: running
> PS C:\Users\lspss> "d68ebbafd913: pauseLog"
> d68ebbafd913: pauseLog

In comparison, the failed one have some random code I do not understand follow the powershell, while the other success after Windows Powershell.

I have tried to reinstall the ssh-server on my PC, and also tried using other laptop as client, which all failed.


问:
Best way for terminating threads started by myself
I'm currently building a jar which runs inside of a parent. My project starts quite a lot of Threads which all get terminated in about 20-200ms (however have a possibility for being active for much longer). These threads can be started at any time during the process's runtime. Parent process has the ability to stop/restart sub programs. How can I terminate all active threads that I've started?

I've thought of making a list of all threads however that would quickly get cluttered with terminated threads.

How should I go about this?


问:
How to specify maximum condition for datetime-local type input field in react?
I have to get the start date-time and the end date-time from the user. But the end date-time should not be more than 12 hours from the start date-time. I want to restrict the end input field.

<TextField label="start time" type="datetime-local" required />

<TextField label="end time" type="datetime-local" required />


问:
How to store safely credentials to the mysql database and secrets
It bothers me that I have no idea how to store connection credentials to the mysql database and secrets for my flask app safely. Actually, I store them in plain text using environmental variables. I get those variables using python os module getenv. Also, I'm using uwsgi + nginx to serve my flask app. My goal is to prevent a hacker from accessing the database if he breaks into the server with mysql credentials (I got on my mysql server IP bind, however he can still execute the mysql request from the server).

I tried encrypting these variables and decrypting them on uwsgi startup by passing arguments, but it's not safe. I thought about using a shell script that ask me for a decryption key, then it runs a python script that decrypts credentials and saves them to a temp file. Then I run my app service and I delete the temp file with decrypted credentials. The second option seems good, but I want your suggestions.


问:
I am using provide/inject to pass the data within components , I've this function using compute, I am trying to run and pass it's result in provide
I have 4 functions, for 1st three functions, I can send the data in provide. For 4th function(

```<code>getViewApplicationDetails
</code>```

), I am trying to fetch api and get application name, now I want that in mounted because, I want the application name as soon as component is rendered so I am trying to execute it in mounted but when I call the it, it's giving me error. Initially application name is empty and it should have the current application name when I fetch the api, the same application name will be used in provide and then I can use that in inject and then in any other component.

```<code>import { computed, inject, onMounted, provide, reactive } from "vue";

export const initStore = () => {
  onMounted(()=>{
  this.getViewApplicationDetails()
  });
  // State
  const state = reactive({
    name: "Bob Day",
    email: "bob@martianmovers.com",
    applicationName: "",
    breadcrumbsData: [
      {
          name: "Home",
          text: 'Home',
          disabled: false,
          href: '/'
      }
    ]
  });
  // Getters
  const getUsername = computed(() => state.name);
  const getEmail = computed(() => console.log("state.email",state.email));
  const getBreadcrumbsData=computed(()=>state.breadcrumbsData)
  console.log("state.applicationName",state.applicationName)
  //this is the temporary function
  const getApplicationName=computed(()=>state.applicationName)
  const getViewApplicationDetails=computed(()=> {
    var viewApplicationDetailsParams = {
        applicationId: this.$route.query.applicationId,
        applicationStatus:this.$route.query.appStatus,
        authType: "api",
        clientId: process.env.VUE_APP_EXTERNAL_API_CLIENT_ID,
        clientSecret: process.env.VUE_APP_EXTERNAL_API_CLIENT_SECRET
    };
    axios({
        method: "post",
        url: process.env.VUE_APP_BLUJ_BACKEND_URL + "/viewapplicationDefinition",
        data: viewApplicationDetailsParams,
        headers: {
            "content-type": "application/json",
        },
    })
        .then((response) =>{
          this.viewDefinitionResponse = response.data.Definitions;
          let applicationName = viewDefinitionResponse.application_display_name.en;
          console.log("tyfgyhkjlfhgjklnm",applicationName)
          setApplicationName(applicationName)

        })
        .catch((error) => {
            console.log("error", error);
        });
});
getViewApplicationDetails()
  // Mutations
  const setUsername = (name) => {
    state.name = name;
  };
  const setEmail = (email) => {
    state.email = email;
  };

  const setBreadCrumbsData=(breadcrumbsData)=>{
    state.breadcrumbsData=breadcrumbsData;
  }
  const setApplicationName=(appName)=>{
    state.applicationName=appName
  }
  // Actions
  const updateUsername = (name) => {
    setUsername(name);
  };
  const updateEmail = (email) => {
    setEmail(email);
  };

  provide("getUsername", getUsername);
  provide("getEmail", getEmail);
  provide("updateUsername", updateUsername);
  provide("updateEmail", updateEmail);
  provide("getViewApplicationDetails", getViewApplicationDetails);
  provide("getApplicationName", getApplicationName);
  provide("getBreadcrumbsData", getBreadcrumbsData);
};

export const useStore = () => ({
  getUsername: inject("getUsername"),
  getEmail: inject("getEmail"),
  updateUsername: inject("updateUsername"),
  updateEmail: inject("updateEmail"),
  viewApplicationDetails: inject("getViewApplicationDetails"),
  getBreadcrumbsData: inject("getBreadcrumbsData"),
  getApplicationName: inject("getApplicationName")
});

</code>```

This is the code snippet.

```<code>  const getUsername = computed(() => state.name);
  const getEmail = computed(() => console.log("state.email",state.email));
  const getBreadcrumbsData=computed(()=>state.breadcrumbsData)
</code>```

I am getting data for this, but for getViewApplicationDetails, it's not working. While hovering over rest of the functions, it is showing "const getUsername: ComputedRef", like this. But, for getViewApplicationDetails, it shows "const getViewApplicationDetails: ComputedRef", this. I think it is not taking it as function or something. Error image is in the link.enter image description here

Body:
I have 4 functions, for 1st three functions, I can send the data in provide. For 4th function(

getViewApplicationDetails

), I am trying to fetch api and get application name, now I want that in mounted because, I want the application name as soon as component is rendered so I am trying to execute it in mounted but when I call the it, it's giving me error. Initially application name is empty and it should have the current application name when I fetch the api, the same application name will be used in provide and then I can use that in inject and then in any other component.

import { computed, inject, onMounted, provide, reactive } from "vue";

export const initStore = () => {
  onMounted(()=>{
  this.getViewApplicationDetails()
  });
  // State
  const state = reactive({
    name: "Bob Day",
    email: "bob@martianmovers.com",
    applicationName: "",
    breadcrumbsData: [
      {
          name: "Home",
          text: 'Home',
          disabled: false,
          href: '/'
      }
    ]
  });
  // Getters
  const getUsername = computed(() => state.name);
  const getEmail = computed(() => console.log("state.email",state.email));
  const getBreadcrumbsData=computed(()=>state.breadcrumbsData)
  console.log("state.applicationName",state.applicationName)
  //this is the temporary function
  const getApplicationName=computed(()=>state.applicationName)
  const getViewApplicationDetails=computed(()=> {
    var viewApplicationDetailsParams = {
        applicationId: this.$route.query.applicationId,
        applicationStatus:this.$route.query.appStatus,
        authType: "api",
        clientId: process.env.VUE_APP_EXTERNAL_API_CLIENT_ID,
        clientSecret: process.env.VUE_APP_EXTERNAL_API_CLIENT_SECRET
    };
    axios({
        method: "post",
        url: process.env.VUE_APP_BLUJ_BACKEND_URL + "/viewapplicationDefinition",
        data: viewApplicationDetailsParams,
        headers: {
            "content-type": "application/json",
        },
    })
        .then((response) =>{
          this.viewDefinitionResponse = response.data.Definitions;
          let applicationName = viewDefinitionResponse.application_display_name.en;
          console.log("tyfgyhkjlfhgjklnm",applicationName)
          setApplicationName(applicationName)

        })
        .catch((error) => {
            console.log("error", error);
        });
});
getViewApplicationDetails()
  // Mutations
  const setUsername = (name) => {
    state.name = name;
  };
  const setEmail = (email) => {
    state.email = email;
  };

  const setBreadCrumbsData=(breadcrumbsData)=>{
    state.breadcrumbsData=breadcrumbsData;
  }
  const setApplicationName=(appName)=>{
    state.applicationName=appName
  }
  // Actions
  const updateUsername = (name) => {
    setUsername(name);
  };
  const updateEmail = (email) => {
    setEmail(email);
  };

  provide("getUsername", getUsername);
  provide("getEmail", getEmail);
  provide("updateUsername", updateUsername);
  provide("updateEmail", updateEmail);
  provide("getViewApplicationDetails", getViewApplicationDetails);
  provide("getApplicationName", getApplicationName);
  provide("getBreadcrumbsData", getBreadcrumbsData);
};

export const useStore = () => ({
  getUsername: inject("getUsername"),
  getEmail: inject("getEmail"),
  updateUsername: inject("updateUsername"),
  updateEmail: inject("updateEmail"),
  viewApplicationDetails: inject("getViewApplicationDetails"),
  getBreadcrumbsData: inject("getBreadcrumbsData"),
  getApplicationName: inject("getApplicationName")
});

This is the code snippet.

  const getUsername = computed(() => state.name);
  const getEmail = computed(() => console.log("state.email",state.email));
  const getBreadcrumbsData=computed(()=>state.breadcrumbsData)

I am getting data for this, but for getViewApplicationDetails, it's not working. While hovering over rest of the functions, it is showing "const getUsername: ComputedRef", like this. But, for getViewApplicationDetails, it shows "const getViewApplicationDetails: ComputedRef", this. I think it is not taking it as function or something. Error image is in the link.enter image description here


问:
Disable biometry authentication on demand
I am trying to implement user-defined app locking mechanism with the help of BiometricManager. The app's config has a toggle which allows users to either enable or disable app lock. Once enabled, I want to use new biometric API. This part looks pretty straightforward to me, but I can not find any information about how to reset or disable the biometry settings for an app. This is how I do trigger biometry configuration being setup:

```<code>private val enableLock = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
   if (it.resultCode == Activity.RESULT_OK) {
       val value = it.data?.getStringExtra("input")
   }
}
...
val enrollIntent = Intent(Settings.ACTION_BIOMETRIC_ENROLL).apply {
  putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED, authentications)
}
enableLock.launch(enrollIntent)
</code>```

But once this method called on a preconfigured biometry, the resultCode is always RESULT_CANCEL, meaning API itself doesn't allow re-configuration. Any ideas?

Body:
I am trying to implement user-defined app locking mechanism with the help of BiometricManager. The app's config has a toggle which allows users to either enable or disable app lock. Once enabled, I want to use new biometric API. This part looks pretty straightforward to me, but I can not find any information about how to reset or disable the biometry settings for an app. This is how I do trigger biometry configuration being setup:

private val enableLock = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
   if (it.resultCode == Activity.RESULT_OK) {
       val value = it.data?.getStringExtra("input")
   }
}
...
val enrollIntent = Intent(Settings.ACTION_BIOMETRIC_ENROLL).apply {
  putExtra(Settings.EXTRA_BIOMETRIC_AUTHENTICATORS_ALLOWED, authentications)
}
enableLock.launch(enrollIntent)

But once this method called on a preconfigured biometry, the resultCode is always RESULT_CANCEL, meaning API itself doesn't allow re-configuration. Any ideas?


问:
WordPress Tools import failed downloading the installation package
I tried to download a package via Tools > Import, and then underneath the WordPress I clicked the "Install Now" link, but it gave me error messages like these:

```<code>Downloading installation package from https://downloads.wordpress.org/plugin/wordpress-importer.0.8.zip…
updates.min.js?ver=6.0.2:2 The authenticity of wordpress-importer.0.8.zip could not be verified as no signature was found.
updates.min.js?ver=6.0.2:2 Unpacking the package…
updates.min.js?ver=6.0.2:2 Could not copy file. wordpress-importer/class-wp-import.php
</code>```

To better understand it, see the image here:

if you notice it there are strange characters &#8230 at the end of the filename.

Does anyone know why it happens?

Body:
I tried to download a package via Tools > Import, and then underneath the WordPress I clicked the "Install Now" link, but it gave me error messages like these:

Downloading installation package from https://downloads.wordpress.org/plugin/wordpress-importer.0.8.zip…
updates.min.js?ver=6.0.2:2 The authenticity of wordpress-importer.0.8.zip could not be verified as no signature was found.
updates.min.js?ver=6.0.2:2 Unpacking the package…
updates.min.js?ver=6.0.2:2 Could not copy file. wordpress-importer/class-wp-import.php

To better understand it, see the image here:

if you notice it there are strange characters &#8230 at the end of the filename.

Does anyone know why it happens?


问:
Is there a way to produce a custom iOS keyboard like Grammarly's without writing the whole keyboard?
Title says it all, did grammarly really build all of their iOS keyboard functionality by themselves? or are there shortcuts by extending the default keyboard?</p>


问:
Animations brokes when adding aim offset to character
I have a anim bp in my game, inside here i have something like that:

My anim graph:

I want to make an anim offset. I creted the animations for that and i set the animations additive type to local space (and i also tried mesh space, and all the other options) and then selected anim frame

If i plug then UpperBody directly to then blend per bone it works normal but of course without the aim offset.

but if i add the AO_Amy to the Blend Pose 0 i'm getting this:

I don't know what i'm doing wrong, i'm working on this for 8 hours now and i can't find any tutorial or solution for this problem.

I followed many tutorials but i all shows the same thing that i'm doing and i want to find a solution as soon as possible


问:
2 Bulma questions - text absolute center and columns min-width
am new to Bulma and flex to be honest.

So i have the following code:

document.addEventListener('DOMContentLoaded', function () {

  // Get all "navbar-burger" elements
  var $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0);

  // Check if there are any nav burgers
  if ($navbarBurgers.length > 0) {

    // Add a click event on each of them
    $navbarBurgers.forEach(function ($el) {
      $el.addEventListener('click', function () {

        // Get the target from the "data-target" attribute
        var target = $el.dataset.target;
        var $target = document.getElementById(target);

        // Toggle the class on both the "navbar-burger" and the "navbar-menu"
        $el.classList.toggle('is-active');
        $target.classList.toggle('is-active');

      });
    });
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>@font-face {
    font-family: Pacifico;
    src: url(fonts/pacifico/Pacifico-Regular.ttf);
}

.pacifico {
    font-family: Pacifico;
    font-size:1.5em;
    color:red;
}

  .top_bg {background-image: url("https://png.pngtree.com/thumb_back/fw800/background/20200113/pngtree-ornate-cross-rhombus-repeating-symmetric-dark-blue-blue-and-white-tile-image_327096.jpg"); background-repeat:repeat-x;}
  .top_bg  div {height:125px;}
  .bottom_bg {background-image: url("images/bg_bottom_repeat.jpeg"); background-repeat:repeat-x;}
  // .bird { background-image: url("images/bird.png"); background-position: 50% 30%; background-attachment: inherit;}
  .under {text-decoration:underline;}
  .navbar-item.is-mega {
  position: static;

  .is-mega-menu-title {
    margin-bottom: 0;
    padding: .375rem 1rem;
  }
}
  </code>```

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>222</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">

<nobr>God save the Queen</nobr>

      1
      2
      3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce dictum ullamcorper felis, nec maximus est suscipit nec. Proin vulputate rutrum metus id mattis. Proin eget sapien lacus. Phasellus a elit ante. Donec accumsan vel elit id malesuada. Sed et cursus massa. Nullam feugiat iaculis laoreet.

Curabitur tristique interdum luctus. Proin rutrum augue ac porta aliquet. Suspendisse quis iaculis dolor. Sed nec arcu sapien. Phasellus vitae convallis risus. Donec vel consectetur nulla, aliquet lacinia leo. Nullam vitae mauris dolor. Etiam ac malesuada tellus, id lacinia felis. Fusce ut turpis metus. Maecenas in interdum nulla. Quisque faucibus vitae est ut euismod. Nullam eu lorem elementum, tempor felis quis, maximus sem. Sed at ipsum fringilla, cursus nunc sed, ullamcorper elit. Aenean eget tortor quam.

Aliquam id ex efficitur quam faucibus bibendum a quis augue. Suspendisse potenti. Maecenas neque lectus, sagittis vitae porta quis, consequat vel lorem. Aliquam vitae gravida justo. Aliquam at orci eget magna scelerisque lacinia. Mauris ornare tincidunt suscipit. Fusce scelerisque erat sit amet dui mattis facilisis. Etiam nec lectus rutrum, viverra purus ultricies, ullamcorper eros.

Suspendisse elementum justo ut enim imperdiet ultricies. Sed non dolor tincidunt, cursus nunc sed, fringilla ligula. Duis a commodo nulla. Fusce vulputate molestie porta. Pellentesque at ligula orci. Proin hendrerit commodo finibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque eleifend gravida libero, sed bibendum sem pulvinar vitae.

Fusce sapien nulla, hendrerit et congue quis, hendrerit sit amet risus. Ut dignissim sodales nunc, sit amet viverra libero sagittis quis. Ut porta porta dolor, non aliquet massa faucibus id. Sed faucibus mollis mollis. Curabitur scelerisque lorem dolor, vitae aliquet magna aliquam vitae. Suspendisse est lorem, feugiat sit amet leo nec, vestibulum convallis quam. Praesent vitae arcu dapibus, euismod augue quis, bibendum ligula. Vestibulum quis eros dui. Donec pharetra sapien ligula, vel egestas est ornare ut. Suspendisse hendrerit, velit ut fringilla bibendum, velit elit congue neque, id rhoncus risus sapien vel ligula. Donec laoreet faucibus nulla, sed varius erat tincidunt sed. Donec vitae mi magna. Maecenas mollis facilisis tellus id convallis. Quisque sit amet egestas erat, tincidunt pretium metus. In hac habitasse platea dictumst. Nulla non laoreet lacus.

```

The first question is how to center vertical text "God save the queen"? I've tried native Bulma classes as is-vcentered but no suсcess.

Second one - if my page is resized to a small mobile- size 2 columns that makes spaces at left / right in main section total disappear with no space left at all . Is there any build in classes for min-width or so?

We'll be appreciate for any kind of help.

Body:
am new to Bulma and flex to be honest.

So i have the following code:

document.addEventListener('DOMContentLoaded', function () {

  // Get all "navbar-burger" elements
  var $navbarBurgers = Array.prototype.slice.call(document.querySelectorAll('.navbar-burger'), 0);

  // Check if there are any nav burgers
  if ($navbarBurgers.length > 0) {

    // Add a click event on each of them
    $navbarBurgers.forEach(function ($el) {
      $el.addEventListener('click', function () {

        // Get the target from the "data-target" attribute
        var target = $el.dataset.target;
        var $target = document.getElementById(target);

        // Toggle the class on both the "navbar-burger" and the "navbar-menu"
        $el.classList.toggle('is-active');
        $target.classList.toggle('is-active');

      });
    });
  }

});

@font-face {
    font-family: Pacifico;
    src: url(fonts/pacifico/Pacifico-Regular.ttf);
}

.pacifico {
    font-family: Pacifico;
    font-size:1.5em;
    color:red;
}

  .top_bg {background-image: url("https://png.pngtree.com/thumb_back/fw800/background/20200113/pngtree-ornate-cross-rhombus-repeating-symmetric-dark-blue-blue-and-white-tile-image_327096.jpg"); background-repeat:repeat-x;}
  .top_bg  div {height:125px;}
  .bottom_bg {background-image: url("images/bg_bottom_repeat.jpeg"); background-repeat:repeat-x;}
  // .bird { background-image: url("images/bird.png"); background-position: 50% 30%; background-attachment: inherit;}
  .under {text-decoration:underline;}
  .navbar-item.is-mega {
  position: static;

  .is-mega-menu-title {
    margin-bottom: 0;
    padding: .375rem 1rem;
  }
}

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>222</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.4/css/bulma.min.css">

<nobr>God save the Queen</nobr>

      1
      2
      3

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce dictum ullamcorper felis, nec maximus est suscipit nec. Proin vulputate rutrum metus id mattis. Proin eget sapien lacus. Phasellus a elit ante. Donec accumsan vel elit id malesuada. Sed et cursus massa. Nullam feugiat iaculis laoreet.

Curabitur tristique interdum luctus. Proin rutrum augue ac porta aliquet. Suspendisse quis iaculis dolor. Sed nec arcu sapien. Phasellus vitae convallis risus. Donec vel consectetur nulla, aliquet lacinia leo. Nullam vitae mauris dolor. Etiam ac malesuada tellus, id lacinia felis. Fusce ut turpis metus. Maecenas in interdum nulla. Quisque faucibus vitae est ut euismod. Nullam eu lorem elementum, tempor felis quis, maximus sem. Sed at ipsum fringilla, cursus nunc sed, ullamcorper elit. Aenean eget tortor quam.

Aliquam id ex efficitur quam faucibus bibendum a quis augue. Suspendisse potenti. Maecenas neque lectus, sagittis vitae porta quis, consequat vel lorem. Aliquam vitae gravida justo. Aliquam at orci eget magna scelerisque lacinia. Mauris ornare tincidunt suscipit. Fusce scelerisque erat sit amet dui mattis facilisis. Etiam nec lectus rutrum, viverra purus ultricies, ullamcorper eros.

Suspendisse elementum justo ut enim imperdiet ultricies. Sed non dolor tincidunt, cursus nunc sed, fringilla ligula. Duis a commodo nulla. Fusce vulputate molestie porta. Pellentesque at ligula orci. Proin hendrerit commodo finibus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Quisque eleifend gravida libero, sed bibendum sem pulvinar vitae.

Fusce sapien nulla, hendrerit et congue quis, hendrerit sit amet risus. Ut dignissim sodales nunc, sit amet viverra libero sagittis quis. Ut porta porta dolor, non aliquet massa faucibus id. Sed faucibus mollis mollis. Curabitur scelerisque lorem dolor, vitae aliquet magna aliquam vitae. Suspendisse est lorem, feugiat sit amet leo nec, vestibulum convallis quam. Praesent vitae arcu dapibus, euismod augue quis, bibendum ligula. Vestibulum quis eros dui. Donec pharetra sapien ligula, vel egestas est ornare ut. Suspendisse hendrerit, velit ut fringilla bibendum, velit elit congue neque, id rhoncus risus sapien vel ligula. Donec laoreet faucibus nulla, sed varius erat tincidunt sed. Donec vitae mi magna. Maecenas mollis facilisis tellus id convallis. Quisque sit amet egestas erat, tincidunt pretium metus. In hac habitasse platea dictumst. Nulla non laoreet lacus.

The first question is how to center vertical text "God save the queen"? I've tried native Bulma classes as is-vcentered but no suсcess.

Second one - if my page is resized to a small mobile- size 2 columns that makes spaces at left / right in main section total disappear with no space left at all . Is there any build in classes for min-width or so?

We'll be appreciate for any kind of help.


问:
NodeJS express serve static page, then throw 404 error
I'm running an app with Node.js and Express. I created the skeleton of the project with Express Generator. Here is a section of the generated code:

```<code>app.use(express.static(path.join(__dirname, 'public')));

// Create routes
app.use('/', indexRouter);
app.use('/data', dataRouter);
app.use('/api', apiRouter);

// Catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// Error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  console.log ('ERROR :', err.status);
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
</code>```

When a static page is served, It continues and generates a 404 error. In the browser everything is fine, but in the Node.js logs, I can see the console.log('ERROR). Why the engine does not stop when a static page is served? How to solve it?

Body:
I'm running an app with Node.js and Express. I created the skeleton of the project with Express Generator. Here is a section of the generated code:

app.use(express.static(path.join(__dirname, 'public')));

// Create routes
app.use('/', indexRouter);
app.use('/data', dataRouter);
app.use('/api', apiRouter);

// Catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// Error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  console.log ('ERROR :', err.status);
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

When a static page is served, It continues and generates a 404 error. In the browser everything is fine, but in the Node.js logs, I can see the console.log('ERROR). Why the engine does not stop when a static page is served? How to solve it?


问:
tensorflow only predicts '[UNK]' characters
I am trying to generate text in a certain style using tensorflow, and even when I copy and paste the code from the tensorflow website it only predicts unknown characters even though there is a mask to prevent this. I'm thinking it has something to do with the version of python I'm running (3.9.15) since it doesnt even work with their code and dataset.

Has anyone else run into this issue?

```<code>class OneStep(tf.keras.Model):
  def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0):
    super().__init__()
    self.temperature = temperature
    self.model = model
    self.chars_from_ids = chars_from_ids
    self.ids_from_chars = ids_from_chars

    # Create a mask to prevent "[UNK]" from being generated.
    skip_ids = self.ids_from_chars(['[UNK]'])[:, None]
    sparse_mask = tf.SparseTensor(
        # Put a -inf at each bad index.
        values=[-float('inf')]*len(skip_ids),
        indices=skip_ids,
        # Match the shape to the vocabulary
        dense_shape=[len(ids_from_chars.get_vocabulary())])
    self.prediction_mask = tf.sparse.to_dense(sparse_mask)

  @tf.function
  def generate_one_step(self, inputs, states=None):
    # Convert strings to token IDs.
    input_chars = tf.strings.unicode_split(inputs, 'UTF-8')
    input_ids = self.ids_from_chars(input_chars).to_tensor()

    # Run the model.
    # predicted_logits.shape is [batch, char, next_char_logits]
    predicted_logits, states = self.model(inputs=input_ids, states=states,
                                          return_state=True)
    # Only use the last prediction.
    predicted_logits = predicted_logits[:, -1, :]
    predicted_logits = predicted_logits/self.temperature
    # Apply the prediction mask: prevent "[UNK]" from being generated.
    predicted_logits = predicted_logits + self.prediction_mask

    # Sample the output logits to generate token IDs.
    predicted_ids = tf.random.categorical(predicted_logits, num_samples=1)
    predicted_ids = tf.squeeze(predicted_ids, axis=-1)

    # Convert from token ids to characters
    predicted_chars = self.chars_from_ids(predicted_ids)

    # Return the characters and model state.
    return predicted_chars, states
</code>```

I lifted this straight from their tutorial and tried to run it in my enviroment and it just predicted '[UNK]'

I'm running a mac M1 with the latest version of tensorflow. So, that may also be an issue.

PLEASE HELP!!

Tutorial for reference: https://www.tensorflow.org/text/tutorials/text_generation

Body:
I am trying to generate text in a certain style using tensorflow, and even when I copy and paste the code from the tensorflow website it only predicts unknown characters even though there is a mask to prevent this. I'm thinking it has something to do with the version of python I'm running (3.9.15) since it doesnt even work with their code and dataset.

Has anyone else run into this issue?

class OneStep(tf.keras.Model):
  def __init__(self, model, chars_from_ids, ids_from_chars, temperature=1.0):
    super().__init__()
    self.temperature = temperature
    self.model = model
    self.chars_from_ids = chars_from_ids
    self.ids_from_chars = ids_from_chars

    # Create a mask to prevent "[UNK]" from being generated.
    skip_ids = self.ids_from_chars(['[UNK]'])[:, None]
    sparse_mask = tf.SparseTensor(
        # Put a -inf at each bad index.
        values=[-float('inf')]*len(skip_ids),
        indices=skip_ids,
        # Match the shape to the vocabulary
        dense_shape=[len(ids_from_chars.get_vocabulary())])
    self.prediction_mask = tf.sparse.to_dense(sparse_mask)

  @tf.function
  def generate_one_step(self, inputs, states=None):
    # Convert strings to token IDs.
    input_chars = tf.strings.unicode_split(inputs, 'UTF-8')
    input_ids = self.ids_from_chars(input_chars).to_tensor()

    # Run the model.
    # predicted_logits.shape is [batch, char, next_char_logits]
    predicted_logits, states = self.model(inputs=input_ids, states=states,
                                          return_state=True)
    # Only use the last prediction.
    predicted_logits = predicted_logits[:, -1, :]
    predicted_logits = predicted_logits/self.temperature
    # Apply the prediction mask: prevent "[UNK]" from being generated.
    predicted_logits = predicted_logits + self.prediction_mask

    # Sample the output logits to generate token IDs.
    predicted_ids = tf.random.categorical(predicted_logits, num_samples=1)
    predicted_ids = tf.squeeze(predicted_ids, axis=-1)

    # Convert from token ids to characters
    predicted_chars = self.chars_from_ids(predicted_ids)

    # Return the characters and model state.
    return predicted_chars, states

I lifted this straight from their tutorial and tried to run it in my enviroment and it just predicted '[UNK]'

I'm running a mac M1 with the latest version of tensorflow. So, that may also be an issue.

PLEASE HELP!!

Tutorial for reference: https://www.tensorflow.org/text/tutorials/text_generation


问:
Updating a profile image in django
so I have this issue when trying to update a profile photo in django.
The Profile photo actually updates if I upload an image. But there are cases where a user may want to update other details on the profile update page without having to update the profile photo.
Trying to implement that gave me a multivalue error.
I've been on it for some time now, Please, who knows how I can handle that.

```<code>Here's my code on views.py file

def profile_update(request, user_id):
    if request.method == 'POST':
        user_obj = User.objects.get(id=user_id)
        user_profile_obj = UserProfile.objects.get(user=user_id)

        user_img = request.FILES['user_img']
        username = request.POST["username"]
        email = request.POST["email"]
        phone = request.POST["phone"]
        address = request.POST["address"]

        fs_handle = FileSystemStorage()
        img_name = 'uploads/profile_pictures/user_{0}'.format(user_id)
        if fs_handle.exists(img_name):
            fs_handle.delete(img_name)
        fs_handle.save(img_name, user_img)

        user_profile_obj.profile_pic = img_name

        user_profile_obj.phone = phone
        user_profile_obj.address = address
        user_profile_obj.save()

        user_obj.username =  username
        user_obj.email = email
        user_obj.save()
        user_obj.refresh_from_db()

</code>```

Here's my models.py file
`

```<code>class UserProfile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    address = models.CharField(max_length=65, null=True, blank=True)
    phone = models.CharField(max_length=65, null=True, blank=True)
    profile_pic = models.FileField(null=True, blank=True, upload_to="uploads/profile_pictures", validators = [FileExtensionValidator(allowed_extensions=['jpg','jpeg','png'])])

    def __str__(self):
        return str(self.user)
</code>```

`

Title: Updating a profile image in django

Body:
so I have this issue when trying to update a profile photo in django.
The Profile photo actually updates if I upload an image. But there are cases where a user may want to update other details on the profile update page without having to update the profile photo.
Trying to implement that gave me a multivalue error.
I've been on it for some time now, Please, who knows how I can handle that.

Here's my code on views.py file

def profile_update(request, user_id):
    if request.method == 'POST':
        user_obj = User.objects.get(id=user_id)
        user_profile_obj = UserProfile.objects.get(user=user_id)

        user_img = request.FILES['user_img']
        username = request.POST["username"]
        email = request.POST["email"]
        phone = request.POST["phone"]
        address = request.POST["address"]

        fs_handle = FileSystemStorage()
        img_name = 'uploads/profile_pictures/user_{0}'.format(user_id)
        if fs_handle.exists(img_name):
            fs_handle.delete(img_name)
        fs_handle.save(img_name, user_img)

        user_profile_obj.profile_pic = img_name

        user_profile_obj.phone = phone
        user_profile_obj.address = address
        user_profile_obj.save()

        user_obj.username =  username
        user_obj.email = email
        user_obj.save()
        user_obj.refresh_from_db()

Here's my models.py file
`

class UserProfile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    address = models.CharField(max_length=65, null=True, blank=True)
    phone = models.CharField(max_length=65, null=True, blank=True)
    profile_pic = models.FileField(null=True, blank=True, upload_to="uploads/profile_pictures", validators = [FileExtensionValidator(allowed_extensions=['jpg','jpeg','png'])])

    def __str__(self):
        return str(self.user)

`


问:
unity app crashes, when login with google using firebase
I am trying to add a 'sign in with google' option to my app, using firebase. However when I click the button which calls the sign in script on my android device, the app crashes and closes completely.

I cannot run this script in the editor. so is there another way of finding out what the error is?

I am using the script found here https://www.dropbox.com/s/qss2wk4v52d48j4/GoogleSignInDemo.cs?dl=0 and have taken the web client id from my firebase project, and enabled google sign in.

I have also added the sha1 fingerprint to my firebase project and have copied the google-services.json file to my unity project. I am using Unity 2020.1.6f1 My firebase packages are version 10.2.0 and the google sign in plugin 1.0.4

I have no idea why it's not working please help me.I finding the solution but no result

[Solved]
I upgrade my pc windows 7 to windows 10 and upgrade unity 2020 to unity 2021 then it automatically fix and work.Thanks for all


问:
How can I make a button in TipTap to insert a carriage return (enter keystroke)

Problem

When I use the hard break, it only adds a new line or
, but does not split off into a new
 element. I want it to split into a new element because I am doing further modifications on a per-element basis.

The .splitBlock() effectively splits the
 tag. This would be perfect, except it doesn't split ordered or unordered list elements.

Consider the example below

How can I extend TipTap's HardBreak to act like a carriage return (enter key)?

```<code>1. Lorem Ipsum Delor

2. //Line 1
   //Line 2
   THIS ONE IS NOT A NEW <LI>, IT IS JUST A "\n" or </br> AS IF I PRESSED (SHIFT + ENTER)

3. Lorem Ipsum Delor
</code>```

Would it be best to extend the hard break? What about extending .splitBlock? Is there a way to press the enter keystroke with a button and skip this whole extension discussion?

Body:
Problem

When I use the hard break, it only adds a new line or
, but does not split off into a new
 element. I want it to split into a new element because I am doing further modifications on a per-element basis.

The .splitBlock() effectively splits the
 tag. This would be perfect, except it doesn't split ordered or unordered list elements.

Consider the example below

How can I extend TipTap's HardBreak to act like a carriage return (enter key)?

1. Lorem Ipsum Delor

2. //Line 1
   //Line 2
   THIS ONE IS NOT A NEW
, IT IS JUST A "\n" or
 AS IF I PRESSED (SHIFT + ENTER)

3. Lorem Ipsum Delor

Would it be best to extend the hard break? What about extending .splitBlock? Is there a way to press the enter keystroke with a button and skip this whole extension discussion?


问:
Defined attributes that are seemingly not used at all for instance objects of some loss classes
I will try to explain my question using an example.
Consider the definition of the BinaryCrossentropy loss class as shown in the following.

```<code>@keras_export("keras.losses.BinaryCrossentropy")
class BinaryCrossentropy(LossFunctionWrapper):
    def __init__(
        self,
        from_logits=False,
        label_smoothing=0.0,
        axis=-1,
        reduction=losses_utils.ReductionV2.AUTO,
        name="binary_crossentropy",
    ):
        super().__init__(
            binary_crossentropy,
            name=name,
            reduction=reduction,
            from_logits=from_logits,
            label_smoothing=label_smoothing,
            axis=axis,
        )
        self.from_logits = from_logits
</code>```

Why defining the attribute of from_logits for an instance object?
My understanding is that for an instance object, the attributes of fn, name, and reduction are assigned within the __init__ method of LossFunctionWrapper (Source code for LossFunctionWrapper) by passing the corresponding arguments to super().__init__ from inside the __init__ method of the loss class (BinaryCrossentropy in this example).
The rest of the keyword argumets (from_logits, label_smoothing, and axis) are assigned to self._fn_kwargs to be passed on to fn when the instance is called.

Why does an instance object of BinaryCrossentropy need to have the attribute of from_logits while (my understanding is that) this attribute is not used anywhere except within fn, which is already provided with the required value? The BinaryFocalCrossentropy class seems to have a similar issue. I would be grateful if someone could please clarify.

Body:
I will try to explain my question using an example.
Consider the definition of the BinaryCrossentropy loss class as shown in the following.

@keras_export("keras.losses.BinaryCrossentropy")
class BinaryCrossentropy(LossFunctionWrapper):
    def __init__(
        self,
        from_logits=False,
        label_smoothing=0.0,
        axis=-1,
        reduction=losses_utils.ReductionV2.AUTO,
        name="binary_crossentropy",
    ):
        super().__init__(
            binary_crossentropy,
            name=name,
            reduction=reduction,
            from_logits=from_logits,
            label_smoothing=label_smoothing,
            axis=axis,
        )
        self.from_logits = from_logits

Why defining the attribute of from_logits for an instance object?
My understanding is that for an instance object, the attributes of fn, name, and reduction are assigned within the __init__ method of LossFunctionWrapper (Source code for LossFunctionWrapper) by passing the corresponding arguments to super().__init__ from inside the __init__ method of the loss class (BinaryCrossentropy in this example).
The rest of the keyword argumets (from_logits, label_smoothing, and axis) are assigned to self._fn_kwargs to be passed on to fn when the instance is called.

Why does an instance object of BinaryCrossentropy need to have the attribute of from_logits while (my understanding is that) this attribute is not used anywhere except within fn, which is already provided with the required value? The BinaryFocalCrossentropy class seems to have a similar issue. I would be grateful if someone could please clarify.


问:
What draws the line between reflective programming & non-reflective programming like simple softcoding?
Not sure if this is the right place to bring up this kind of discussion but, Im reading https://en.wikipedia.org/wiki/Reflective_programming and feel I need a bit further clarification for where the line between "reflective" & non-reflective programming really goes. Theres a series of examples of reflective v non-reflective code towards the end of the wikipedia page where all the "reflective" examples seem to access data with string identifiers - but what would actually differentiate this from say putting a bunch of objects in a collection/array of some sort and accessing them by an index - say compared to accessing them by an array of string identifiers that you can use to fetch the desired object?

In some languages you can clearly see the difference & benefit, like in Python & JS they have the eval method that lets them insert all sorts of code at runtime that can be pretty much endlessly complex and completely change the code flow of an application - and no longer limited to accessing mere special type objects. But in the examples listed on the wiki page you can also find examples where the "reflection" seems limited only to accessing specially declared objects by there name (at which point Im questioning if you can really argue that the program really can be considered to be "modifying" itself at all, at least on a high level in conceptual point of view).

Does the way that the underlying machinery producd by the compiler (or the way that the interpreter reads your code) affect whats considered to be reflective?

Is the ability of redefining the contents of existing objects or declaring new objects without a "base class"/preexisting structure created at compile time that  differentiates reflective & non-reflective code? If so, how would this play with the examples at the wikipedia page that doesnt seem to showcase this ability?

Can the meaning of "reflective programming" vary slightly depending on the scenario?

Any thoughts appreciated <3


问:
How to authenticate Springboot API based on User role that is being fetched from DB
I have user role saved in DB, so based on role ID authentication has to be done for each API.

I tried few approaches but did not succeed.

Code Snippet:

CONTROLLER:

```<code>    @PreAuthorize("@AuthService.getUserRole(1)")
    @PostMapping(name = "POST - Save the user info to Automation Counter table", path = "userlogininfo")
    @Operation(summary = "Save the user info to Automation Counter table")
    public ResponseEntity<ApiResponse> saveUserInfoinDB(@RequestBody SaveUserInfo saveUserInfoDetails, Principal principal)
    {

        try
        {
            saveUserInfoDetails.ntid = principal.getName().split("\\n")[0];
            if (saveUserInfoDetails.firstName != null && saveUserInfoDetails.lastName != null && saveUserInfoDetails.ntid != null && saveUserInfoDetails.applicationName !=null)
            {
                ApiResponse apiResponse = restService.osmAPIPost("/dashboard/userlogininfo",saveUserInfoDetails);
                return ResponseEntity.ok(apiResponse);
            }
            else
            {
                ApiResponse response = new ApiResponse<>(false, "Did not receive data in correct format", null);
                return ResponseEntity.badRequest().body(response);
            }
        }
        catch (Exception ex)
        {
            String logMessage = SharedUtils.logErrorMessage(this.getClass().getSimpleName(), ex, "Error while saving user info in DB.");
            ApiResponse response = new ApiResponse<>(false, logMessage, null);
            return ResponseEntity.badRequest().body(response);
        }
    }
</code>```

SERVICE:

```<code> @Service
public class AuthService {

    private  final AuthRepository authRepository;

    public AuthService(AuthRepository authRepository)
    {

        this.authRepository = authRepository;
    }

    public boolean getUserRole(int roleId)
    {
        try
        {
              boolean userRole=authRepository.getUserLoginInfo(Principal.class.getName().split("\\n")[0],roleId);
              return userRole;
        }
        catch (Exception ex)
        {
           throw ex;
        }
    }
}
</code>```

REPOSITORY:

```<code>@Transactional
    public boolean getUserLoginInfo(String ntid, int roleId )
    {
        try
        {
            String returnValue=null;
            String sql = "SELECT Alias FROM Users where NTID=? AND RoleId=?" ;
             returnValue=  osmv2JdbcTemplate.queryForObject(sql,String.class,ntid,roleId);
            if(returnValue!=null)
            {
                return  true;
            }
            else
            {
                return  false;
            }
        }
        catch(Exception ex)
        {
            String logMessage = SharedUtils.logErrorMessage(this.getClass().getSimpleName(), ex, "Could not fetch the User alias based on role ID and NTID from DB");
            LOGGER.info(logMessage);
            return false;
        }

    }
</code>```

I have created custom method that will be used in @PreAuthorize but it did not work. The method is fetching the role id from DB based on username.Please help.. Thanks in advance:)

Body:
I have user role saved in DB, so based on role ID authentication has to be done for each API.

I tried few approaches but did not succeed.

Code Snippet:

CONTROLLER:

    @PreAuthorize("@AuthService.getUserRole(1)")
    @PostMapping(name = "POST - Save the user info to Automation Counter table", path = "userlogininfo")
    @Operation(summary = "Save the user info to Automation Counter table")
    public ResponseEntity<ApiResponse> saveUserInfoinDB(@RequestBody SaveUserInfo saveUserInfoDetails, Principal principal)
    {

        try
        {
            saveUserInfoDetails.ntid = principal.getName().split("\\n")[0];
            if (saveUserInfoDetails.firstName != null && saveUserInfoDetails.lastName != null && saveUserInfoDetails.ntid != null && saveUserInfoDetails.applicationName !=null)
            {
                ApiResponse apiResponse = restService.osmAPIPost("/dashboard/userlogininfo",saveUserInfoDetails);
                return ResponseEntity.ok(apiResponse);
            }
            else
            {
                ApiResponse response = new ApiResponse<>(false, "Did not receive data in correct format", null);
                return ResponseEntity.badRequest().body(response);
            }
        }
        catch (Exception ex)
        {
            String logMessage = SharedUtils.logErrorMessage(this.getClass().getSimpleName(), ex, "Error while saving user info in DB.");
            ApiResponse response = new ApiResponse<>(false, logMessage, null);
            return ResponseEntity.badRequest().body(response);
        }
    }

SERVICE:

 @Service
public class AuthService {

    private  final AuthRepository authRepository;

    public AuthService(AuthRepository authRepository)
    {

        this.authRepository = authRepository;
    }

    public boolean getUserRole(int roleId)
    {
        try
        {
              boolean userRole=authRepository.getUserLoginInfo(Principal.class.getName().split("\\n")[0],roleId);
              return userRole;
        }
        catch (Exception ex)
        {
           throw ex;
        }
    }
}

REPOSITORY:

@Transactional
    public boolean getUserLoginInfo(String ntid, int roleId )
    {
        try
        {
            String returnValue=null;
            String sql = "SELECT Alias FROM Users where NTID=? AND RoleId=?" ;
             returnValue=  osmv2JdbcTemplate.queryForObject(sql,String.class,ntid,roleId);
            if(returnValue!=null)
            {
                return  true;
            }
            else
            {
                return  false;
            }
        }
        catch(Exception ex)
        {
            String logMessage = SharedUtils.logErrorMessage(this.getClass().getSimpleName(), ex, "Could not fetch the User alias based on role ID and NTID from DB");
            LOGGER.info(logMessage);
            return false;
        }

    }

I have created custom method that will be used in @PreAuthorize but it did not work. The method is fetching the role id from DB based on username.Please help.. Thanks in advance:)


问:
How to access a static method in a different static class in Razor?
I have a helper class for accessing the database, however I can't access it from the code portion in my razor page

```<code>using MongoDB.Driver;
using OsrsPriceHistory.Models;

namespace OsrsPriceHistory.Helpers
{
    public static class DBConnection
    {
        private static OsrsDatabaseSettings databaseSettings = new OsrsDatabaseSettings();
        private static MongoClient? mongoClient;
        public static IMongoDatabase getDatabase()
        {
            if (mongoClient == null)
            {
                mongoClient = new MongoClient(databaseSettings.ConnectionString);
            }

            var database = mongoClient.GetDatabase("OsrsPrices");

            return database;
        }
    }
}
</code>```

and another class (razor page) I am trying to access the static method in

```<code>@page "/"
@using OsrsPriceHistory.Helpers

<PageTitle>Prices</PageTitle>

<h1> Prices</h1>

@code {

    DBConnection.

}
</code>```

However I get the error "The name 'DBConnection' does not exist in the current context and the error "The name 'getDatabase' does not exist in the current context."

I'm unsure what's wrong since I seem to be implementing static correctly

Body:
I have a helper class for accessing the database, however I can't access it from the code portion in my razor page

using MongoDB.Driver;
using OsrsPriceHistory.Models;

namespace OsrsPriceHistory.Helpers
{
    public static class DBConnection
    {
        private static OsrsDatabaseSettings databaseSettings = new OsrsDatabaseSettings();
        private static MongoClient? mongoClient;
        public static IMongoDatabase getDatabase()
        {
            if (mongoClient == null)
            {
                mongoClient = new MongoClient(databaseSettings.ConnectionString);
            }

            var database = mongoClient.GetDatabase("OsrsPrices");

            return database;
        }
    }
}

and another class (razor page) I am trying to access the static method in

@page "/"
@using OsrsPriceHistory.Helpers

<PageTitle>Prices</PageTitle>

 Prices

@code {

    DBConnection.

}

However I get the error "The name 'DBConnection' does not exist in the current context and the error "The name 'getDatabase' does not exist in the current context."

I'm unsure what's wrong since I seem to be implementing static correctly


问:
Display a window (dialog) above a system app
I am developing an App Locker for android. Everything works except for when you try to delete an app, the popup does not appear. I tried to force the lock-screen dialog to appear manually from within the app, but the results were crashes and ANRs.
I thought to myself that the popup is not available because the packageInstaller (System app) is using the screen at the same time, and it gets more priority.
Another thing is that when I cancel an uninstall, packageInstaller goes away and then my display appears for a fraction of a second and then disappears. Note that this is after, I need it to be present before, or even while the packageInstaller is running.

My question is if it is possible to put my window at a certain priority, so that goes even above the system app?

In my app check service, in my method that's on repeat constantly I had:
`

```<code>if (mpackageName.equals("com.google.android.packageinstaller")) {

        showUnlockDialog();
 }
</code>```

however, this caused my lock-display to get opened a lot of times (because of the repeat), which caused the app to become irresponsive. What I now have (after omitting) is the dialog appearing after, at the end then going away on its own.

This is my show dialog method:
`

```<code>{
if (context == null) {
    context = getApplicationContext();
}
LayoutInflater layoutInflater = LayoutInflater.from(context);
@SuppressLint("InflateParams") View promptsView;

promptsView = layoutInflater.inflate(R.layout.popup_unlock, null, false);
Lock9View lock9View = (Lock9View) promptsView.findViewById(R.id.lock_9_view);
Button forgetPassword = (Button) promptsView.findViewById(R.id.forgetPassword);
LinearLayout linearLayout = promptsView.findViewById(R.id.popup_background);
TextView textView = promptsView.findViewById(R.id.textView);
linearLayout.setBackgroundResource(R.drawable.gradient_list);
textView.setTextColor(getResources().getColor(R.color.colorWhite));
forgetPassword.setTextColor(getResources().getColor(R.color.colorWhite));
animateBanner1(linearLayout);
lock9View = (Lock9View) promptsView.findViewById(R.id.lock_10_view);
lock9View.setVisibility(View.VISIBLE);
lock9View.setCallBack(new Lock9View.CallBack() {
    @Override
    public void onFinish(String password) {
        if (password.matches(sharedPreference.getPassword(context))) {
            dialog.dismiss();

        } else {
            Toast.makeText(context, "Wrong pattern, try again", Toast.LENGTH_SHORT).show();
        }
    }
});

forgetPassword.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent i = new Intent(AppCheckServices.this, PasswordRecoveryActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
        dialog.dismiss();
    }
});
 dialog = new Dialog(context, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    dialog.setCanceledOnTouchOutside(false);
    dialog.setCancelable(false);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);

    }
    else {
        Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_PHONE);
    }
    dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
    dialog.setContentView(promptsView);
    dialog.getWindow().setGravity(Gravity.CENTER);

    dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode,
                             KeyEvent event) {

            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_UP) {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
            }
            return true;
        }
    });

}
dialog.show();
}
</code>```

As I said this works on every other app besides the packageInstaller even if I specifically lock it.

Here are my relevant Manifest Permissions:

```<code><uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission
    android:name="android.permission.INTERNAL_SYSTEM_WINDOW"
    tools:ignore="ProtectedPermissions" />
<uses-permission
    android:name="android.permission.PACKAGE_USAGE_STATS"
    tools:ignore="ProtectedPermissions" />
</code>```

From What I understand, the highest "setType()" for the window manager is the:

```<code>SYSTEM_ALERT_WINDOW
</code>```

It allows to have the top most display. I thought that by using this, I could block the packageInstaller.
However this too requires special permission (2003 from the crashes), and does not get granted easily.

I would appreciate any help in regard to this matter and can post anything else that is relevant.
Thanks in advance!

`

Body:
I am developing an App Locker for android. Everything works except for when you try to delete an app, the popup does not appear. I tried to force the lock-screen dialog to appear manually from within the app, but the results were crashes and ANRs.
I thought to myself that the popup is not available because the packageInstaller (System app) is using the screen at the same time, and it gets more priority.
Another thing is that when I cancel an uninstall, packageInstaller goes away and then my display appears for a fraction of a second and then disappears. Note that this is after, I need it to be present before, or even while the packageInstaller is running.

My question is if it is possible to put my window at a certain priority, so that goes even above the system app?

In my app check service, in my method that's on repeat constantly I had:
`

if (mpackageName.equals("com.google.android.packageinstaller")) {

        showUnlockDialog();
 }

however, this caused my lock-display to get opened a lot of times (because of the repeat), which caused the app to become irresponsive. What I now have (after omitting) is the dialog appearing after, at the end then going away on its own.

This is my show dialog method:
`

{
if (context == null) {
    context = getApplicationContext();
}
LayoutInflater layoutInflater = LayoutInflater.from(context);
@SuppressLint("InflateParams") View promptsView;

promptsView = layoutInflater.inflate(R.layout.popup_unlock, null, false);
Lock9View lock9View = (Lock9View) promptsView.findViewById(R.id.lock_9_view);
Button forgetPassword = (Button) promptsView.findViewById(R.id.forgetPassword);
LinearLayout linearLayout = promptsView.findViewById(R.id.popup_background);
TextView textView = promptsView.findViewById(R.id.textView);
linearLayout.setBackgroundResource(R.drawable.gradient_list);
textView.setTextColor(getResources().getColor(R.color.colorWhite));
forgetPassword.setTextColor(getResources().getColor(R.color.colorWhite));
animateBanner1(linearLayout);
lock9View = (Lock9View) promptsView.findViewById(R.id.lock_10_view);
lock9View.setVisibility(View.VISIBLE);
lock9View.setCallBack(new Lock9View.CallBack() {
    @Override
    public void onFinish(String password) {
        if (password.matches(sharedPreference.getPassword(context))) {
            dialog.dismiss();

        } else {
            Toast.makeText(context, "Wrong pattern, try again", Toast.LENGTH_SHORT).show();
        }
    }
});

forgetPassword.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent i = new Intent(AppCheckServices.this, PasswordRecoveryActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(i);
        dialog.dismiss();
    }
});
 dialog = new Dialog(context, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    dialog.setCanceledOnTouchOutside(false);
    dialog.setCancelable(false);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);

    }
    else {
        Objects.requireNonNull(dialog.getWindow()).setType(WindowManager.LayoutParams.TYPE_PHONE);
    }
    dialog.getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT);
    dialog.setContentView(promptsView);
    dialog.getWindow().setGravity(Gravity.CENTER);

    dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode,
                             KeyEvent event) {

            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getAction() == KeyEvent.ACTION_UP) {
                Intent startMain = new Intent(Intent.ACTION_MAIN);
                startMain.addCategory(Intent.CATEGORY_HOME);
                startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(startMain);
            }
            return true;
        }
    });

}
dialog.show();
}

As I said this works on every other app besides the packageInstaller even if I specifically lock it.

Here are my relevant Manifest Permissions:

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission
    android:name="android.permission.INTERNAL_SYSTEM_WINDOW"
    tools:ignore="ProtectedPermissions" />
<uses-permission
    android:name="android.permission.PACKAGE_USAGE_STATS"
    tools:ignore="ProtectedPermissions" />

From What I understand, the highest "setType()" for the window manager is the:

SYSTEM_ALERT_WINDOW

It allows to have the top most display. I thought that by using this, I could block the packageInstaller.
However this too requires special permission (2003 from the crashes), and does not get granted easily.

I would appreciate any help in regard to this matter and can post anything else that is relevant.
Thanks in advance!

`


问:
How do I only display the BLE name and not the mac address in MIT App Inventor?
I followed a tutorial and did this simple block of code that scans for BLE devices:This is what I had

However, I'm wondering if there is a way to hide the MAC addresses of scanned devices. I would just like the name so that the list looks cleaner. Thank you in advance.

I only looked up a solution but couldn't find much, other than redesigning so that you input a name rather than scan for all devices nearby. That isn't what I'm looking to do.


问:
How can I fix Flask bootstrap javascript vulnerabilties?
I am using Flask with boostrap version Flask-Bootstrap==3.3.7.1 for my webapp.

Lighthouse is telling me these are vulnerable:

```<code>Bootstrap@3.3.7
jQuery@1.12.4
</code>```

My code that is related to these is very minimal and looks like this:

index.html

```<code>{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
...
</code>```

base.html

```<code>{% block head %}
{{ super() }}
{% endblock %}
...
{% block scripts %}
{{ super() }}
{% endblock %}
</code>```

When I inspect the html code I see that these are being including with the super():

```<code>//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js
//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js
</code>```

How can I fix this? My flask-boostrap is already at the most recent version.

Body:
I am using Flask with boostrap version Flask-Bootstrap==3.3.7.1 for my webapp.

Lighthouse is telling me these are vulnerable:

Bootstrap@3.3.7
jQuery@1.12.4

My code that is related to these is very minimal and looks like this:

index.html

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
...

base.html

{% block head %}
{{ super() }}
{% endblock %}
...
{% block scripts %}
{{ super() }}
{% endblock %}

When I inspect the html code I see that these are being including with the super():

//cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js
//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js

How can I fix this? My flask-boostrap is already at the most recent version.